text
stringlengths
10
2.72M
package com.tencent.mm.plugin.setting.ui.setting; import android.os.Bundle; import com.tencent.mm.model.q; import com.tencent.mm.plugin.setting.a.g; import com.tencent.mm.plugin.setting.a.i; import com.tencent.mm.plugin.setting.model.k; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.base.preference.MMPreference; import com.tencent.mm.ui.base.preference.Preference; import com.tencent.mm.ui.base.preference.f; public class SettingsPluginsNotifyUI extends MMPreference { private f eOE; private int state; public void onCreate(Bundle bundle) { super.onCreate(bundle); initView(); } public void onResume() { super.onResume(); btS(); } public final int Ys() { return -1; } public final boolean a(f fVar, Preference preference) { String str = preference.mKey; if (str.equals("settings_plugings_disturb_on")) { vR(0); } if (str.equals("settings_plugings_disturb_on_night")) { vR(1); } if (str.equals("settings_plugings_disturb_off")) { vR(2); } return false; } private void btS() { this.eOE.removeAll(); Preference preference = new Preference(this); preference.setTitle(i.settings_plugings_disturb_on); preference.setKey("settings_plugings_disturb_on"); preference.setLayoutResource(g.mm_preference); if (this.state == 0) { preference.setWidgetLayoutResource(g.mm_preference_radio_checked); } else { preference.setWidgetLayoutResource(g.mm_preference_radio_unchecked); } this.eOE.a(preference); preference = new Preference(this); preference.setTitle(i.settings_plugings_disturb_on_night); preference.setKey("settings_plugings_disturb_on_night"); preference.setLayoutResource(g.mm_preference); if (this.state == 1) { preference.setWidgetLayoutResource(g.mm_preference_radio_checked); } else { preference.setWidgetLayoutResource(g.mm_preference_radio_unchecked); } this.eOE.a(preference); preference = new Preference(this); preference.setTitle(i.settings_plugings_disturb_off); preference.setKey("settings_plugings_disturb_off"); preference.setLayoutResource(g.mm_preference); if (this.state == 2) { preference.setWidgetLayoutResource(g.mm_preference_radio_checked); } else { preference.setWidgetLayoutResource(g.mm_preference_radio_unchecked); } this.eOE.a(preference); preference = new Preference(this); preference.setTitle(i.settings_plugings_disturb_time_tip); preference.setLayoutResource(g.mm_preference_info); this.eOE.a(preference); this.eOE.notifyDataSetChanged(); } private void vR(int i) { this.state = i; if (this.state == 1 || this.state == 0) { com.tencent.mm.kernel.g.Ei().DT().set(8200, Boolean.valueOf(true)); if (this.state == 1) { com.tencent.mm.kernel.g.Ei().DT().set(8201, Integer.valueOf(22)); com.tencent.mm.kernel.g.Ei().DT().set(8208, Integer.valueOf(8)); ((com.tencent.mm.plugin.messenger.foundation.a.i) com.tencent.mm.kernel.g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FQ().b(new k(true, 22, 8)); } else { com.tencent.mm.kernel.g.Ei().DT().set(8201, Integer.valueOf(0)); com.tencent.mm.kernel.g.Ei().DT().set(8208, Integer.valueOf(0)); ((com.tencent.mm.plugin.messenger.foundation.a.i) com.tencent.mm.kernel.g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FQ().b(new k(true, 0, 0)); } } else { com.tencent.mm.kernel.g.Ei().DT().set(8200, Boolean.valueOf(false)); ((com.tencent.mm.plugin.messenger.foundation.a.i) com.tencent.mm.kernel.g.l(com.tencent.mm.plugin.messenger.foundation.a.i.class)).FQ().b(new k()); } btS(); } protected final void initView() { Boolean valueOf = Boolean.valueOf(q.Hb()); int Hj = q.Hj(); int Hk = q.Hk(); if (valueOf.booleanValue()) { this.state = Hj == Hk ? 0 : 1; } else { this.state = 2; } x.d("ui.settings.SettingsPlugingsNotify", valueOf + "st " + Hj + " ed " + Hk + " state " + this.state); this.state = this.state; this.eOE = this.tCL; setMMTitle(i.settings_plugings_disturb_title); setBackBtn(new 1(this)); } }
package p3; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; public class P3 { private ArrayList<Integer> deck = new ArrayList<>(); private int n; /*public static void main(String[] args) { P3 p3 = new P3(); p3.readFile("input1.txt"); p3.doAlgorithm(); }*/ public void readFile(String inputFile) { try { BufferedReader reader = new BufferedReader(new FileReader(inputFile)); n = Integer.parseInt(reader.readLine()); for(int i= 0; i < n; i++) deck.add(-1); reader.close(); }catch (Exception e) { System.out.println("Error while reading the file"); } } public void doAlgorithm() { int numbers = n; int numberToPut = 0; boolean put = true; while(numbers> 0) { if(numbers< n) { if ( n%2==0) put=true; } for(int i = 0;i< deck.size(); i++) { if(deck.get(i)==-1) { if(put) { deck.set(i, numberToPut); numberToPut++; numbers--; put=!put; }else { put = !put; } } } } deck.forEach(x -> System.out.print(x + " ")); } }
/* * LumaQQ - Java QQ Client * * Copyright (C) 2004 luma <stubma@163.com> * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.tsinghua.lumaqq.ui.helper; import edu.tsinghua.lumaqq.models.Cluster; import edu.tsinghua.lumaqq.models.Organization; import edu.tsinghua.lumaqq.models.User; import edu.tsinghua.lumaqq.ui.BrowserShell; import edu.tsinghua.lumaqq.ui.CheckUpdateShell; import edu.tsinghua.lumaqq.ui.IPSeekerWindow; import edu.tsinghua.lumaqq.ui.InfoManagerWindow; import edu.tsinghua.lumaqq.ui.LastLoginTipWindow; import edu.tsinghua.lumaqq.ui.MainShell; import edu.tsinghua.lumaqq.ui.MemberEditShell; import edu.tsinghua.lumaqq.ui.ReceiveIMWindow; import edu.tsinghua.lumaqq.ui.ReceiveSystemMessageShell; import edu.tsinghua.lumaqq.ui.SMSWindow; import edu.tsinghua.lumaqq.ui.SendClusterIMWindow; import edu.tsinghua.lumaqq.ui.SendIMTabWindow; import edu.tsinghua.lumaqq.ui.SendIMWindow; import edu.tsinghua.lumaqq.ui.SystemMessageListWindow; import edu.tsinghua.lumaqq.ui.TempSessionIMWindow; import edu.tsinghua.lumaqq.ui.WeatherWindow; import edu.tsinghua.lumaqq.ui.config.cluster.ClusterInfoWindow; import edu.tsinghua.lumaqq.ui.config.face.FaceWindow; import edu.tsinghua.lumaqq.ui.config.sys.SystemOptionWindow; import edu.tsinghua.lumaqq.ui.config.user.UserInfoWindow; import edu.tsinghua.lumaqq.ui.wizard.WizardWindow; import edu.tsinghua.lumaqq.ui.wizard.cluster.ClusterWizard; import edu.tsinghua.lumaqq.ui.wizard.search.SearchWizard; /** * Shell factory class, to encapsulate some creation code * * @author luma */ public class ShellFactory { /** * 创建临时会话消息窗口 * * @param main * @param f * @return */ public static TempSessionIMWindow createTempSessionIMWindow(MainShell main, User f) { TempSessionIMWindow win = new TempSessionIMWindow(main, f); main.getShellRegistry().addTempSessionIMWindow(f, win); return win; } /** * 创建天气预报窗口 * * @param main * @return */ public static WeatherWindow createWeatherWindow(MainShell main) { WeatherWindow window = new WeatherWindow(main); main.getShellRegistry().registerWeatherWindow(window); return window; } /** * 创建短信窗口 * * @param main * MainShell * @return * SMSWindow */ public static SMSWindow createSMSWindow(MainShell main) { SMSWindow window = new SMSWindow(main); main.getShellRegistry().registerSMSWindow(window); return window; } /** * 创建短信窗口 * * @param main * MainShell * @param friend * 用户model * @return * SMSWindow */ public static SMSWindow createSMSWindow(MainShell main, User friend) { SMSWindow window = new SMSWindow(main, friend); main.getShellRegistry().addSMSWindow(friend, window); return window; } /** * 创建短信窗口 * * @param main * MainShell * @param mobile * 手机号码 * @return * SMSWindow */ public static SMSWindow createSMSWindow(MainShell main, String mobile) { SMSWindow window = new SMSWindow(main, mobile); main.getShellRegistry().addSMSWindow(mobile, window); return window; } /** * 创建信息管理器窗口 * * @param main * @return */ public static InfoManagerWindow createInfoManagerWindow(MainShell main) { return new InfoManagerWindow(main); } /** * 创建一个查看消息窗口 * * @return * 查看消息窗口 */ public static ReceiveIMWindow createReceiveIMWindow(MainShell main, User f) { ReceiveIMWindow rms = new ReceiveIMWindow(main, f); main.getShellRegistry().addReceiveIMWindow(f, rms); return rms; } /** * 创建一个发送消息窗口 * * @return * 发送消息窗口 */ public static SendIMWindow createSendIMWindow(MainShell main, User f) { SendIMWindow sms = new SendIMWindow(main, f); main.getShellRegistry().addSendIMWindow(f, sms); return sms; } /** * 创建一个群消息发送窗口 * * @param main * MainShell * @return * 群消息发送窗口 */ public static SendClusterIMWindow createSendClusterIMWindow(MainShell main, Cluster c) { return new SendClusterIMWindow(main, c); } /** * 创建一个消息发送标签页窗口 * * @param main * MainShell * @return * SendIMTabWindow */ public static SendIMTabWindow createSendIMTabWindow(MainShell main) { SendIMTabWindow window = new SendIMTabWindow(main); return window; } /** * 创建一个系统消息列表窗口 * * @param main * MainShell * @return * 系统消息列表窗口 */ public static SystemMessageListWindow createSystemMessageListWindow(MainShell main) { return new SystemMessageListWindow(main); } /** * 创建一个搜索窗口 * * @param main * MainShell * @param startPage * 起始页 * @return * 搜索窗口 */ public static WizardWindow createSearchWizard(MainShell main) { SearchWizard wizard = new SearchWizard(); WizardWindow window = new WizardWindow(main, wizard); wizard.init(main); window.create(); return window; } /** * 创建一个创建群向导 * * @param main * MainShell * @return * 群向导 */ public static WizardWindow createClusterWizard(MainShell main) { ClusterWizard wizard = new ClusterWizard(); WizardWindow window = new WizardWindow(main, wizard); wizard.init(main); window.create(); return window; } /** * 创建一个系统设置窗口 * * @param main * MainShell * @return * 系统设置窗口 */ public static SystemOptionWindow createSystemOptionWindow(MainShell main) { return new SystemOptionWindow(main); } /** * 创建一个检测更新窗口 * * @param main * MainShell * @return * 检测更新窗口 */ public static CheckUpdateShell createCheckUpdateShell(MainShell main) { return new CheckUpdateShell(main); } /** * 创建一个查看系统消息窗口 * * @param main * MainShell * @return * 查看系统消息窗口 */ public static ReceiveSystemMessageShell createReceiveSystemMessageShell(MainShell main) { return new ReceiveSystemMessageShell(main); } /** * 创建一个IP查询窗口 * * @param main * MainShell * @return * IP查询窗口 */ public static IPSeekerWindow createIPSeekerWindow(MainShell main) { return new IPSeekerWindow(main); } /** * 创建一个临时群/组织信息编辑窗口 * * @param main * @param type * @param parentCluster * @param parentOrganization * @return */ public static MemberEditShell createMemberEditShell(MainShell main, int type, Cluster parentCluster, Organization parentOrganization) { MemberEditShell shell = new MemberEditShell(main, type); shell.setParentCluster(parentCluster); shell.setParentOrganization(parentOrganization); return shell; } /** * 创建一个群资料窗口 * * @param main * MainShell * @return * 群资料窗口 */ public static ClusterInfoWindow createClusterInfoWindow(MainShell main, Cluster c) { if(c.isCreator(main.getMyModel().qq)) return new ClusterInfoWindow(main, c, ClusterInfoWindow.EDITABLE_CREATOR); else if(c.isSuperMember(main.getMyModel().qq)) return new ClusterInfoWindow(main, c, ClusterInfoWindow.EDITABLE_ADMIN); else return new ClusterInfoWindow(main, c, ClusterInfoWindow.READ_ONLY); } /** * 创建一个浏览器窗口 * * @param main * MainShell * @return * 浏览器窗口 */ public static BrowserShell createBrowserShell(MainShell main) { return new BrowserShell(main); } /** * 创建一个好友资料窗口 * * @param main * MainShell * @param model * 好友model * @param style * 窗口样式 * @return * 好友资料窗口 */ public static UserInfoWindow createUserInfoWindow(MainShell main, User model, int style) { return new UserInfoWindow(main, model, style); } /** * 创建一个表情管理窗口 * * @param main * MainShell * @return * FaceWindow对象 */ public static FaceWindow createFaceWindow(MainShell main) { return new FaceWindow(main); } /** * 创建一个上次登录信息提示窗口 * * @param main * @return */ public static LastLoginTipWindow createLastLoginTipWindow(MainShell main) { return new LastLoginTipWindow(main); } }
package PrimeGenerator; import static java.lang.System.out; import java.util.ArrayList; import java.util.BitSet; public class SieveofEratosthenesPrimeFounder extends PrimeAlgo { public SieveofEratosthenesPrimeFounder(int from, int until) { super(from, until); this.primes = findPrimes(until); } @Override public ArrayList<Integer> findPrimes(int until) { BitSet bitset = null; ArrayList<Integer> primes = null; try { bitset = new BitSet(until); } catch (Exception e) { out.println("Upper Boundry is invalid.\n\nPlease try a Upper Boundry " + "which is greater than 0 and lower Boundry"); return null; } for (int prime = 2; prime * prime <= until; prime++) { if (!bitset.get(prime)) { // out.println(prime); for (int j = prime * prime; j <= until; j += prime) { bitset.set(j); } } } primes = getPrimes(bitset, until); return primes; } public ArrayList<Integer> getPrimes(BitSet bitset, int until) { int clearIndex; ArrayList<Integer> primes = new ArrayList<>(); // out.println(bitset); clearIndex = bitset.nextClearBit(2) + 1; while (clearIndex <= bitset.length()) { // out.println("found "+(clearIndex-1)); primes.add(clearIndex - 1); clearIndex = bitset.nextClearBit(clearIndex) + 1; } return primes; } }
package com.tencent.mm.plugin.webview.model; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import java.util.HashMap; public final class ae { private static ae pRO = new ae(); HashMap<String, WebViewJSSDKFileItem> pRP = new HashMap(); public static final ae bUk() { return pRO; } public final void b(WebViewJSSDKFileItem webViewJSSDKFileItem) { if (webViewJSSDKFileItem == null || bi.oW(webViewJSSDKFileItem.bNH)) { x.e("MicroMsg.WebViewJSSDKFileItemManager", "item is null or local id is null, ignore this add"); return; } x.i("MicroMsg.WebViewJSSDKFileItemManager", "add jssdk file item, local id : %s, file path : %s", new Object[]{webViewJSSDKFileItem.bNH, webViewJSSDKFileItem.fnM}); this.pRP.put(webViewJSSDKFileItem.bNH, webViewJSSDKFileItem); } public final WebViewJSSDKFileItem Qq(String str) { if (!bi.oW(str)) { return (WebViewJSSDKFileItem) this.pRP.get(str); } x.e("MicroMsg.WebViewJSSDKFileItemManager", "get by local id error, local id is null or nil"); return null; } }
package jdk8; import java.util.ArrayList; /** * @author yinchao * @date 2020/12/7 20:12 */ public class ArrayListTest { public static void main (String[] args) { ArrayList<Integer> arrayList; } }
package com.fansolomon.Structural.Bridge.Shape.impl; import com.fansolomon.Structural.Bridge.Shape.DrawAPI; /** * ConcreteImplementor * 实现Implementor接口并定义它的具体实现 */ public class DrawGreen implements DrawAPI { @Override public void drawColor(String content) { System.out.println("Drawing Circle[ color: green, content: " + content +"]"); } }
package com.tencent.mm.g.c; import android.content.ContentValues; import android.database.Cursor; import com.tencent.mm.sdk.e.c; import com.tencent.mm.sdk.e.c.a; import java.lang.reflect.Field; public abstract class cy extends c { private static final int cHK = "musicId".hashCode(); private static final int cJD = "musicUrl".hashCode(); private static final int cJE = "indexBitData".hashCode(); private static final int cJF = "fileCacheComplete".hashCode(); private static final int cJG = "pieceFileMIMEType".hashCode(); public static final String[] ciG = new String[0]; private static final int ciP = "rowid".hashCode(); private static final int czu = "fileName".hashCode(); private boolean cHd = true; private boolean cJA = true; private boolean cJB = true; private boolean cJC = true; private boolean cJz = true; private boolean cyZ = true; public int field_fileCacheComplete; public String field_fileName; public byte[] field_indexBitData; public String field_musicId; public String field_musicUrl; public String field_pieceFileMIMEType; public static a wI() { a aVar = new a(); aVar.sKy = new Field[6]; aVar.columns = new String[7]; StringBuilder stringBuilder = new StringBuilder(); aVar.columns[0] = "musicId"; aVar.sKA.put("musicId", "TEXT PRIMARY KEY "); stringBuilder.append(" musicId TEXT PRIMARY KEY "); stringBuilder.append(", "); aVar.sKz = "musicId"; aVar.columns[1] = "musicUrl"; aVar.sKA.put("musicUrl", "TEXT"); stringBuilder.append(" musicUrl TEXT"); stringBuilder.append(", "); aVar.columns[2] = "fileName"; aVar.sKA.put("fileName", "TEXT"); stringBuilder.append(" fileName TEXT"); stringBuilder.append(", "); aVar.columns[3] = "indexBitData"; aVar.sKA.put("indexBitData", "BLOB"); stringBuilder.append(" indexBitData BLOB"); stringBuilder.append(", "); aVar.columns[4] = "fileCacheComplete"; aVar.sKA.put("fileCacheComplete", "INTEGER"); stringBuilder.append(" fileCacheComplete INTEGER"); stringBuilder.append(", "); aVar.columns[5] = "pieceFileMIMEType"; aVar.sKA.put("pieceFileMIMEType", "TEXT"); stringBuilder.append(" pieceFileMIMEType TEXT"); aVar.columns[6] = "rowid"; aVar.sql = stringBuilder.toString(); return aVar; } public final void d(Cursor cursor) { String[] columnNames = cursor.getColumnNames(); if (columnNames != null) { int length = columnNames.length; for (int i = 0; i < length; i++) { int hashCode = columnNames[i].hashCode(); if (cHK == hashCode) { this.field_musicId = cursor.getString(i); this.cHd = true; } else if (cJD == hashCode) { this.field_musicUrl = cursor.getString(i); } else if (czu == hashCode) { this.field_fileName = cursor.getString(i); } else if (cJE == hashCode) { this.field_indexBitData = cursor.getBlob(i); } else if (cJF == hashCode) { this.field_fileCacheComplete = cursor.getInt(i); } else if (cJG == hashCode) { this.field_pieceFileMIMEType = cursor.getString(i); } else if (ciP == hashCode) { this.sKx = cursor.getLong(i); } } } } public final ContentValues wH() { ContentValues contentValues = new ContentValues(); if (this.cHd) { contentValues.put("musicId", this.field_musicId); } if (this.cJz) { contentValues.put("musicUrl", this.field_musicUrl); } if (this.cyZ) { contentValues.put("fileName", this.field_fileName); } if (this.cJA) { contentValues.put("indexBitData", this.field_indexBitData); } if (this.cJB) { contentValues.put("fileCacheComplete", Integer.valueOf(this.field_fileCacheComplete)); } if (this.cJC) { contentValues.put("pieceFileMIMEType", this.field_pieceFileMIMEType); } if (this.sKx > 0) { contentValues.put("rowid", Long.valueOf(this.sKx)); } return contentValues; } }
package com.mygdx.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.graphics.Texture; import java.util.List; /** * Created by on 26.07.14. */ public class Player extends Collidable { private int moveSpeed = 5; private int jumpSpeed = 12; private int smallJumpSpeed = 7; private float playerGravity = 0.5f; private float verticalSpeed = 0.0f; public Player(int x, int y, int w, int h, Texture sprite) { super(x, y, w, h, sprite); } public void step(List<Object> objects) { boolean canJump = gravity(objects) == -1; boolean leftKey = Gdx.input.isKeyPressed(Input.Keys.A); boolean rightKey = Gdx.input.isKeyPressed(Input.Keys.D); boolean upKey = Gdx.input.isKeyPressed(Input.Keys.W); if (leftKey && rightKey) { return; } if (leftKey) { goLeft(objects); } if (rightKey) { goRight(objects); } if (upKey && canJump) { jump(); } if (!upKey) { stopJump(); } } private void jump() { if (verticalSpeed == 0) { verticalSpeed = jumpSpeed; } } private void stopJump() { if (verticalSpeed > smallJumpSpeed) { verticalSpeed = smallJumpSpeed; } } private int gravity(List<Object> objects) { int weCollided = 0; verticalSpeed -= playerGravity; if (verticalSpeed > getH()) { verticalSpeed = getH(); } setY(getY() + Math.round(verticalSpeed)); for (Object next : objects) { if (next instanceof Player) continue; if (next instanceof Collidable) { if (this.rectangle.overlaps(((Collidable) next).getRectangle())) { while (this.rectangle.overlaps(((Collidable) next).getRectangle())) { if (verticalSpeed > 0) { weCollided = 1; setY(getY() - 1); } else { weCollided = -1; setY(getY() + 1); } } verticalSpeed = 0; } } } return weCollided; } private void goRight(List<Object> objects) { setX(getX() + moveSpeed); int i; for (Object next : objects) { if (next instanceof Player) continue; if (next instanceof Collidable) { for (i = 0; i < moveSpeed; i++) { if (this.rectangle.overlaps(((Collidable) next).getRectangle())) { setX(getX() - 1); } } } } } private void goLeft(List<Object> objects) { setX(getX() - moveSpeed); int i; for (Object next : objects) { if (next instanceof Player) continue; if (next instanceof Collidable) { for (i = 0; i < moveSpeed; i++) { if (this.rectangle.overlaps(((Collidable) next).getRectangle())) { setX(getX() + 1); } } } } } }
package com.canby.command.commands.power; import com.canby.command.Command; import com.canby.command.interfaces.HasPower; /** * Created by acanby on 6/11/2014. */ public abstract class AbstractPowerCommand implements Command { protected final HasPower hasPower; public AbstractPowerCommand(HasPower hasPower) { this.hasPower = hasPower; } protected void turnOff() { hasPower.turnOff(); } protected void turnOn() { hasPower.turnOn(); } }
package com.tencent.mm.protocal; import com.tencent.mm.protocal.c.g; public class c$go extends g { public c$go() { super("reportActionInfo", "reportActionInfo", 234, false); } }
package ru.javabegin.training.webservices.main; import ru.javabegin.training.webservices.parsers.StaxParser; public class Start { public static void main(String[] args) { String xmlPath = "c:\\test\\people2.xml"; // new DomParser().parse(xmlPath); // new SaxParser().parse(xmlPath); new StaxParser().parse(xmlPath); } }
package com.example.ahmed.octopusmart.Model.ServiceModels; import java.io.Serializable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import org.apache.commons.lang.builder.ToStringBuilder; public class UserRateModel implements Serializable { @SerializedName("rate") @Expose private double rate; @SerializedName("user_count") @Expose private Long userCount; private final static long serialVersionUID = 2585601833525808412L; public double getRate() { return rate; } public void setRate(Long rate) { this.rate = rate; } public Long getUserCount() { return userCount; } public void setUserCount(Long userCount) { this.userCount = userCount; } @Override public String toString() { return new ToStringBuilder(this).append("rate", rate).append("userCount", userCount).toString(); } }
package com.espendwise.manta.web.tags; import com.espendwise.manta.util.Constants; import com.espendwise.manta.util.alert.AppLocale; import com.espendwise.manta.util.arguments.ArgumentType; import com.espendwise.manta.util.parser.AppParserException; import com.espendwise.manta.util.parser.Parse; import com.espendwise.manta.web.util.AppI18nUtil; import javax.servlet.jsp.JspException; public class MothWithDayFormatTag extends AppFormatTag{ @Override public int doStartTag() throws JspException { setType(ArgumentType.MONTH_WITH_DAY); return super.doStartTag(); } @Override public Object retrieveValue() { Object value = getValue(); if (value instanceof String) { try { return Parse.parseMonthWithDay((String) value, Constants.NOT_LEAP_YEAR, AppLocale.SYSTEM_LOCALE); } catch (AppParserException e) { e.printStackTrace(); return AppI18nUtil.getMessage("admin.global.text.wrongValue", new Object[]{value}); } } return super.retrieveValue(); } }
package main.java.breakingPointTool.calculations; import java.sql.SQLException; import java.util.ArrayList; public class OptimalArtifactC { private double optimalComplexity; // private double optimalNumOfFunctions; private double optimalLinesOfCode; //private double optimalCommentsDensity; private double optimalCoupling; private double optimalCohesion; public void calculateOptimalClass(ArrayList<FindSimilarArtifactsC> similarClasses, int version) throws SQLException { ArrayList<OptimalArtifactC > optimalClassesList = new ArrayList<OptimalArtifactC >(); for (int i = 0; i < similarClasses.size(); i++) { OptimalArtifactC optimClass = new OptimalArtifactC (); // Values from considered class double complexity = similarClasses.get(i).getName().getComplexity(); double linesOfCode = similarClasses.get(i).getName().getNcloc(); double coupling = similarClasses.get(i).getName().getCoupling(); double cohesion = similarClasses.get(i).getName().getCohesion(); //double functions = similarClasses.get(i).getName().getNumOfFunctions(); //double commentsDensity = similarClasses.get(i).getName().getCommentsDensity(); //System.out.println("Arxikopoihsh optimal: " + complexity + " " + functions + " " + linesOfCode + " " + commentsDensity); System.out.println("Find optimal for class: " + similarClasses.get(i).getName().getClassName()); // Check only the 5 or less most similar int sizeOfArtifacts = similarClasses.get(i).getSimilarClasses().size(); if (sizeOfArtifacts > 5) sizeOfArtifacts = 4; for (int j = 0; j < sizeOfArtifacts; j++) { System.out.println("Class name: " + similarClasses.get(i).getSimilarClasses().get(j).getClassName() ); /*System.out.println("Ypoloipes times: " + similarClasses.get(i).getSimilarClasses().get(j).getComplexity() + " " + similarClasses.get(i).getSimilarClasses().get(j).getNumOfFunctions() + " "+ similarClasses.get(i).getSimilarClasses().get(j).getNcloc() + " " + similarClasses.get(i).getSimilarClasses().get(j).getCommentsDensity()); */ /* if (similarClasses.get(i).getSimilarClasses().get(j).getComplexity() + similarClasses.get(i).getSimilarClasses().get(j).getNumOfFunctions() + similarClasses.get(i).getSimilarClasses().get(j).getNcloc() + similarClasses.get(i).getSimilarClasses().get(j).getCommentsDensity() == 0) { continue; } if (similarClasses.get(i).getSimilarClasses().get(j).getCommentsDensity() == 100.0) { continue; }*/ if (similarClasses.get(i).getSimilarClasses().get(j).getComplexity() < complexity) complexity = similarClasses.get(i).getSimilarClasses().get(j).getComplexity(); if (similarClasses.get(i).getSimilarClasses().get(j).getNcloc() < linesOfCode) linesOfCode = similarClasses.get(i).getSimilarClasses().get(j).getNcloc(); if (similarClasses.get(i).getSimilarClasses().get(j).getCohesion() < cohesion) cohesion = similarClasses.get(i).getSimilarClasses().get(j).getCohesion(); if (similarClasses.get(i).getSimilarClasses().get(j).getCoupling() < coupling) coupling = similarClasses.get(i).getSimilarClasses().get(j).getCoupling(); /* if (similarClasses.get(i).getSimilarClasses().get(j).getNumOfFunctions() < functions) functions = similarClasses.get(i).getSimilarClasses().get(j).getNumOfFunctions(); if (similarClasses.get(i).getSimilarClasses().get(j).getCommentsDensity() > commentsDensity) commentsDensity = similarClasses.get(i).getSimilarClasses().get(j).getCommentsDensity(); */ /*System.out.println("Clasas name:" + similarClasses.get(i).getSimilarClasses().get(j).getClassName()); System.out.println("try to find optimal: " + similarClasses.get(i).getSimilarClasses().get(j).getDit() + " " + similarClasses.get(i).getSimilarClasses().get(j).getNocc() + " " + similarClasses.get(i).getSimilarClasses().get(j).getMpc() + " " + similarClasses.get(i).getSimilarClasses().get(j).getRfc() + " " + similarClasses.get(i).getSimilarClasses().get(j).getLcom() + " " + similarClasses.get(i).getSimilarClasses().get(j).getDac() + " " + similarClasses.get(i).getSimilarClasses().get(j).getWmpc() + " " + similarClasses.get(i).getSimilarClasses().get(j).getCc() + " " + similarClasses.get(i).getSimilarClasses().get(j).getSize1() + " " + similarClasses.get(i).getSimilarClasses().get(j).getSize2());*/ } optimClass.setOptimalClassValues(complexity, linesOfCode, cohesion, coupling); /* * System.out.println("For class: " + * similarClasses.get(i).getName().getClassName()); * System.out.println("With metrics: " + * similarClasses.get(i).getName().getComplexity() + " " + * similarClasses.get(i).getName().getNumOfFunctions() + " " + * similarClasses.get(i).getName().getLinesOfCode() + " " + * similarClasses.get(i).getName().getCommentsDensity()); * System.out.println("The optimal class is: " + complexity + " " + functions + * " " + linesOfCode +" "+ commentsDensity); */ ResultsC rs = new ResultsC(); optimalClassesList.add(optimClass); rs.calculateInterest(similarClasses.get(i).getName(), optimClass, version); } } public void calculateOptimalPackage(ArrayList<FindSimilarArtifactsC> similarPackages, int version) throws SQLException { ArrayList<OptimalArtifactC> optimalClassesList = new ArrayList<OptimalArtifactC>(); for (int i = 0; i < similarPackages.size(); i++) { OptimalArtifactC optimClass = new OptimalArtifactC(); // Values from considered class double complexity = similarPackages.get(i).getPackage().getComplexity(); double linesOfCode = similarPackages.get(i).getPackage().getNcloc(); double coupling = similarPackages.get(i).getPackage().getCoupling(); double cohesion = similarPackages.get(i).getPackage().getCohesion(); /* double functions = similarPackages.get(i).getPackage().getNumOfFunctions(); double commentsDensity = similarPackages.get(i).getPackage().getCommentsDensity(); */ System.out.println("Find optimal package for: " + similarPackages.get(i).getPackage().getPackageName()); // Check only the 5 or less most similar int sizeOfArtifacts = similarPackages.get(i).getSimilarPackages().size(); if (sizeOfArtifacts > 5) sizeOfArtifacts = 4; // Values from similar classes for (int j = 0; j < sizeOfArtifacts; j++) { System.out.println("Package Name: " + similarPackages.get(i).getSimilarPackages().get(j).getPackageName()); if (similarPackages.get(i).getSimilarPackages().get(j).getComplexity() < complexity) complexity = similarPackages.get(i).getSimilarPackages().get(j).getComplexity(); if (similarPackages.get(i).getSimilarPackages().get(j).getNcloc() < linesOfCode) linesOfCode = similarPackages.get(i).getSimilarPackages().get(j).getNcloc(); if (similarPackages.get(i).getSimilarPackages().get(j).getCohesion() < cohesion) cohesion = similarPackages.get(i).getSimilarPackages().get(j).getCohesion(); if (similarPackages.get(i).getSimilarPackages().get(j).getCoupling() < coupling) coupling = similarPackages.get(i).getSimilarPackages().get(j).getCoupling(); /* if (similarPackages.get(i).getSimilarPackages().get(j).getCommentsDensity() > commentsDensity) commentsDensity = similarPackages.get(i).getSimilarPackages().get(j).getCommentsDensity(); if (similarPackages.get(i).getSimilarPackages().get(j).getNumOfFunctions() < functions) functions = similarPackages.get(i).getSimilarPackages().get(j).getNumOfFunctions(); */ /*System.out.println("Clasas name:" + similarClasses.get(i).getSimilarClasses().get(j).getClassName()); System.out.println("try to find optimal: " + similarClasses.get(i).getSimilarClasses().get(j).getDit() + " " + similarClasses.get(i).getSimilarClasses().get(j).getNocc() + " " + similarClasses.get(i).getSimilarClasses().get(j).getMpc() + " " + similarClasses.get(i).getSimilarClasses().get(j).getRfc() + " " + similarClasses.get(i).getSimilarClasses().get(j).getLcom() + " " + similarClasses.get(i).getSimilarClasses().get(j).getDac() + " " + similarClasses.get(i).getSimilarClasses().get(j).getWmpc() + " " + similarClasses.get(i).getSimilarClasses().get(j).getCc() + " " + similarClasses.get(i).getSimilarClasses().get(j).getSize1() + " " + similarClasses.get(i).getSimilarClasses().get(j).getSize2());*/ } optimClass.setOptimalClassValues(complexity, linesOfCode, cohesion, coupling); /* * System.out.println("For package: " + * similarPackages.get(i).getPackage().getPackageName()); * System.out.println("With metrics: " + * similarPackages.get(i).getPackage().getComplexity() + " " + * similarPackages.get(i).getPackage().getNumOfFunctions() + " " + * similarPackages.get(i).getPackage().getNcloc() + " " + * similarPackages.get(i).getPackage().getCommentsDensity()); * System.out.println("The optimal class is: " + complexity + " " + functions + * " " + linesOfCode +" "+ commentsDensity); */ ResultsC rs = new ResultsC(); optimalClassesList.add(optimClass); rs.calculateInterestPackage(similarPackages.get(i).getPackage(), optimClass, version); } } public void setOptimalClassValues(double complexity, double linesOfCode, double cohesion, double coupling) { this.optimalComplexity = complexity; this.optimalLinesOfCode = linesOfCode; this.optimalCoupling = coupling; this.optimalCohesion = cohesion; } public double getComplexity() { return this.optimalComplexity; } public double getLinesOfCode() { return this.optimalLinesOfCode; } public double getCohesion() { return this.optimalCohesion; } public double getCoupling() { return this.optimalCoupling; } }
package com.google.android.gms.common.internal; import android.content.ComponentName; import android.content.Context; import android.content.ServiceConnection; import android.os.Handler; import android.os.Handler.Callback; import android.os.IBinder; import android.os.Message; import java.util.HashMap; import java.util.HashSet; import java.util.Set; final class n extends m implements Callback { private final Context aGi; private final HashMap<a, b> aOx = new HashMap(); private final com.google.android.gms.common.stats.b aOy; private final long aOz; private final Handler mHandler; private final class b { IBinder aMX; ComponentName aOC; final a aOD = new a(this); final Set<ServiceConnection> aOE = new HashSet(); boolean aOF; final a aOG; int mState = 2; public b(a aVar) { this.aOG = aVar; } public final void a(ServiceConnection serviceConnection, String str) { n.this.aOy.a(n.this.aGi, serviceConnection, str, this.aOG.pn(), 3); this.aOE.add(serviceConnection); } public final boolean a(ServiceConnection serviceConnection) { return this.aOE.contains(serviceConnection); } public final void bd(String str) { this.aOF = n.this.aOy.a(n.this.aGi, str, this.aOG.pn(), this.aOD, 129); if (this.aOF) { this.mState = 3; return; } try { n.this.aOy.a(n.this.aGi, this.aOD); } catch (IllegalArgumentException e) { } } public final boolean po() { return this.aOE.isEmpty(); } } n(Context context) { this.aGi = context.getApplicationContext(); this.mHandler = new Handler(context.getMainLooper(), this); this.aOy = com.google.android.gms.common.stats.b.pG(); this.aOz = 5000; } private void a(a aVar, ServiceConnection serviceConnection) { w.j(serviceConnection, "ServiceConnection must not be null"); synchronized (this.aOx) { b bVar = (b) this.aOx.get(aVar); if (bVar == null) { throw new IllegalStateException("Nonexistent connection status for service config: " + aVar); } else if (bVar.a(serviceConnection)) { bVar.aOH.aOy.a(bVar.aOH.aGi, serviceConnection, null, null, 4); bVar.aOE.remove(serviceConnection); if (bVar.po()) { this.mHandler.sendMessageDelayed(this.mHandler.obtainMessage(0, bVar), this.aOz); } } else { throw new IllegalStateException("Trying to unbind a GmsServiceConnection that was not bound before. config=" + aVar); } } } private boolean a(a aVar, ServiceConnection serviceConnection, String str) { boolean z; w.j(serviceConnection, "ServiceConnection must not be null"); synchronized (this.aOx) { b bVar = (b) this.aOx.get(aVar); if (bVar != null) { this.mHandler.removeMessages(0, bVar); if (!bVar.a(serviceConnection)) { bVar.a(serviceConnection, str); switch (bVar.mState) { case 1: serviceConnection.onServiceConnected(bVar.aOC, bVar.aMX); break; case 2: bVar.bd(str); break; } } throw new IllegalStateException("Trying to bind a GmsServiceConnection that was already connected before. config=" + aVar); } bVar = new b(aVar); bVar.a(serviceConnection, str); bVar.bd(str); this.aOx.put(aVar, bVar); z = bVar.aOF; } return z; } public final void a(ComponentName componentName, ServiceConnection serviceConnection) { a(new a(componentName), serviceConnection); } public final void a(String str, String str2, ServiceConnection serviceConnection) { a(new a(str, str2), serviceConnection); } public final boolean a(ComponentName componentName, ServiceConnection serviceConnection, String str) { return a(new a(componentName), serviceConnection, str); } public final boolean a(String str, String str2, ServiceConnection serviceConnection, String str3) { return a(new a(str, str2), serviceConnection, str3); } public final boolean handleMessage(Message message) { switch (message.what) { case 0: b bVar = (b) message.obj; synchronized (this.aOx) { if (bVar.po()) { if (bVar.aOF) { bVar.aOH.aOy.a(bVar.aOH.aGi, bVar.aOD); bVar.aOF = false; bVar.mState = 2; } this.aOx.remove(bVar.aOG); } } return true; default: return false; } } }
package com.example.railway.repository.Train; import com.example.railway.model.Root; import com.example.railway.model.Train; import org.springframework.data.mongodb.repository.MongoRepository; public interface TrainRepository extends MongoRepository<Train, String> { }
package com.catnap.core.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created with IntelliJ IDEA. * * @author gwhit7 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @CatnapAnnotation public @interface CatnapProperty { /** * Special value that indicates that handlers should use the default * name (derived from method or field name) for property. * * @since 2.1 */ public final static String USE_DEFAULT_NAME = ""; /** * Defines name of the logical property, i.e. JSON object field * name to use for the property. If value is empty String (which is the * default), will try to use name of the field that is annotated. * Note that there is * <b>no default name available for constructor arguments</b>, * meaning that * <b>Empty String is not a valid value for constructor arguments</b>. */ String value() default USE_DEFAULT_NAME; /** * Property that indicates whether a value (which may be explicit * null) is expected for property during deserialization or not. * If expected, <code>BeanDeserialized</code> should indicate * this as a validity problem (usually by throwing an exception, * but this may be sent via problem handlers that can try to * rectify the problem, for example, by supplying a default * value). *<p> * Note that as of 2.0, this property is NOT used by * <code>BeanDeserializer</code>: support is expected to be * added for a later minor version. * * @since 2.0 */ boolean required() default false; }
package bicicleteria; import java.util.ArrayList; import java.util.List; public class Bicicleteria { private List<Bicicleta> bicicletas; private float ganancias; private Integer cantidadDeVentas; public Bicicleteria(){ bicicletas= new ArrayList<>(); } public Bicicleteria(List<Bicicleta> bicicletas, float ganancias, Integer cantidadDeVentas){ this.bicicletas=bicicletas; this.ganancias=ganancias; this.cantidadDeVentas=cantidadDeVentas; } public void addBicicleta(Bicicleta bicicleta){ this.bicicletas.add(bicicleta); } public List<Bicicleta> getBicicletas(){ return bicicletas; } public void setBicicletas(List<Bicicleta> bicicletas){ this.bicicletas=bicicletas; } public Float getGanancias(){ return ganancias; } public void setGanancias(Float ganancias){ this.ganancias=ganancias; } public Integer getCantidadDeVentas(){ return cantidadDeVentas; } public void setCantidadDeVentas(Integer cantidadDeVentas){ this.cantidadDeVentas=cantidadDeVentas; } public void venderBicicleta(Bicicleta bicicleta){ this.bicicletas.remove(bicicleta); } public Bicicleta buscarBicicleta(String nroDeSerie){ String ret = null; for(int i=0;i<bicicletas.size(); i++){ ret = bicicletas.get(i).getNroDeSerie(); if(ret.equals(nroDeSerie)){ return bicicletas.get(i); } return null; }
/** * Subclass of Shape */ public class ShapeS extends Shape { //set a color index for this Tetris shape public static final int COLOR = 6; /** * Constructor * Set the coordinates of the blocks in a way that would form this figure */ public ShapeS (){ //set coordinates of the blocks super(5, 0, 5, 1, 6, 1, 6, 2, COLOR, "S"); } /** * @Override * Rotate shape */ public int[][] rotate(int rotationIndex) { switch (rotationIndex){ // coordinate adjustment for rotation all blocks of this shape case 0: return new int[][] {{1,0},{0,-1},{-1,0},{-2,-1}}; case 1: return new int[][] {{0,2},{1,1},{0,0},{1,-1}}; case 2: return new int[][] {{-2,-1},{-1,0},{0,-1},{1,0}}; case 3: return new int[][] {{1,-1},{0,0},{1,1},{0,2}}; default: return new int[][] {{0,0},{0,0},{0,0},{0,0}}; } } }
/* * Copyright (c) 2018-2025, lxr All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the pig4cloud.com developer nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * Author: lxr (wangiegie@gmail.com) */ package com.itfdms.upmsservice.service.impl; import com.baomidou.mybatisplus.mapper.EntityWrapper; import com.baomidou.mybatisplus.plugins.Page; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import com.itfdms.common.util.QueryPage; import com.itfdms.upmsservice.mapper.SysRoleDeptMapper; import com.itfdms.upmsservice.mapper.SysRoleMapper; import com.itfdms.upmsservice.model.dto.RoleDTO; import com.itfdms.upmsservice.model.entity.SysRole; import com.itfdms.upmsservice.model.entity.SysRoleDept; import com.itfdms.upmsservice.service.SysRoleService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * java类简单作用描述 * * @ProjectName: * @Package: com.itfdms.upmsservice.service.impl * @ClassName: SysRoleServiceImpl * @Description: 服务实现类 * @Author: lxr * @CreateDate: 2018-08-30 18:54 * @UpdateUser: lxr * @UpdateDate: 2018-08-30 18:54 * @UpdateRemark: The modified content * @Version: 1.0 * Copyright: Copyright (c) 2018-08-30 **/ @Service public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService { @Autowired private SysRoleDeptMapper sysRoleDeptMapper; @Autowired private SysRoleMapper sysRoleMapper; /** * 方法实现说明 * * @param roleDto 角色信息 * @return 成功、失败 * @throws * @className: SysRoleServiceImpl * @methodName * @description: 添加角色 * @author lxr * @createDate 2018-08-30 21:51 * @updateUser: lxr * @updateDate: 2018-08-30 21:51 * @updateRemark: The modified content * @version 1.0 * @see /对类、属性、方法的说明 参考转向 **/ @Override public Boolean insertRole(RoleDTO roleDto) { SysRole sysRole = new SysRole(); BeanUtils.copyProperties(roleDto, sysRole); sysRoleMapper.insert(sysRole); SysRoleDept roleDept = new SysRoleDept(); roleDept.setRoleId(sysRole.getRoleId()); roleDept.setDeptId(roleDto.getRoleDeptId()); sysRoleDeptMapper.insert(roleDept); return true; } /** * 方法实现说明 * * @param query 查询条件 * @param wrapper wapper * @throws * @className: SysRoleServiceImpl * @methodName * @description: 分页查角色列表 * @author lxr * @createDate 2018-08-30 21:51 * @updateUser: lxr * @updateDate: 2018-08-30 21:51 * @updateRemark: The modified content * @version 1.0 * @see /对类、属性、方法的说明 参考转向 **/ @Override public Page selectwithDeptPage(QueryPage<Object> query, EntityWrapper<Object> wrapper) { query.setRecords(sysRoleMapper.selectRolePage(query, query.getCondition())); return query; } /** * 方法实现说明 * * @param roleDto 含有部门信息 * @return 成功、失败 * @throws * @className: SysRoleServiceImpl * @methodName * @description: 更新角色 * @author lxr * @createDate 2018-08-30 21:51 * @updateUser: lxr * @updateDate: 2018-08-30 21:51 * @updateRemark: The modified content * @version 1.0 * @see /对类、属性、方法的说明 参考转向 **/ @Transactional(rollbackFor = Exception.class) @Override public Boolean updateRoleById(RoleDTO roleDto) { //删除原有的角色部门关系 SysRoleDept condition = new SysRoleDept(); condition.setRoleId(roleDto.getRoleId()); sysRoleDeptMapper.delete(new EntityWrapper<>(condition)); //更新角色信息 SysRole sysRole = new SysRole(); BeanUtils.copyProperties(roleDto, sysRole); sysRoleMapper.updateById(sysRole); //维护角色部门关系 SysRoleDept roleDept = new SysRoleDept(); roleDept.setRoleId(sysRole.getRoleId()); roleDept.setDeptId(roleDto.getRoleDeptId()); sysRoleDeptMapper.insert(roleDept); return true; } /** * 方法实现说明 * * @param deptId 部门ID * @return 角色列表 * @throws * @className: SysRoleServiceImpl * @methodName * @description: 通过部门ID查询角色列表 * @author lxr * @createDate 2018-08-30 21:52 * @updateUser: lxr * @updateDate: 2018-08-30 21:52 * @updateRemark: The modified content * @version 1.0 * @see /对类、属性、方法的说明 参考转向 **/ @Override public List<SysRole> selectListByDeptId(Integer deptId) { return sysRoleMapper.selectListByDeptId(deptId); } }
package com.tencent.mm.plugin.appbrand.jsapi.auth; import com.tencent.mm.plugin.appbrand.jsapi.auth.JsApiOperateWXData.OperateWXDataTask; import com.tencent.mm.plugin.appbrand.jsapi.auth.JsApiOperateWXData.OperateWXDataTask.a; import com.tencent.mm.protocal.c.bio; import com.tencent.mm.sdk.platformtools.x; import java.util.LinkedList; class JsApiOperateWXData$OperateWXDataTask$1 implements a { final /* synthetic */ OperateWXDataTask fJJ; JsApiOperateWXData$OperateWXDataTask$1(OperateWXDataTask operateWXDataTask) { this.fJJ = operateWXDataTask; } public final void qe(String str) { x.d("MicroMsg.JsApiOperateWXData", "onSuccess !"); this.fJJ.fJH = str; this.fJJ.fJw = "ok"; OperateWXDataTask.a(this.fJJ); } public final void fM(String str) { x.e("MicroMsg.JsApiOperateWXData", "onFailure !"); this.fJJ.fJw = "fail:" + str; OperateWXDataTask.b(this.fJJ); } public final void a(LinkedList<bio> linkedList, String str, String str2) { x.d("MicroMsg.JsApiOperateWXData", "onConfirm !"); this.fJJ.fJy = linkedList.size(); int i = 0; while (i < this.fJJ.fJy) { try { this.fJJ.fJz.putByteArray(String.valueOf(i), ((bio) linkedList.get(i)).toByteArray()); i++; } catch (Throwable e) { x.e("MicroMsg.JsApiOperateWXData", "IOException %s", new Object[]{e.getMessage()}); x.printErrStackTrace("MicroMsg.JsApiOperateWXData", e, "", new Object[0]); this.fJJ.fJw = "fail"; OperateWXDataTask.c(this.fJJ); return; } } this.fJJ.mAppName = str; this.fJJ.fyq = str2; this.fJJ.fJw = "needConfirm"; OperateWXDataTask.d(this.fJJ); } }
// Maryam Athar Khan // Homework 08 Part 1 // Due date is October 20,2015 // This program is designed to calcuate the Area of a shape that the user inputs, using methods. import java.util.Scanner; // import Scanner class public class Area { // define a class public static double input() {// define input method with output of type double Scanner myScanner= new Scanner(System.in); // declare scanner variable while (true) { // loop always runs if (myScanner.hasNextDouble()) { // if Scanner is double double input=myScanner.nextDouble(); // store value into input return input; // ask to return input } // end of if statement else { // otherwise System.out.print("Sorry, you did not enter a double value. Try again: ");// error message and prompt user again myScanner.nextLine();// whatever user inputs } // end of else statement } // end of while loop } // end of input method public static double rectArea(double width, double height) {// define the rectangle area method double rectArea=width*height;// rectArea formula return rectArea;//return value } // end of rectArea method public static double triArea(double base, double height) {// define the triangle area method double triArea=0.5*base*height;// formula for the area of a triangle return triArea; // return value }// end of triArea method public static double cirArea(double radius) {// define the circle area method final double PI=3.14159; // declare the constant PI double cirArea=PI*radius*radius; // formula for the area of a circle return cirArea; // return value } // end of cirArea method public static void main(String[] args) { // define the main method Scanner myScanner= new Scanner(System.in); // declare Scanner variable System.out.print("Please input what shape's area you would like to calculate: "); // ask user to input shape String a="rectangle"; // declare string a and assign rectangle to it String b="triangle"; // declare string b and assign triangle to it String c="circle"; // declare string c and assign circle to it double rWidth=0; // declare rectangle width double rHeight=0; // declare rectangle height double tBase=0; // declare triangle base double tHeight=0; // declare triangle height double radius=0; // delcare radius String shape=myScanner.next(); // declare shape and assign whatever the user inputs to it while (true) { // loop always runs if (shape.equals(a) || shape.equals(b) || shape.equals(c) ) { // if shape is equal to rectangle, triangle, or circle break; // break and exit } // end of if statement else { // otherwise System.out.println("This is not an acceptable shape. The acceptable shapes are: rectangle, triangle, or a circle."); // error message and tell them what acceptable shapes are System.out.print("Please input what shape's area you would like to calculate: "); // ask again shape=myScanner.next(); // assign what they input to shape } // end of else statement } // end of while loop if (shape.equals(a)) {// if shape is a rectangle System.out.print("Please input the width of the rectangle: "); // ask width rWidth=input();// run input method with width value System.out.print("Please input the height of the rectangle: "); // ask height rHeight=input(); // run input method with heigh value double rectArea=rectArea(rWidth,rHeight); // calculate the area of the rectangle and run rectArea method System.out.println("The area of the rectangle is: " +rectArea);// print out output } // end of if rectangle statement else if (shape.equals(b)) { // if shape is a triangle System.out.print("Please input the base length of the triangle: "); // ask base length tBase=input(); // run input method with triangle base value System.out.print("Please input the height of the triangle: "); // ask height tHeight=input(); // run input method with triangle height value double triArea=triArea(tBase,tHeight);// calculate triangle area by running triArea method System.out.println("The area of the triangle is: " +triArea); // print out output } // end of if triangle statement else if (shape.equals(c)) { // if shape is a circle System.out.print("Please input the radius of the circle: "); // ask the radius radius=input(); // run input method with radius double cirArea=cirArea(radius); // calculate area of a circle by running cirArea method System.out.println("The area of the circle is: " +cirArea); // print out output } // end of if circle statement } // end of main method } // end of class
package org.apache.commons.net.ftp; public interface FTPFileFilter { boolean accept(FTPFile paramFTPFile); } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\ftp\FTPFileFilter.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
public class Node { int data; Node left; Node right; Node(int data) { this.data = data; } } public class BinaryTree { public static Node root; public static int preIndex; public static Node buildTree(int in[], int pre[], int inStrt, int inEnd) { if(inStrt > inEnd ) { return null; } Node tNode = new Node(pre[preIndex++]); if(inStrt == inEnd) { return tNode; } int index = search(in, inStrt, inEnd, tNode.data); tNode.left = buildTree(in, pre, inStrt, index -1); tNode.right = buildTree(in,pre, index+1, inEnd); return tNode; } public static int search(int arr[], int inStrt, int inEnd, int data) { int i; for(i = inStrt; i < inEnd; i++) { if(arr[i] == data) { return i; } } return i; } public static void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.data + " "); /* now recur on right child */ printInorder(node.right); } public static void main(String[] args) { BinaryTree tree = new BinaryTree(); int in[] = new int[]{13,14,23,25,30,40,45,50,60}; int pre[] = new int[]{30,13,23,14,25,50,45,40,60}; int len = in.length; Node root = tree.buildTree(in, pre, 0, len - 1); // building the tree by printing inorder traversal System.out.println("Inorder traversal of constructed tree is : "); tree.printInorder(root); } }
package airplanebooking.gui; import airplanebooking.CurrentBooking; import airplanebooking.BookingListener; import airplanebooking.CurrentFlight; import airplanebooking.database.Airplane; import airplanebooking.database.Database; import airplanebooking.database.Flight; import airplanebooking.database.Seat; import airplanebooking.SeatListener; import java.awt.Color; import java.awt.Graphics; import java.awt.Cursor; import java.util.ArrayList; /** * AirplaneCanvas is used to draw the airplane on a JComponent. * @author Andreas Jacobsen */ public final class AirplaneCanvas extends javax.swing.JComponent implements BookingListener { // The flight to mark the seats for. private Flight flight; // The airplane to draw. private Airplane airplane; // Economy Class private Boolean EClass; private int EseatGroups; private int EseatLength; private int ErowSeats; private int EseatSize; // Business Class private Boolean BClass; private int BseatGroups; private int BseatLength; private int BrowSeats; private int BtotalSeats; private int BseatSize; // First Class private Boolean FClass; private int FseatGroups; private int FseatLength; private int FrowSeats; private int FtotalSeats; private int FseatSize; // Initial space in x- and y-direction private int iniX; private int iniY; // array of seats and current seat. private int[][] seats; private int seat; // public int seatNumber; public String seatClass; private int seatsCount; public Boolean bookable; // X- and y-coordinate for the mouse. public int x; public int y; // List of event subscribers private static final ArrayList<SeatListener> listeners = new ArrayList<>(); /** * Constructor used to initialze everything. */ public AirplaneCanvas() { CurrentBooking.reset(); reset(); } private void reset() { bookable = false; flight = null; airplane = null; // Economy Class EseatGroups = 0; EseatLength = 0; ErowSeats = 0; EseatSize = 0; EClass = EseatGroups > 0 && EseatLength > 0 && ErowSeats > 0; // Business Class BseatGroups = 0; BseatLength = 0; BrowSeats = 0; BseatSize = 0; BClass = BseatGroups > 0 && BseatLength > 0 && BrowSeats > 0; BtotalSeats = BseatGroups*BseatLength*BrowSeats; // First Class FseatGroups = 0; FseatLength = 0; FrowSeats = 0; FseatSize = 0; FClass = FseatGroups > 0 && FseatLength > 0 && FrowSeats > 0; FtotalSeats = FseatGroups*FseatLength*FrowSeats; // Reset current seat values seatNumber = 0; seatClass = ""; // Drawing start offset iniX = 0; iniY = 0; // All seats available seatsCount = 0; seats = new int[10][6]; seat = 0; } /** * This method sets the airplane canvas with everything * used to draw the airplane. * @param isBookable Whether seat can be clicked for booking or not as boolean. * @param flight The flight to draw for as flight object. * @see Flight */ public void setAirplaneCanvas(Boolean isBookable, Flight flight) { reset(); CurrentBooking.reset(); // Add flight to current booking CurrentBooking.addFlight(flight); // Set whether flight is bookable or not this.bookable = isBookable; // Set flight and airplane variables this.flight = flight; airplane = flight.getAirplane(); // Get seat formations String[] ec = airplane.getECSeatFormation().split(":"); String[] bc = airplane.getBCSeatFormation().split(":"); String[] fc = airplane.getFCSeatFormation().split(":"); // Economy Class EseatLength = Integer.parseInt(ec[0]); EseatGroups = Integer.parseInt(ec[1]); ErowSeats = Integer.parseInt(ec[2]); EseatSize = 10; EClass = EseatGroups > 0 && EseatLength > 0 && ErowSeats > 0; // Business Class BseatLength = Integer.parseInt(bc[0]); BseatGroups = Integer.parseInt(bc[1]); BrowSeats = Integer.parseInt(bc[2]); BseatSize = 12; BClass = BseatGroups > 0 && BseatLength > 0 && BrowSeats > 0; BtotalSeats = BseatGroups*BseatLength*BrowSeats; // First Class FseatLength = Integer.parseInt(fc[0]); FseatGroups = Integer.parseInt(fc[1]); FrowSeats = Integer.parseInt(fc[2]); FseatSize = 15; FClass = FseatGroups > 0 && FseatLength > 0 && FrowSeats > 0; FtotalSeats = FseatGroups*FseatLength*FrowSeats; // Reset current seat values seatNumber = 0; seatClass = ""; // Drawing start offset iniX = 10; iniY = 10; // All seats available seatsCount = (EseatGroups*EseatLength*ErowSeats)+(BseatGroups*BseatLength*BrowSeats)+(FseatGroups*FseatLength*FrowSeats); seats = new int[seatsCount][6]; seat = 0; // Create data for seats int i = 0; for (int[] s : seats) { s[0] = i++; } if (bookable == true) { // Go through all blocked seats for (Seat s : CurrentBooking.getBlockedSeats()) { seats[s.getSeatID()-1][1] = 1; } // Go through all booked seats for (Seat s : CurrentBooking.getBookedSeats()) { seats[s.getSeatID()-1][1] = 2; } } else { for (Seat s : Database.db().getFlightBookedSeats(flight.getID())) { seats[s.getSeatID()-1][1] = 1; } } // Event for mouse movement addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { @Override public void mouseMoved(java.awt.event.MouseEvent e) { x = e.getX(); y = e.getY(); Boolean isInside = false; for (int i = 0; i < seatsCount; i++) { // Check if mouse is inside a seat if (x > seats[i][2] && y > seats[i][3] && x < seats[i][4] && y < seats[i][5]) { isInside = true; if (bookable == true) { if (seats[i][1] == 2) { // Blue changeCursor(new Cursor(Cursor.HAND_CURSOR)); } else if (seats[i][1] == 0) { // Green changeCursor(new Cursor(Cursor.HAND_CURSOR)); } else { changeCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } else { if (seats[i][1] == 1) { // Red changeCursor(new Cursor(Cursor.HAND_CURSOR)); } else { changeCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } // Current seat seatNumber = i+1; // Current seat is First Class if (FClass && FtotalSeats > i) { seatClass = "First Class"; } // Current seat is Business Class else if (BClass && FtotalSeats + BtotalSeats > i) { seatClass = "Business Class"; } // Current seat is Economy Class else if (EClass && seatsCount > i) { seatClass = "Economy Class"; } break; } } if (!isInside) { // If nothing is found reset seatNumber = 0; seatClass = ""; changeCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } repaint(); } }); // If bookable add AirplaneCanvas to booking listeners if(bookable == true) addToBookingListeners(); addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseReleased(java.awt.event.MouseEvent e) { x = e.getX(); y = e.getY(); for (int i = 0; i < seatsCount; i++) { if (x > seats[i][2] && y > seats[i][3] && x < seats[i][4] && y < seats[i][5]) { clickSeat(i); } } } }); repaint(); } /** * This method changes the mouse cursor * @param c Cursor to change to * @see Cursor */ public void changeCursor(Cursor c) { this.setCursor(c); } /** * This method checks if airplane if fully booked. * @return Whether airplane is fully booked or not as boolean. */ public Boolean airplaneIsFull() { int c = 0; for (int i = 0; i < seatsCount; i++) { if (seats[i][1] == 1) c++; } return c >= seatsCount; } /** * This method send an update notify to all listeners. */ public void updated() { // Notify everybody that may be interested. for (SeatListener sl : listeners) { sl.seatChanged(); } } /** * This method adds AirplaneCanvas to CurrentBooking as listener. */ private void addToBookingListeners() { CurrentBooking.addListener(this); } /** * This method make a virtual click on a list of seats. * @param list Array list of seat objects. * @see Seat */ public void clickSeats(ArrayList<Seat> list) { for (int[] s : seats) { if(s[1] == 3) s[1] = 1; } for (Seat i : list) { if (bookable == false) { if (seats[i.getSeatID()-1][1] == 1) { // Red seats[i.getSeatID()-1][1] = 3; } } } repaint(); } /** * This method makes a virtual click on a seat. * @param i The seat number to click on. */ public void clickSeat(int i) { if (bookable == true) { if (seats[i][1] == 2) { // Blue // Remove booking CurrentBooking.removeSeat(i+1); } else if (seats[i][1] == 0) { // Green // Add booking CurrentBooking.addSeat(new Seat(i+1)); } } else { if (seats[i][1] == 1) { changeCursor(new Cursor(Cursor.WAIT_CURSOR)); for (int s = 0; s < seatsCount; s++) { if (seats[s][1] == 3) seats[s][1] = 1; } // Red seats[i][1] = 3; CurrentFlight.setSeat(new Seat(i+1)); updated(); } } repaint(); } /** * This method paints the airplane. * @param g * @see Graphics */ @Override public void paint(Graphics g) { // Set default drawing color g.setColor(Color.black); // Draw rectangle around area g.drawRect(0, 0, getWidth()-1, getHeight()-1); // If a seat is hovered, show info if(seatNumber > 0) g.drawString(seatClass + " Seat: " + seatNumber, 4, 12); // Set drawing offset based on window size iniX = offsetX(); iniY = offsetY(); seat = 0; // Draw airplane for all classes if (FClass) drawClass(g, "first"); if (BClass) drawClass(g, "business"); if (EClass) drawClass(g, "economy"); } /** * This method draws the correspondent class. * @param g * @see Graphics * @param cl Class to draw as string. */ private void drawClass(Graphics g, String cl) { // Set default values int seatLength = 0; int seatGroups = 0; int rowSeats = 0; int seatSize = 0; int rowSpace = 0; int initialY = offsetY(); // Check which class to draw now // and change variables to match class switch(cl) { case "first": seatLength = FseatLength; seatGroups = FseatGroups; rowSeats = FrowSeats; seatSize = FseatSize; break; case "business": seatLength = BseatLength; seatGroups = BseatGroups; rowSeats = BrowSeats; seatSize = BseatSize; break; case "economy": seatLength = EseatLength; seatGroups = EseatGroups; rowSeats = ErowSeats; seatSize = EseatSize; break; } iniY = initialY; // If there is only one group of seats if (seatGroups == 1) { // Place seat in middle iniY = initialY + (((getClassHeight(getBiggestClass())) - getClassHeight(cl)) / 2); } else { // Place seats closest to the windows if (cl.equals(getBiggestClass())) rowSpace = 15; else rowSpace = 15 + (((getClassHeight(getBiggestClass())) - getClassHeight(cl)) / (seatGroups - 1)); } // column number int l = 0; // row number int r = 0; // seat number int s = 0; // go through each column for (int li = 0; li < seatLength; li++) { // go through each row for (int ri = 0; ri < seatGroups; ri++) { // go through each seat for (int si = 0; si < rowSeats; si++) { // Ff seat is booked show red // else show green if (seats[seat][1] == 0) { g.setColor(Color.green); } else if (seats[seat][1] == 1) { g.setColor(Color.red); } else if (seats[seat][1] == 2) { g.setColor(Color.blue); } else if (seats[seat][1] == 3) { g.setColor(Color.orange); } g.fillRect(((l*(seatSize+5))+iniX), ((s*(seatSize+5))-5)+(r*rowSpace)+iniY, seatSize, seatSize); // Set seat coordinates seats[seat][2] = (l*(seatSize+5))+iniX; seats[seat][3] = ((s*(seatSize+5))-5)+(r*rowSpace)+iniY; seats[seat][4] = ((l*(seatSize+5))+iniX)+seatSize; seats[seat][5] = (((s*(seatSize+5))-5)+(r*rowSpace)+iniY)+seatSize; s++; seat++; } r++; } s = 0; r = 0; l++; } // Set x-offset for next class-drawing iniX = iniX+(l*15)+30; } /** * This method gets the highest (in pixel) class. * @return The class as string (economy/business/first). */ private String getBiggestClass() { int EconomyClassHeight = getClassHeight("economy"); int BusinessClassHeight = getClassHeight("business"); int FirstClassHeight = getClassHeight("first"); // if (EconomyClassHeight > FirstClassHeight) { if (EconomyClassHeight > BusinessClassHeight) { return "economy"; // return economy class as the highest class } else { return "business"; // return business class as the highest class } } else { if (FirstClassHeight > BusinessClassHeight) { return "first"; // return first class as the highest class } else { return "business"; // return business class as the highest class } } } /** * This method gets the height of a class in pixel. * @param cl Class to get height of. * @return The height of the class as integer. */ private int getClassHeight(String cl) { switch(cl) { case "first": return (FseatGroups * ((FrowSeats*(FseatSize+5)))) + (15*(FseatGroups - 1)); case "business": return (BseatGroups * ((BrowSeats*(BseatSize+5)))) + (15*(BseatGroups - 1)); case "economy": return (EseatGroups * ((ErowSeats*(EseatSize+5)))) + (15*(EseatGroups - 1)); } return 0; } /** * This method gets the class for a given seat number. * @param s The seat number as integer. * @return The class as string (f/b/e). */ public String getClassType(int s) { if (FClass && FtotalSeats > s) { return "f"; } // Current seat is Business Class else if (BClass && FtotalSeats + BtotalSeats > s) { return "b"; } // Current seat is Economy Class else if (EClass && seatsCount > s) { return "e"; } return "error"; } /** * This method gets the length in pixel of the airplane (all of the seats). * @return The length in pixel as integer. */ private int getAirplaneLength() { int l = 0; if (FClass) l += ((FseatLength * (FseatSize+5))-5) + 30; if (BClass) l += ((BseatLength * (BseatSize+5))-5) + 30; if (EClass) l += ((EseatLength * (EseatSize+5))-5); return l; } /** * This method gets the x-offset to draw after. * @return Offest in integer. */ private int offsetX() { return (getWidth() - getAirplaneLength()) / 2; } /** * This method gets y-offet to draw after. * @return Offset in integer. */ private int offsetY() { return (getHeight() - getClassHeight(getBiggestClass())) / 2; } /** * This method is called when a booking changed event has been fired. */ @Override public void bookingChanged() { // Go through all seats and set them to free. for (int[] s : seats) { s[1] = 0; } if (bookable == true) { // Go through all blocked seats and mark them red. for (Seat s : CurrentBooking.getBlockedSeats()) { seats[s.getSeatID()-1][1] = 1; } // Go through all seats which are blocked but allowed to be booked anyway. for (Seat s : CurrentBooking.getAllowedSeats()) { seats[s.getSeatID()-1][1] = 0; } // Go through all booked seats and mark them blue. for (Seat s : CurrentBooking.getBookedSeats()) { seats[s.getSeatID()-1][1] = 2; } } else { for (Seat s : Database.db().getFlightBookedSeats(flight.getID())) { seats[s.getSeatID()-1][1] = 1; } } repaint(); } /** * This method adds a listener to the SeatListener list. * @param listener Listener as SeatListener. */ public void addListener(SeatListener listener) { listeners.add(listener); } }
package main.java.com.activationFunctions; /* * Activation function interface * * Author: Dylan Lasher */ import main.java.com.deepNeuralNetwork.Matrix; public interface ActivationFunctions { Matrix forward(Matrix z); Matrix backward(Matrix dA, Matrix z); }
package com.malko7.petagram.fragment.pet; import java.util.List; /** * Created by Fenix on 28/05/2016. */ public interface IPetFragmentPresenter { void getPets(); void getUserMediaRecent(String user); void getTimeLine(List<String> accounts); void onDestroy(); }
package com.polsl.edziennik.desktopclient.properties; public class Properties { public static final String Component = "com/polsl/edziennik/desktopclient/properties/components"; public static final String Menu = "com/polsl/edziennik/desktopclient/properties/menu"; public static final String Entity = "com/polsl/edziennik/desktopclient/properties/entity"; }
package com.shagaba.kickstarter.auth.core.service.security.account; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import com.google.common.collect.Lists; import com.shagaba.kickstarter.core.domain.security.account.UserAccount; import com.shagaba.kickstarter.core.repository.security.account.UserAccountRepository; @Service public class UserAccountServiceImpl implements UserAccountService { @Autowired protected UserAccountRepository userAccountRepository; @Override public UserAccount getUserAccountByUsername(String username) { Assert.notNull(username); return userAccountRepository.getUserAccountByUsername(username); } @Override public UserAccount getUserAccountByAccountId(String accountId) { Assert.notNull(accountId); return userAccountRepository.findOne(accountId); } @Override public List<UserAccount> getAllUserAccounts() { return Lists.newArrayList(userAccountRepository.findAll()); } @Override public UserAccount create(UserAccount userAccount){ Assert.notNull(userAccount); Assert.isNull(userAccount.getAccountId()); return userAccountRepository.save(userAccount); } @Override public UserAccount update(UserAccount userAccount){ Assert.notNull(userAccount); Assert.notNull(userAccount.getAccountId()); return userAccountRepository.save(userAccount); } @Override public void delete(String accountId) { Assert.notNull(accountId); userAccountRepository.delete(accountId); } }
package com.joe.holi; import androidx.appcompat.app.AppCompatActivity; import android.Manifest; import android.annotation.TargetApi; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.widget.FrameLayout; import com.boniu.ad.SplashAdManager; import java.util.ArrayList; import java.util.List; public class SplashActivity extends AppCompatActivity { private boolean isTomain = true; public static final String IS_TOMAIN = "IS_TOMAIN"; private FrameLayout frameLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); isTomain = getIntent().getBooleanExtra(IS_TOMAIN,true); frameLayout = ((FrameLayout) findViewById(R.id.framelayout)); if (Build.VERSION.SDK_INT >= 23) { checkAndRequestPermission(); }else{ new SplashAdManager().ShowSplashAd(this,frameLayout,iStartNext,"53d230df6a5e4a589f78c45d35eed0c0"); } } private SplashAdManager.IStartNext iStartNext = new SplashAdManager.IStartNext() { @Override public void startNext(String type) { gotoNext(); } @Override public void onerror(String msg) { Log.e("MainActivity", "onerror: " + msg ); gotoNext(); } }; /** * ----------非常重要---------- * <p> * Android6.0以上的权限适配简单示例: * <p> * 如果targetSDKVersion >= 23,那么建议动态申请相关权限,再调用广点通SDK * <p> * SDK不强制校验下列权限(即:无下面权限sdk也可正常工作),但建议开发者申请下面权限,尤其是READ_PHONE_STATE权限 * <p> * READ_PHONE_STATE权限用于允许SDK获取用户标识, * 针对单媒体的用户,允许获取权限的,投放定向广告;不允许获取权限的用户,投放通投广告,媒体可以选择是否把用户标识数据提供给优量汇,并承担相应广告填充和eCPM单价下降损失的结果。 * <p> * Demo代码里是一个基本的权限申请示例,请开发者根据自己的场景合理地编写这部分代码来实现权限申请。 * 注意:下面的`checkSelfPermission`和`requestPermissions`方法都是在Android6.0的SDK中增加的API,如果您的App还没有适配到Android6.0以上,则不需要调用这些方法,直接调用广点通SDK即可。 */ @TargetApi(Build.VERSION_CODES.M) private void checkAndRequestPermission() { List<String> lackedPermission = new ArrayList<String>(); if (!(checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)) { lackedPermission.add(Manifest.permission.READ_PHONE_STATE); } if (!(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) { lackedPermission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE); } // 如果需要的权限都已经有了,那么直接调用SDK if (lackedPermission.size() != 0) { // 否则,建议请求所缺少的权限,在onRequestPermissionsResult中再看是否获得权限 String[] requestPermissions = new String[lackedPermission.size()]; lackedPermission.toArray(requestPermissions); requestPermissions(requestPermissions, 1024); } else { new SplashAdManager().ShowSplashAd(this,frameLayout,iStartNext,"53d230df6a5e4a589f78c45d35eed0c0"); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == 1024) { gotoNext(); } } private void gotoNext() { if (isTomain){ Intent intent = new Intent(SplashActivity.this, MainActivity.class); startActivity(intent); } finish(); } }
import java.io.*; import java.util.*; public class Hero{ private ArrayList<Weapon> weapons = new ArrayList<Weapon>(); private String name; private int xPos; private int yPos; private int health; private Weapon weapon; private Armor armor; private int numPotions; public Hero(String name){ this.name = name; xPos = 0; yPos = 9; health = 100; weapon = new Weapon(0); numPotions = 0; } public int getNumPotions(){ return numPotions; } public int setNumPotions(int addPotion){ numPotions += addPotion; return numPotions; } public String getName(){ return name; } public int getX(){ return xPos; } public int getY(){ return yPos; } public Weapon setWeapon(int newWeapon){ weapon = new Weapon(newWeapon); return weapon; } public Weapon getWeapon(){ return weapon; } public int getHealth(){ return health; } public int setHealth(int newHealth){ health = newHealth; return health; } }
package com.example.waterbilling; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.sql.SQLDataException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import database.sqldataclass; import android.app.Activity; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.res.Resources; import android.database.SQLException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; public class Bill_meter_satus extends Activity implements OnItemSelectedListener { @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); } Uri uri; String filePath; Button b1, b2; EditText edt1; TextView tv1; //ImageView mImage; Spinner faultspin; Bitmap b; private static final int CAMERA_PIC_REQUEST = 1888; String values,consID; String selecteditem; ArrayList<String> faultsdescp=new ArrayList<String>(); ArrayList<String> faults=new ArrayList<String>(); Uri uriSavedImage; //---------------Added on 19-6-14-----------------// File image; //---------------Added on 20-6-14-----------------// File imagesFolder; //---------------Added on 21-8-14-----------------// sqldataclass dt = new sqldataclass(Bill_meter_satus.this) ; //---------------Added on 5-12-14-------------------// String zoneWardName; //---------------Added on 5-12-14-------------------// boolean picClick = false; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.bill_meter_sat); b1 = (Button) findViewById(R.id.finallprint);// go next activity b2 = (Button) findViewById(R.id.remainingconsumers); //take picture edt1 = (EditText) findViewById(R.id.conscodedupli1); tv1 = (TextView) findViewById(R.id.noofconsvalue); // mImage = (ImageView) findViewById(R.id.imageView1); faultspin = (Spinner) findViewById(R.id.spinner1); faultspin.setOnItemSelectedListener(this); // mImage.setTag("meterpic"); //---------------Added on 5-12-14-------------------// String tempfilename = dt.fetchfilename(); String [] splitname; splitname = tempfilename.split("\\."); zoneWardName = splitname[0]; //----------------------------------------------// Load_Spinner_Data(); faultspin .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub selecteditem = faultspin.getSelectedItem().toString(); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); Bundle extra = getIntent().getExtras(); if (extra != null) { values = extra.getString("Cons_Code"); consID = extra.getString("ConsID"); edt1.setText(values); Toast.makeText(Bill_meter_satus.this, values, Toast.LENGTH_SHORT) .show(); } b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub Intent intent = new Intent( android.provider.MediaStore.ACTION_IMAGE_CAPTURE); String timeStamp = new SimpleDateFormat("dd-MM-yy").format(new Date()); //folder stuff // Commented on 21-8-14 File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Waterbill"); //File imagesFolder = new File(Environment.getRootDirectory(), "Waterbill"); //imagesFolder.mkdirs(); //-------------------- Added on 21-8-14 ----------------------// if(Environment.getExternalStorageDirectory() != null) { File sdCard = Environment.getExternalStorageDirectory(); imagesFolder = new File (sdCard.getAbsolutePath() + "/Waterbill"); } //-----------------------------------------------------------// if(!imagesFolder.mkdirs()) System.out.println("Folder failed to get created"); //String fip = values.concat("_"+timeStamp); //String fip = consID.concat("_"+timeStamp); //String fip = timeStamp.concat("_"+values); //Commented on 14-8-14 //---------------------------Added on 13-11-14--------------------------------// String fip; String conscode= values; if((conscode.contains("*")) || (conscode.contains("<")) || (conscode.contains(">")) || (conscode.contains("?")) || (conscode.contains("/")) || (conscode.contains("|")) || (conscode.contains("\\"))) { if(conscode.contains("*")) { //conscode.replaceAll("*,<,>,?,/,|,\\", " RP "); conscode = conscode.replaceAll("\\*", " "); } if(conscode.contains("<")) { conscode = conscode.replaceAll("<", " "); } if(conscode.contains(">")) { conscode = conscode.replaceAll(">", " "); } if(conscode.contains("?")) { conscode = conscode.replaceAll("\\?", " "); } if(conscode.contains("|")) { conscode = conscode.replaceAll("\\|", " "); } if(conscode.contains("\\")) { conscode = conscode.replace("\\"," "); } if(conscode.contains("/")) { conscode = conscode.replaceAll("/", " "); } fip = timeStamp.concat("_"+zoneWardName+"_"+"0"+conscode); } else //---------------------------------------------------------------------------// fip = timeStamp.concat("_"+zoneWardName+"_"+"0"+values); //Added on 14-8-14 //String fip = timeStamp.concat("_"+"0"+values); //Added on 14-8-14 commented 14-11-14 filePath = "/Waterbill/" +fip +".jpg" ; //File image = new File(imagesFolder, "CC_" + fip + ".jpg"); //Uri uriSavedImage = Uri.fromFile(image); //image = new File(imagesFolder, "CC_" + fip + ".jpg"); //Commented on 14-8-14 image = new File(imagesFolder, fip + ".jpg"); //Added on 14-8-14 uriSavedImage = Uri.fromFile(image); intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage); startActivityForResult(intent, CAMERA_PIC_REQUEST); } }); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub /* String b = mImage.getTag().toString(); System.out.println("The image tag is "+b); if (b == "meterpic") { // change to == */ //-----------Added on 9-6-15--------------// if(picClick==false) { //--------------------------------------// tv1.setText("Please click a picture"); // Toast.makeText(Bill_meter_satus.this,"Please click image", // Toast.LENGTH_SHORT).show(); } else { String str2 = selecteditem; System.out.print(str2); String str = "Normal"; if (selecteditem.equalsIgnoreCase(str)) { //check if the status is normal Intent next = new Intent( "com.example.waterbilling.Bill_meter_status_normal"); next.putExtra("Cons_Code", values); next.putExtra("status", selecteditem); next.putExtra("statuscode", faults.get(faultspin.getSelectedItemPosition())); next.putExtra("consid", consID); // Added on 5-3-15 startActivity(next); //----------uncommented by Ryan 5-3-15-------------// //startActivityForResult(next, 100); commented on 5-3-15 } else { Intent faultnext = new Intent("com.example.waterbilling.Bill_meter_status_faulty"); faultnext.putExtra("Cons_Code", values); faultnext.putExtra("status", selecteditem); faultnext.putExtra("statuscode", faults.get(faultspin.getSelectedItemPosition())); faultnext.putExtra("consid", consID); // Added on 5-3-15 startActivity(faultnext); //----------uncommented by Ryan 5-3-15-------------// //startActivityForResult(faultnext, 100); //commented on 5-3-15 } } } }); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_CANCELED) { if (requestCode == CAMERA_PIC_REQUEST) { // 2 //-------------------------------------Added on 20-6-14-----------------------------------------// try{ File imgFile = new File(image.toString()); if(imgFile.exists()){ //-----------------------------19-6-14------------------------------// MediaScannerConnection.scanFile(getApplicationContext(), new String[] { image.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() { @Override public void onScanCompleted(String path, Uri uri) { // TODO Auto-generated method stub System.out.println( "Scanned "+path + ":"); System.out.println("->uri="+uri); } }); //MediaScannerConnection.scanFile(context, paths, mimeTypes, callback); //----------------------------------------------------------------// /* Bitmap myBitmap =(Bitmap) BitmapFactory.decodeFile(imgFile.getAbsolutePath()); //mImage.setImageBitmap(myBitmap); Commented on 16-4-15 //--------------Added on 17-4-15-------------------//; mImage.setImageBitmap( decodeFile(imgFile, 90, 90)); //-------------------------------------------------// mImage.setTag(image.toString()); */ picClick = true; //Added on 9-6-15 tv1.setText("The Photo Has Been Saved"); //Added on 9-6-15 } } catch (Exception e) { e.printStackTrace(); } } } //------------------------------Added By Ryan To Exit properly 15-5-14-------------------------------// switch (requestCode) { case 100: setResult(requestCode); this.finish(); break; default: break; } super.onActivityResult(requestCode, resultCode, data); //--------------------------------------------------------------------------------------------------// } public void Load_Spinner_Data() { sqldataclass spindata = new sqldataclass(Bill_meter_satus.this); List<String> labels; try { labels = spindata.getspinnerdata(); for(int i=1;i<=labels.size();i++) { faults.add(labels.get(i)); i++; } for(int i=0;i<labels.size();i++) { faultsdescp.add(labels.get(i)); i++; } ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, faultsdescp); dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); faultspin.setAdapter(dataAdapter); } catch (SQLDataException e) { // TODO Auto-generated catch block System.out.print("Sql error"); } catch (SQLException e) { System.out.print("sql error"); } catch (Exception e) { System.out.println("i em a excpetion"); e.printStackTrace(); } } @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } //--------------------------Added on 17-4-15--------------------------// private Bitmap decodeFile(File f,int req_Height,int req_Width){ try { //decode image size BitmapFactory.Options o1 = new BitmapFactory.Options(); o1.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f),null,o1); //Find the correct scale value. It should be the power of 2. int width_tmp = o1.outWidth; int height_tmp = o1.outHeight; int scale = 1; if(width_tmp > req_Width || height_tmp > req_Height) { int heightRatio = Math.round((float) height_tmp / (float) req_Height); int widthRatio = Math.round((float) width_tmp / (float) req_Width); scale = heightRatio < widthRatio ? heightRatio : widthRatio; } BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; o2.inScaled = false; return BitmapFactory.decodeFile(f.getAbsolutePath(),o2); } catch(Exception e) { e.printStackTrace(); } return null; } //-------------------------------------------------------------------// }
package com.gtfs.util; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.Iterator; public class CalenderUtil implements Serializable { public static Integer monthDiff(Date oldDate, Date newDate) { if (oldDate.compareTo(newDate) > 0) { return -1; } int months = -1; int days = 0; Calendar oldCalendar = Calendar.getInstance(); oldCalendar.setTime(oldDate); Calendar newCalendar = Calendar.getInstance(); newCalendar.setTime(newDate); do { months++; oldCalendar.add(Calendar.MONTH, 1); } while (newCalendar.compareTo(oldCalendar) >= 0); oldCalendar.add(Calendar.MONTH, -1); do { days++; oldCalendar.add(Calendar.DATE, 1); } while (newCalendar.compareTo(oldCalendar) >= 0); if (months == 0) { return months; } else { if (days < 15) { return months; } else { return months + 1; } } } public static Date incrementDate(Date date, Integer days) { Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, days); return cal.getTime(); } public static void main(String args[]){ Calendar oldCal = Calendar.getInstance(); oldCal.set(Calendar.DATE,5); oldCal.set(Calendar.MONTH,3); oldCal.set(Calendar.YEAR,2014); Integer fineMnth = CalenderUtil.monthDiff(oldCal.getTime(),new Date()); System.out.print(fineMnth); } }
/* * 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 processBD; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.swing.JOptionPane; /** * * @author bryan */ public class conexionBD { public static PreparedStatement prest=null; public static CallableStatement cllst=null; public static Connection conec=null; public static Statement st=null; public static ResultSet rt=null; public static String usu; public static String contra; public static String host; public static String db; public static String driver; public void Conectar(){ try{ usu="root"; contra=""; host="localhost"; db="cutonala"; driver="com.mysql.jdbc.Driver"; String url="jdbc:mysql://"+host+"/"+db; Class.forName(driver).newInstance(); conec=DriverManager.getConnection(url,usu,contra); }catch(ClassNotFoundException | IllegalAccessException | InstantiationException | SQLException e){ JOptionPane.showMessageDialog(null, e.toString()); } } public void closeBD(){ if ( conexionBD.conec != null ){ try{ conexionBD.conec.close(); conexionBD.st.close(); }catch( SQLException e ) { System.out.print("<h1>"+e.getMessage()+"</h1>"); } } } }
package id.ac.ub.ptiik.papps.base; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class Agenda { public String agenda_id, jenis_kegiatan_id, lokasi, ruang, judul, keterangan, penyelenggara, tgl_mulai, tgl_selesai, is_publish, is_private; public Calendar getCalendarTanggalMulai() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); try { Date tanggal = format.parse(this.tgl_mulai); Calendar cal = Calendar.getInstance(Locale.US); cal.setTime(tanggal); return cal; } catch (ParseException e) { e.printStackTrace(); } return null; } public int getTanggal() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); try { Date tanggal = format.parse(this.tgl_mulai); Calendar cal = Calendar.getInstance(Locale.US); cal.setTime(tanggal); return cal.get(Calendar.DAY_OF_MONTH); } catch (ParseException e) { e.printStackTrace(); } return 0; } public Calendar getCalendarTanggalSelesai() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); try { Date tanggal = format.parse(this.tgl_selesai); Calendar cal = Calendar.getInstance(Locale.US); cal.setTime(tanggal); return cal; } catch (ParseException e) { e.printStackTrace(); } return null; } public String getDayOfWeekTanggalMulai() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd k:m:s", Locale.US); try { Date tanggal = format.parse(this.tgl_mulai); Calendar cal = Calendar.getInstance(Locale.US); cal.setTime(tanggal); return cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US); } catch (ParseException e) { e.printStackTrace(); } return null; } public String getDayOfWeekTanggalSelesai() { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd k:m:s", Locale.US); try { Date tanggal = format.parse(this.tgl_selesai); Calendar cal = Calendar.getInstance(Locale.US); cal.setTime(tanggal); return cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US); } catch (ParseException e) { e.printStackTrace(); } return null; } }
package controllers.filters; import models.User; import services.BlockedService; import services.UserService; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.sql.SQLException; @WebFilter("/AuthenticationFilter") public class AuthenticationFilter implements Filter { UserService userService = new UserService(); BlockedService blockedService = new BlockedService(); @Override public void init(FilterConfig filterConfig) throws ServletException { Filter.super.init(filterConfig); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String uri = req.getRequestURI(); User user = null; Cookie[] cookies = req.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals("token")) { try { user = userService.getUserByToken(cookie.getValue()); } catch (SQLException | ClassNotFoundException throwables) { throwables.printStackTrace(); } } } if (!(uri.contains("login") || uri.contains("register")) && user == null) { res.sendRedirect("login"); return; } else if (!(uri.contains("login") || uri.contains("register")) && user != null) { try { if (blockedService.isUserBlocked(user.getId()) == 1) { res.sendRedirect("login"); return; } } catch (SQLException | ClassNotFoundException throwables) { throwables.printStackTrace(); } } req.setAttribute("user", user); chain.doFilter(request, response); } @Override public void destroy() { Filter.super.destroy(); } }
package com.wlt.retrofit.bean; /** * Created by Administrator on 2016-5-12. */ public class BaseBean { /** * message : success * message_code : 10000 */ /* * * 10000 请求成功 *10001 用户未登录 *10004 用户名不存在 *10006 缺少参数 *error_code 20000 数据库连接失败 * */ public String message; public String message_code; public void setMessage(String message) { this.message = message; } public void setMessage_code(String message_code) { this.message_code = message_code; } public String getMessage() { return message; } public String getMessage_code() { return message_code; } @Override public String toString() { return "BaseBean{" + "message='" + message + '\'' + ", message_code='" + message_code + '\'' + '}'; } }
package com.yboweb.bestmovie; import android.widget.ImageView; /** * Created by test on 24/03/16. */ public class ImageItem { private String image = null; private String title = null; private String rating = null; private String voting = null; private String id = null; private String videoKey = null; private String mapString = null; private String mapImages = null; private String imageList = null; private String imageGalleryNames = null; private String actorsJaon = null; ImageView keepImageView = null; private int type = -1; final static public int MAIN_VERTICAL_ITEM = 1; final static public int SCROLL_HORIZONTAL_ITEM = 2; final static public int GALLERY_ITEM = 3; final static public int VIDEO_ITEM = 4; final static public int ACTOR_ITEM = 5; final static public int ACTOR_DETAIL_IMAGE_ITEM = 6; final static public int ACTOR_DETAIL_MOVIE_ITEM = 7; public ImageItem() { super(); } public String getImage() { if(image == null) { } return image; } public void setType(int type) { this.type = type; } public int getType() { return (type); } public void setImage(String image) { this.image = image; } public void setTitle(String title) { this.title = title; } public String gettTitle() { return(title); } public void setRating(String rating) { this.rating = rating; } public String gettRating() { return(rating); } public void setVoting(String voting) { this.voting = voting; } public String getVoting() { return(voting); } public void setMap(String mapString) { this.mapString = mapString; } public String getMap() { return(mapString); } public void setImages(String mapImages) { this.mapImages = mapImages; } public String getImages() { return(mapImages); } public void setImageList(String imageList) { this.imageList = imageList; } public String getImageList() { return this.imageList;} public void setId(String id) { this.id = id; } public String getId() { return(id); } public void setVideoKey(String key) { videoKey = key;} String getVideoKey() { return(videoKey); } void setimageGalleryNames(String name) { imageGalleryNames = name; } String getimageGalleryNames() { return(imageGalleryNames); } public void setActorsJson(String name) {this.actorsJaon = name;} public String getActorsJaon() {return actorsJaon; } public void setImageView(ImageView imageview) { keepImageView = imageview; } public ImageView getImageVIew() { return(keepImageView); } }
import java.util.List; import java.util.ArrayList; /** * Provides a structure for handling multiple orders of cookies. * * @author Ben Godfrey * @version 13 FEB 2018 */ public class MasterOrder { /** Holds the list of cookie orders. */ private List<CookieOrder> orders; /** Constructs a new master order. */ public MasterOrder() { orders = new ArrayList<CookieOrder>(); } /** * Adds another order of cookies to the master order. * * @param theOrder The order to be added. */ public void addOrder(CookieOrder theOrder) { orders.add(theOrder); } /** * Calculates the total number of boxes in the master order. * * @return The total number of boxes. */ public int getTotalBoxes() { int sum = 0; for (CookieOrder c: orders) { sum += c.getNumBoxes(); } return sum; } /** * Removes all orders for a particular variety of cookies * from the master order. * * @param cookieVar The variety of cookies to be removed. * * @return The number of boxes removed. */ public int removeVariety(String cookieVar) { int counter = 0; for (int i=0; i<orders.size(); i++) { CookieOrder c = orders.get(i); String type = c.getVariety(); if (type.equals(cookieVar)) { counter += c.getNumBoxes(); orders.remove(i); i--; } } return counter; } /** * Returns a representation of this object as a string. * * @return String representation of this object. */ public String toString() { String output = "---MASTER ORDER---\n"; for (CookieOrder c: orders) { output += c + "\n"; } return output + "---END MASTER ORDER---"; } }
package entidades; import java.text.SimpleDateFormat; import java.util.Date; import enums.TipoLancamento; public class Lancamentos { private int id; private String descricao; private double valor; private Date data; private int categoria; private TipoLancamento tipoLancamento; public Lancamentos(int id, String descricao, double valor, int categoria, TipoLancamento tipoLancamento) { this.id = id; this.descricao = descricao; this.valor = valor; this.data = new Date(); this.categoria = categoria; this.tipoLancamento = tipoLancamento; } public String getDescricao() { return descricao; } public double getValor() { return valor; } public int getCategoria() { return categoria; } public TipoLancamento getTipoLancamento() { return tipoLancamento; } @Override public String toString() { SimpleDateFormat DateFor = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String stringDate = DateFor.format(data); return "Data do Lançamento: " + stringDate + "| Descrição: "+ descricao + " | valor: R$" + valor + " | Categoria: " + categoria ; } }
package com.cse308.sbuify.security; /** * Security-related constants. */ public class SecurityConstants { public static final String LOGIN_URL = "/api/login"; public static final String SIGN_UP_URL = "/api/users"; public static final String RESET_URL = "/api/reset-password"; public static final String CHANGE_PASS_URL = "/api/change-password"; public static final String ADMIN_PATTERN = "/api/admins/**"; public static final String CUSTOMER_PATTERN = "/api/customer/**"; public static final String CRON_PATTERN = "/api/cron/**"; public static final String IMAGE_PATTERN = "/static/i/**"; public static final String STREAM_PATTERN = "/api/stream/**"; public static final String SECRET = "70733b8a257ec1b86ac59f4dfd82309e"; public static final String HEADER_NAME = "Authorization"; public static final String HEADER_PREFIX = "Bearer "; }
package com.hesoyam.pharmacy.pharmacy.controller; import com.hesoyam.pharmacy.pharmacy.dto.PharmacyCreateDTO; import com.hesoyam.pharmacy.pharmacy.dto.PharmacyDTO; import com.hesoyam.pharmacy.pharmacy.dto.PharmacySearchDTO; import com.hesoyam.pharmacy.pharmacy.exceptions.InvalidPharmacyCreateRequest; import com.hesoyam.pharmacy.pharmacy.model.Pharmacy; import com.hesoyam.pharmacy.pharmacy.service.IPharmacyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import javax.persistence.EntityNotFoundException; import javax.validation.Valid; import java.util.ArrayList; import java.util.List; @RestController @RequestMapping(value="/pharmacy", produces = MediaType.APPLICATION_JSON_VALUE) public class PharmacyController { @Autowired private IPharmacyService pharmacyService; @PostMapping("/create") @Secured("ROLE_SYS_ADMIN") public ResponseEntity<Pharmacy> create(@RequestBody @Valid PharmacyCreateDTO pharmacyCreateDTO, BindingResult errors){ if(errors.hasErrors()){ return ResponseEntity.badRequest().build(); } Pharmacy savedPharmacy = null; try { savedPharmacy = pharmacyService.create(pharmacyCreateDTO); } catch (InvalidPharmacyCreateRequest invalidPharmacyCreateRequest) { return ResponseEntity.status(HttpStatus.CONFLICT).build(); } return ResponseEntity.ok(savedPharmacy); } @GetMapping(value = "/{id}") public ResponseEntity<PharmacyDTO> getPharmacy(@PathVariable Long id){ try{ Pharmacy pharmacy = pharmacyService.findOne(id); return new ResponseEntity<>(new PharmacyDTO(pharmacy), HttpStatus.OK); } catch (EntityNotFoundException e){ return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } @GetMapping(value="/all") public ResponseEntity<List<PharmacySearchDTO>> getAllPharmacies(){ List<Pharmacy> pharmacies = pharmacyService.getAll(); List<PharmacySearchDTO> pharmacySearchDTOList = new ArrayList<>(); for(Pharmacy p: pharmacies){ pharmacySearchDTOList.add(new PharmacySearchDTO(p.getId(), p.getName(), p.getRating(), p.getDescription(), p.getAddress().getCity().getCityName(), p.getAddress().getAddressLine(), p.getAddress().getLatitude(), p.getAddress().getLongitude())); } return ResponseEntity.ok().body(pharmacySearchDTOList); } @GetMapping(value = "/medicine-{id}") public ResponseEntity<List<PharmacyDTO>> getPharmaciesWithMedicine(@PathVariable Long id){ try{ List<Pharmacy> pharmacies = pharmacyService.findAllPharmaciesByMedicine(id); List<PharmacyDTO> retVal = new ArrayList<>(); for(Pharmacy p: pharmacies){ retVal.add(new PharmacyDTO(p)); } return new ResponseEntity<>(retVal, HttpStatus.OK); } catch (Exception e) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } } }
package com.oocl.ita.test; import static org.junit.Assert.*; import org.junit.Test; public class ExamsTest extends Exams{ @Test public void Question1() { assertEquals("onetwodefault",q1()); } @Test public void Question2() { int n = 5; assertEquals(8, q2(n)); } @Test public void Question3() { int inner=2, outer=2; int result=0; int i = 0, j = 0; while (i<outer) { while (j<inner) { result = (result*result)+1; j++; } i++; j = 0; } assertEquals(result, q3()); } @Test public void Question4() { assertEquals("HelloHelloHelloHello",q4()); } @Test public void Question7(){ assertEquals("62\n31\n10\n2\n0\n5", q7()); } @Test public void Question8() { } @Test public void Question9(){ int x = 1, y = 2, a = 3, b = 4, g = 5, i = 6, j = 7; boolean q9aequiv = x >= 5 && y < 7; boolean q9bequiv = a != b || g== 5; boolean q9cequiv = i <= 4 && j > 6; assertEquals(q9a(x, y), q9aequiv); assertEquals(q9b(a,b,g), q9bequiv); assertEquals(q9c(i,j),q9cequiv); } @Test public void Question10() { assertEquals("in for:9.0\nin for:9.5\nin for:10.0\nafter for10.5", q10a()); assertEquals("Main before p1: 10\\nIn p1: 100\\nMain before p2: 100\\nIn p2: 20\\nMain at the end: 20\\n-----\\nMain before p1: 30\\nIn p1: 600\\nMain before p2: 600\\nIn p2: 120\\nMain at the end: 120", q10b()); } }
package com.allinpay.its.boss.framework.repository.mybatis.model; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.Column; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import com.allinpay.its.boss.framework.annotation.Description; import com.allinpay.its.boss.framework.repository.mybatis.Exception.MyBatisPojoStructureException; import org.apache.commons.lang.StringUtils; import com.google.gson.Gson; /** * MyBatis用POJO基类 * * @author YM * */ public class MyBatisBaseModel implements Serializable { private static final long serialVersionUID = 1L; /** * 获取POJO对应的表名 需要POJO中的属性定义@Table(name) * * @return */ // public String getTableName() { // Table table = this.getClass().getAnnotation(Table.class); // if (table != null) { // return table.name(); // } else { // throw new MyBatisPojoStructureException( // "undefine POJO @Table, need Tablename(@Table(name))"); // } // } /** * 获取POJO对应的字段中文描述 * @return */ public String getModelFieldDescription(String fieldName) { for (Field field : this.getClass().getDeclaredFields()) { if(fieldName.equals(field.getName())){ if (field.isAnnotationPresent(Description.class)){ Description description= field.getAnnotation(Description.class); return description.value(); } }else{ return null; } } throw new MyBatisPojoStructureException( "undefine POJO @Description, need on Field(@Description(\"description\"))"); } /** * 获取POJO中的主键字段名 需要定义@Id * * @return */ public String getPrimaryKey() { for (Field field : this.getClass().getDeclaredFields()) { if (field.isAnnotationPresent(Id.class)) return field.getName(); } throw new MyBatisPojoStructureException("undefine POJO @Id"); } /** * 获取POJO中主键的序列名称,需要定义@SequenceGenerator(name="序列名称") * @return */ public String getSequenceName() { Field[] fields = this.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].isAnnotationPresent(SequenceGenerator.class)) { SequenceGenerator seq = fields[i] .getAnnotation(SequenceGenerator.class); return seq.name(); } } throw new MyBatisPojoStructureException("undefine POJO @SequenceGenerator(name=\"seqName\")"); } /** * 用于存放POJO的列信息 */ private transient static Map<Class<? extends MyBatisBaseModel>, List<String>> columnMap = new HashMap<Class<? extends MyBatisBaseModel>, List<String>>(); private boolean isNull(String fieldname) { try { Field field = this.getClass().getDeclaredField(fieldname); return isNull(field); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } return false; } private boolean isNull(Field field) { try { field.setAccessible(true); return field.get(this) == null; } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return false; } /** * 用于计算类定义 需要POJO中的属性定义@Column(name) */ public void caculationColumnList() { if (columnMap.containsKey(this.getClass())) return; Field[] fields = this.getClass().getDeclaredFields(); List<String> columnList = new ArrayList<String>(fields.length); for (Field field : fields) { if (field.isAnnotationPresent(Column.class)) columnList.add(field.getName()); } columnMap.put(this.getClass(), columnList); } /** * 获取用于WHERE的 有值字段详细信息 * * @return */ public List<WhereColumnModel> getWhereColumnsNameValueType() { Field[] fields = this.getClass().getDeclaredFields(); List<WhereColumnModel> columnList = new ArrayList<WhereColumnModel>(fields.length); for (Field field : fields) { if (field.isAnnotationPresent(Column.class) && !isNull(field)) columnList.add(new WhereColumnModel(field.getName(),"#{"+field.getName()+"}", field .getGenericType())); } return columnList; } /** * 用于获取Insert的字段累加 * * @return */ public String returnInsertColumnsName() { StringBuilder sb = new StringBuilder(); List<String> list = columnMap.get(this.getClass()); int i = 0; for (String column : list) { if (isNull(column)){ continue; } if (i++ != 0){ sb.append(','); } sb.append(column); } return sb.toString(); } /** * 用于获取Insert的字段映射累加 * * @return */ public String returnInsertColumnsDefine() { StringBuilder sb = new StringBuilder(); List<String> list = columnMap.get(this.getClass()); int i = 0; for (String column : list) { if (isNull(column)) continue; if (i++ != 0) sb.append(','); sb.append("#{").append(column).append('}'); } return sb.toString(); } /** * 用于获取Update Set的字段累加 * * @return */ public String returnUpdateSet() { StringBuilder sb = new StringBuilder(); List<String> list = columnMap.get(this.getClass()); int i = 0; for (String column : list) { if (isNull(column)) continue; if (i++ != 0) sb.append(','); sb.append(column).append("=#{").append(column).append('}'); } return sb.toString(); } /** * 转化POJO为JSON格式 * * @return */ public String toJSONString() { Gson gson = new Gson(); return gson.toJson(this); } /** * 打印类字段信息 */ @Override public String toString() { Field[] fields = this.getClass().getDeclaredFields(); StringBuilder sb = new StringBuilder(); sb.append('['); for (Field f : fields) { if (Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())) continue; Object value = null; try { f.setAccessible(true); value = f.get(this); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if (value != null) sb.append(f.getName()).append('=').append(value).append(','); } sb.append(']'); return sb.toString(); } /** * 每页显示多少条(每页记录数) */ private int numPerPage=10; /** * 当前是第几页(页码) */ private int pageNum=1; private int pageNumShown; //分页所要执行的配置文件中对应的id名称 private String pageSqlIdName; private String countPageSqlIdName; public int getNumPerPage() { return numPerPage; } public void setNumPerPage(int numPerPage) { this.numPerPage = numPerPage; } public int getPageNumShown() { return pageNumShown; } public void setPageNumShown(int pageNumShown) { this.pageNumShown = pageNumShown; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } // public String getPageSqlIdName() { // if(StringUtils.isBlank(pageSqlIdName)){ // return ("page_"+this.getTableName()+"_id").toUpperCase(); // } // return pageSqlIdName; // } public void setPageSqlIdName(String pageSqlIdName) { this.pageSqlIdName = pageSqlIdName; } // public String getCountPageSqlIdName() { // if(StringUtils.isBlank(countPageSqlIdName)){ // return ("count_page_"+this.getTableName()+"_id").toUpperCase(); // } // return countPageSqlIdName; // } public void setCountPageSqlIdName(String countPageSqlIdName) { this.countPageSqlIdName = countPageSqlIdName; } }
package oopsPractice; //abstract class abstract class Car{ //constructor Car() { System.out.println("Car classs"); } //abstract method abstract void gearChange(); void name() { System.out.println("CAR"); } } //inheritance class Swift extends Car{ @Override void name() { System.out.println("SWIFT CAR"); } void gearChange() { System.out.println("manually"); } } class Audi extends Car{ @Override void name() { System.out.println("AUDI CAR"); } void gearChange() { System.out.println("Auto gear"); } } public class AbstactionDemo { public static void main(String args[]) { //child ref and parent class /* Swift obj2 = new Car(); obj2.name(); obj2.gearChange(); */ //child ref and child class Audi obj = new Audi(); obj.name(); obj.gearChange(); System.out.println("........"); //parent ref and Parent class //cant create object abstrct class /* Car obj3 = new Car(); obj3.name(); //obj3.gearChange(); System.out.println("........"); */ //parent ref and child class Car obj4=new Swift(); obj4.name(); //obj4.gearChange(); System.out.println("........"); } }
package com.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Set; import com.configuration.DBConnect; import com.model.Member; public class MemberDao_imp implements MemberDao { @Override public int addmember(Member m) { int status =0; Connection connection = null; PreparedStatement preparedStatement =null; try { connection = DBConnect.getConnection(); preparedStatement =connection.prepareStatement(("insert into member values (?,?,?,?)")); preparedStatement.setInt(1, m.getMember_id()); preparedStatement.setString(2, m.getMember_name()); preparedStatement.setLong(3, m.getMobile()); preparedStatement.setString(4, m.getAddress()); status = preparedStatement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if(preparedStatement!=null) preparedStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(connection!=null) connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return status; } @Override public int removemember(String Member_name) { int status =0; Connection connection = null; PreparedStatement preparedStatement =null; try { connection = DBConnect.getConnection(); preparedStatement =connection.prepareStatement("delete from member where Member_name =?"); preparedStatement.setString(1, Member_name); status =preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if(preparedStatement!=null) preparedStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(connection!=null) connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return status; } @Override public int updatemember_byname(String membername,String addr) { int status =0; Connection connection = null; PreparedStatement preparedStatement =null; String sql ="update Member set address=? where member_name=?"; try { preparedStatement = DBConnect.getConnection().prepareStatement(sql); preparedStatement.setString(1, addr); preparedStatement.setString(2, membername); status =preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if(preparedStatement!=null) preparedStatement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { if(connection!=null) connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return status; } }
package org.proyectofinal.gestorpacientes.vista; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.ImageIcon; import javax.swing.JTextField; import java.awt.Font; import java.awt.Window; import javax.swing.JPasswordField; import javax.swing.JButton; import javax.swing.JCheckBox; import org.proyectofinal.gestorpacientes.controler.ControladorLogin; import org.proyectofinal.gestorpacientes.modelo.ModeloPaciente; import org.proyectofinal.gestorpacientes.modelo.ModeloUsuario; public class Login extends JFrame{ private JTextField usuario; private JPasswordField clave; private JButton btnAceptar; private JButton btnCancelar; public JTextField getUsuario() { return usuario; } public void setUsuario(JTextField usuario) { this.usuario = usuario; } public JPasswordField getClave() { return clave; } public void setClave(JPasswordField clave) { this.clave = clave; } public JButton getBtnAceptar() { return btnAceptar; } public void setBtnAceptar(JButton btnAceptar) { this.btnAceptar = btnAceptar; } public JButton getBtnCancelar() { return btnCancelar; } public void setBtnCancelar(JButton btnCancelar) { this.btnCancelar = btnCancelar; } public Login() { setTitle("Autenticacion"); setResizable(false); getContentPane().setLayout(null); setSize(446, 306); setLocationRelativeTo(null); JCheckBox chckbxNewCheckBox = new JCheckBox("Recordar clave"); chckbxNewCheckBox.setBounds(114, 185, 208, 23); getContentPane().add(chckbxNewCheckBox); JLabel lblClave = new JLabel("Clave"); lblClave.setFont(new Font("Tahoma", Font.PLAIN, 12)); lblClave.setBounds(117, 151, 36, 14); getContentPane().add(lblClave); usuario = new JTextField(); usuario.setBounds(173, 106, 152, 20); getContentPane().add(usuario); usuario.setColumns(10); JLabel lblNombre = new JLabel("Usuario"); lblNombre.setFont(new Font("Tahoma", Font.PLAIN, 12)); lblNombre.setBounds(117, 109, 46, 14); getContentPane().add(lblNombre); clave = new JPasswordField(); clave.setBounds(173, 149, 152, 20); getContentPane().add(clave); btnAceptar = new JButton("Ok"); btnAceptar.setBounds(245, 223, 89, 23); getContentPane().add(btnAceptar); btnCancelar = new JButton("Cancelar"); btnCancelar.setBounds(342, 223, 89, 23); getContentPane().add(btnCancelar); JLabel lblNewLabel = new JLabel(""); lblNewLabel.setIcon(new ImageIcon(Login.class.getResource("/Imagenes/login.png"))); lblNewLabel.setBounds(0, 0, 442, 83); getContentPane().add(lblNewLabel); new ControladorLogin(this,ModeloUsuario.getInstancia(false, false)); } }
package com.example.royal.app; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; /** * Created by user on 2017/7/25. */ public class CheckActivity extends AsyncTask<String,Void,String> { private Context context; public CheckActivity(Context context) { this.context = context; } protected void onPreExecute() {} protected String doInBackground(String... arg0){ String user = arg0[0]; String password = arg0[1]; String link; String data; BufferedReader bufferedReader; String result; try { data = "?user="+ URLEncoder.encode(user,"utf8"); data += "&password="+URLEncoder.encode(password,"utf8"); link = "http://192.168.0.2/insert.php"+data; URL url = new URL(link); HttpURLConnection con = (HttpURLConnection) url.openConnection(); bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream())); result = bufferedReader.readLine(); } catch (Exception e){ return new String("Exception: " + e.getMessage()); } return result; } protected void onPostExecute(String result){ String jsonStr = result; Log.d("result=",result); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); String query_result = jsonObj.getString("query_result"); if (query_result.equals("SUCCESS")) { Toast.makeText(context, "會員記錄建檔成功", Toast.LENGTH_SHORT).show(); }else if (query_result.equals("FAILURE")) { Toast.makeText(context, "會員記錄建檔失敗", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); Toast.makeText(context, "會員記錄建檔成功", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show(); } } }
package cn.wycclub.dao.po; import java.io.Serializable; import java.util.Date; /** * 订单和商品关联信息 * * @author WuYuchen * @create 2018-02-19 19:03 **/ public class ProductOrderConnInfo implements Serializable { protected int oid; protected int pid; protected int quantity; protected Date gmtCreate = new Date(); protected Date gmtModified; public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public int getOid() { return oid; } public void setOid(int oid) { this.oid = oid; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } @Override public String toString() { return "ProductOrderConnInfo{" + "oid=" + oid + ", pid=" + pid + ", quantity=" + quantity + ", gmtCreate=" + gmtCreate.toLocaleString() + ", gmtModified=" + gmtModified + '}'; } }
package com.tencent.mm.plugin.mmsight.ui; import com.tencent.mm.plugin.mmsight.ui.a.7; class a$7$1 implements Runnable { final /* synthetic */ 7 lpo; a$7$1(7 7) { this.lpo = 7; } public final void run() { if (this.lpo.lpk.eXe != null) { this.lpo.lpk.eXe.dismiss(); } if (this.lpo.lpk.lpc != null) { this.lpo.lpk.lpc.onError(); } } }
package org.fuusio.api.rest; import org.fuusio.api.component.Component; /** * {@link RequestManager} define interface for a {@link Component} that is used to execute * {@link RestRequest}s. */ public interface RequestManager<T_Request extends RestRequest> extends Component { <T extends T_Request> T execute(final T_Request request); void cancelPendingRequests(final Object tag); void cancelAllRequests(); void clearRequestCache(); }
/* * #%L * Janus * %% * Copyright (C) 2014 KIXEYE, Inc * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.kixeye.janus; import com.codahale.metrics.MetricRegistry; import com.kixeye.janus.Janus.Builder; import com.kixeye.janus.loadbalancer.LoadBalancer; import com.kixeye.janus.loadbalancer.RandomLoadBalancer; import com.kixeye.janus.loadbalancer.ZoneAwareLoadBalancer; import com.kixeye.janus.serverlist.ConfigServerList; import com.kixeye.janus.serverlist.ConstServerList; import com.netflix.config.ConfigurationManager; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.lang.reflect.Field; //import com.kixeye.janus.Janus.Builder; public class JanusTest { private final String VIP_TEST = "kvpservice"; private static long DEFAULT_REFRESH_INTERVAL_IN_MILLIS = 500l; @Before public void setConfiguration() { ConfigurationManager.getConfigInstance().setProperty("janus.errorThresholdPerSec", 3); ConfigurationManager.getConfigInstance().setProperty("janus.shortCircuitDuration", 1000); ConfigurationManager.getConfigInstance().setProperty("janus.refreshIntervalInMillis", DEFAULT_REFRESH_INTERVAL_IN_MILLIS); ConfigurationManager.getConfigInstance().clearProperty(ConfigServerList.PROPERTY_NAME_PREFIX + "." + VIP_TEST); } @Test public void GetServerTest() { Janus janus = new Janus( VIP_TEST, new ConstServerList(VIP_TEST,"http://localhost:0001","http://localhost:002","http://localhost:003"), new RandomLoadBalancer(), new ServerStatsFactory(ServerStats.class,new MetricRegistry())); // should randomly a server from the list ServerStats firstResult = janus.getServer(); boolean randomSuccess = false; for (int i = 0; i < 10; i++) { ServerStats nextResult = janus.getServer(); if (firstResult != nextResult) { randomSuccess = true; break; } } Assert.assertTrue(randomSuccess); } @Test public void RefreshIntervalTest() { Janus janus = new Janus( VIP_TEST, new ConstServerList(VIP_TEST,"http://localhost:0001","http://localhost:002","http://localhost:003"), new RandomLoadBalancer(), new ServerStatsFactory(ServerStats.class,new MetricRegistry()) ); Assert.assertEquals(DEFAULT_REFRESH_INTERVAL_IN_MILLIS, janus.getRefreshInterval()); janus.setRefreshInterval(DEFAULT_REFRESH_INTERVAL_IN_MILLIS+1); Assert.assertEquals(DEFAULT_REFRESH_INTERVAL_IN_MILLIS+1, janus.getRefreshInterval()); } @Test public void ShortCircuitTest() throws InterruptedException { Janus janus = new Janus( VIP_TEST, new ConstServerList(VIP_TEST,"http://localhost:8080"), new RandomLoadBalancer(), new ServerStatsFactory(ServerStats.class,new MetricRegistry()) ); ServerStats stats = janus.getServer(); Assert.assertEquals( stats.getServerInstance().isShortCircuited(), false ); // short circuit should be 0 at this point Assert.assertTrue( stats.getServerInstance().getCircuitBreakerRemainingTime() <= 0.0); // mark 3 errors and the 3rd should cause the server instance to short circuit stats.incrementErrors(); Assert.assertEquals(stats.getServerInstance().isShortCircuited(), false); stats.incrementErrors(); Assert.assertEquals(stats.getServerInstance().isShortCircuited(), false); stats.incrementErrors(); Assert.assertEquals(stats.getServerInstance().isShortCircuited(), true); // this should return null as there are no available servers ServerStats stats2 = janus.getServer(); Assert.assertNull(stats2); // wait 1 seconds and the instance should return to normal Thread.sleep(1005); Assert.assertEquals(stats.getServerInstance().isShortCircuited(), false); // we should get a server again since the short circuit expired stats = janus.getServer(); Assert.assertNotNull(stats); // mark 3 errors and the 3rd should cause the server instance to short circuit again stats.incrementErrors(); Assert.assertEquals(stats.getServerInstance().isShortCircuited(), false); stats.incrementErrors(); Assert.assertEquals(stats.getServerInstance().isShortCircuited(), false); stats.incrementErrors(); Assert.assertEquals(stats.getServerInstance().isShortCircuited(), true); // this is a second short circuit in under the duration so timeout is longer Assert.assertTrue(stats.getServerInstance().getCircuitBreakerRemainingTime() > 1.0); } @Test public void noServersTest() { Janus janus = new Janus( VIP_TEST, new ConstServerList(VIP_TEST), new RandomLoadBalancer(), new ServerStatsFactory(ServerStats.class,new MetricRegistry()) ); Assert.assertNull(janus.getServer()); } @Test public void defaultBuilder() { Janus janus = Janus.builder(VIP_TEST).build(); Assert.assertNull(janus.getServer()); } @Test public void builderWithServers(){ Janus janus = Janus.builder(VIP_TEST).withServers("http://localhost:8080").build(); Assert.assertEquals("localhost", janus.getServer().getServerInstance().getHost()); } @Test public void builderWithConstServerList(){ Janus janus = Janus.builder(VIP_TEST).withServerList(new ConstServerList(VIP_TEST, "http://localhost:8080")).build(); Assert.assertEquals("localhost", janus.getServer().getServerInstance().getHost()); } @Test public void builderWithRefreshInterval(){ Janus janus = Janus.builder(VIP_TEST).withRefreshIntervalInMillis(100).build(); Assert.assertEquals(100, janus.getRefreshInterval()); } @Test public void builder_withConstServerList() { Builder builder = Janus.builder(VIP_TEST); builder.withServerList(new ConstServerList(VIP_TEST, "http://localhost:0001")); Janus janus = builder.build(); Assert.assertEquals("localhost", janus.getServer().getServerInstance().getHost()); } @Test public void builder_withServers() { Builder builder = Janus.builder(VIP_TEST); builder.withServers("http://localhost:0001"); Janus janus = builder.build(); Assert.assertEquals("localhost", janus.getServer().getServerInstance().getHost()); } @Test public void builder_withRandomLoadBalancing() { Builder builder = Janus.builder(VIP_TEST); builder.withRandomLoadBalancing(); Janus janus = builder.build(); Assert.assertNull("localhost", janus.getServer()); assertFieldType(janus, LoadBalancer.class, RandomLoadBalancer.class); } @Test public void builder_withZoneAwardLoadBalancing() { Builder builder = Janus.builder(VIP_TEST); builder.withZoneAwareLoadBalancing("default"); Janus janus = builder.build(); Assert.assertNull("localhost", janus.getServer()); assertFieldType(janus, LoadBalancer.class, ZoneAwareLoadBalancer.class); } @Test public void builder_withZoneAwardLoadBalancing_changeMetricRegistry() { Builder builder = Janus.builder(VIP_TEST); builder.withZoneAwareLoadBalancing("default"); builder.withMetricRegistry(new MetricRegistry()); Janus janus = builder.build(); Assert.assertNull("localhost", janus.getServer()); assertFieldType(janus, LoadBalancer.class, ZoneAwareLoadBalancer.class); } //used to assert that a field is of the expected type private void assertFieldType(Janus janus, Class<?> interfaceClass, Class<?> expectedClass){ Field field = null; for (Field candidateField : Janus.class.getDeclaredFields()) { if (candidateField.getType().isAssignableFrom(interfaceClass)) { field = candidateField; break; } } field.setAccessible(true); try { Assert.assertEquals(expectedClass, field.get(janus).getClass()); } catch (Exception e) { throw new RuntimeException(e); } } }
package laioffer.serial; /** * Created by mengzhou on 6/25/17. */ public class AboutGame { class NQueen { } class Sudoku { } }
package com.tencent.tencentmap.mapsdk.a; public abstract class ol { public kk a; }
package ua.goit.timonov.enterprise.web; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import ua.goit.timonov.enterprise.exceptions.NoItemInDbException; import ua.goit.timonov.enterprise.model.Employee; import ua.goit.timonov.enterprise.service.EmployeeService; import ua.goit.timonov.enterprise.web.validate.EmployeeValidate; import java.util.Map; /** * Spring MVC controller for mapping service pages for employees */ @ControllerAdvice @Controller @RequestMapping("/service/employee") @SessionAttributes("employeeView") public class EmployeeServiceController { public static final String PATH_EMPLOYEES = "service/employee/employees"; public static final String PATH_ADD = "service/employee/add"; public static final String PATH_EDIT = "service/employee/edit"; public static final String PATH_ERROR = "service/errorMessage"; public static final String ERROR_MESSAGE = "errorMessage"; public static final String EMPLOYEES = "employees"; public static final String EMPLOYEE_VALIDATE = "employeeValidate"; public static final String EMPLOYEE_VIEW = "employeeView"; private EmployeeService employeeService; @Autowired public void setEmployeeService(EmployeeService employeeService) { this.employeeService = employeeService; } @RequestMapping(value = "/employees", method = RequestMethod.GET) public String serviceEmployees(Map<String, Object> model) { model.put(EMPLOYEES, employeeService.getAllEmployees()); return PATH_EMPLOYEES; } @RequestMapping(value = "/add", method = RequestMethod.GET) public String getEmployeeToAdd(Map<String, Object> model) { model.put(EMPLOYEE_VALIDATE, new EmployeeValidate()); model.put(EMPLOYEE_VIEW, new EmployeeView()); return PATH_ADD; } @RequestMapping(value = "/add", method = RequestMethod.POST) public String addEmployee(Map<String, Object> model, @ModelAttribute("employeeView") EmployeeView employeeView, @ModelAttribute("employeeValidate") EmployeeValidate employeeValidate) { if (employeeValidate.isValid(employeeView)) { Employee employee = employeeView.getEmployeeFromView(); employeeService.add(employee); model.put("employees", employeeService.getAllEmployees()); return PATH_EMPLOYEES; } else { model.put("employeeValidate", employeeValidate); model.put("employeeView", employeeView); return PATH_ADD; } } @RequestMapping(value = "/edit", method = RequestMethod.GET) public String editEmployeeById(Map<String, Object> model, @RequestParam(value="id", required=true) Integer id) { try { Employee employee = employeeService.getEmployeeById(id); model.put("employeeView", new EmployeeView(employee)); model.put("employeeValidate", new EmployeeValidate()); return PATH_EDIT; } catch (NoItemInDbException e) { model.put(ERROR_MESSAGE, e.getMessage()); return PATH_ERROR; } } @RequestMapping(value = "/editByName", method = RequestMethod.GET) public String editEmployeeByName(Map<String, Object> model, @RequestParam(value="name", required=true) String name, @RequestParam(value="surname", required=true) String surname) { try { Employee employee = employeeService.getEmployeeByName(name, surname); model.put("employeeView", new EmployeeView(employee)); model.put("employeeValidate", new EmployeeValidate()); return PATH_EDIT; } catch (NoItemInDbException e) { model.put(ERROR_MESSAGE, e.getMessage()); return PATH_ERROR; } } @RequestMapping(value = "/edit", method = RequestMethod.POST) public String saveEditDish(Map<String, Object> model, @RequestParam(value="id", required=true) Integer id, @ModelAttribute("employeeView") EmployeeView employeeView, @ModelAttribute("employeeValidate") EmployeeValidate employeeValidate) { if (employeeValidate.isValid(employeeView)) { Employee employee = employeeView.getEmployeeFromView(); employee.setId(id); employeeService.update(employee); model.put("employees", employeeService.getAllEmployees()); return PATH_EMPLOYEES; } else { model.put("employeeView", employeeView); model.put("employeeValidate", employeeValidate); return PATH_EDIT; } } }
package org.tellervo.desktop.tridasv2.ui; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.tellervo.desktop.core.App; import org.tellervo.desktop.tridasv2.ui.support.TridasEntityProperty; import org.tellervo.desktop.tridasv2.ui.support.TridasProjectDictionaryProperty; import org.tellervo.schema.UserExtendableDataType; import org.tellervo.schema.WSIUserDefinedField; import org.tridas.schema.TridasElement; import org.tridas.schema.TridasEntity; import org.tridas.schema.TridasFile; import org.tridas.schema.TridasGenericField; import org.tridas.schema.TridasObject; import org.tridas.schema.TridasSample; import com.dmurph.mvc.model.MVCArrayList; import com.l2fprod.common.propertysheet.Property; import com.l2fprod.common.propertysheet.PropertySheetPanel; /** * This class exists to kludge over a bug in PropertySheetPanel, whereby * the array of TridasFiles is not written to the entity when writeToObject * is called. * * I presume this bug is also an issue for any other arrays, so be warned! * * @author pwb48 * */ public class TellervoPropertySheetPanel extends PropertySheetPanel { private final static Logger log = LoggerFactory.getLogger(TellervoPropertySheetPanel.class); private static final long serialVersionUID = 1L; public TellervoPropertySheetPanel(TellervoPropertySheetTable propertiesTable) { super(propertiesTable); } @Override public void readFromObject(Object object) { super.readFromObject(object); Property[] prop = this.getProperties(); // Handle UserDefined Fields generically if(object instanceof TridasEntity) { MVCArrayList<WSIUserDefinedField> udfdictionary = App.dictionary.getMutableDictionary("userDefinedFieldDictionary"); TridasEntity entity = (TridasEntity) object; if (entity.isSetGenericFields()) { for(TridasGenericField gf : entity.getGenericFields()) { if (gf.getName().startsWith("userDefinedField")) { for(WSIUserDefinedField fld : udfdictionary) { if(fld.getName().equals(gf.getName())) { for(Property p2 : prop) { TridasEntityProperty tep2 = (TridasEntityProperty) p2; if(!tep2.lname.equals("custom fields")) continue; for(Property p : tep2.getChildProperties()) { TridasEntityProperty tep = (TridasEntityProperty) p; if(tep.humanReadableName!=null && tep.humanReadableName.equals(fld.getLongfieldname())) { try{ if(fld.getDatatype().equals(UserExtendableDataType.XS___BOOLEAN)) { Boolean b = false; if(gf.getValue().toLowerCase().equals("true") || gf.getValue().toLowerCase().equals("t")) { b = true; } p.setValue(b); } else if (fld.getDatatype().equals(UserExtendableDataType.XS___FLOAT)) { p.setValue(Float.parseFloat(gf.getValue())); } else if (fld.getDatatype().equals(UserExtendableDataType.XS___INT)) { p.setValue(Integer.parseInt(gf.getValue())); } else if (fld.getDatatype().equals(UserExtendableDataType.XS___STRING)) { p.setValue(gf.getValue()); } else { log.error("Unsupported data type for generic field"); } } catch (NumberFormatException e) { log.error("Invalid value for generic field. Doesn't match specified data type"); } } } } } } } } } } // Handle Object-specific generic fields if(object instanceof TridasObject) { TridasObject obj = (TridasObject) object; TellervoGenericFieldProperty refField = TellervoGenericFieldProperty.getObjectCodeProperty(); TellervoGenericFieldProperty refField2 = TellervoGenericFieldProperty.getVegetationTypeProperty(); if (obj.isSetGenericFields()) { for(TridasGenericField gf : obj.getGenericFields()) { if(gf.getName().equals(refField.getXMLFieldName())) { for(Property p : prop) { TridasEntityProperty tep = (TridasEntityProperty) p; if(tep.qname.equals(refField.qname)) { p.setValue(gf.getValue()); } } } else if(gf.getName().equals(refField2.getXMLFieldName())) { for(Property p : prop) { TridasEntityProperty tep = (TridasEntityProperty) p; if(tep.qname.equals(refField2.qname)) { p.setValue(gf.getValue()); } } } else if(gf.getName().equals("tellervo.object.projectid")) { for(Property p : prop) { if(p instanceof TridasProjectDictionaryProperty) { p.setValue(App.dictionary.getTridasProjectByID(gf.getValue())); } } } } } } // Handle sample specific generic fields if(object instanceof TridasSample) { TridasSample sample = (TridasSample) object; TellervoGenericFieldProperty externalID = TellervoGenericFieldProperty.getSampleExternalIDProperty(); TellervoGenericFieldProperty curationStatus = TellervoGenericFieldProperty.getSampleCurationStatusProperty(); TellervoGenericFieldProperty sampleStatus = TellervoGenericFieldProperty.getSampleStatusProperty(); if (sample.isSetGenericFields()) { for(TridasGenericField gf : sample.getGenericFields()) { if(gf.getName().equals(externalID.getXMLFieldName())) { for(Property p : prop) { TridasEntityProperty tep = (TridasEntityProperty) p; //log.debug("Property name : "+tep.qname); if(tep.qname.equals(externalID.qname)) { p.setValue(gf.getValue()); } } } else if(gf.getName().equals(curationStatus.getXMLFieldName())) { for(Property p : prop) { TridasEntityProperty tep = (TridasEntityProperty) p; //log.debug("Property name : "+tep.qname); if(tep.qname.equals(curationStatus.qname)) { p.setValue(gf.getValue()); } } } else if(gf.getName().equals(sampleStatus.getXMLFieldName())) { for(Property p : prop) { TridasEntityProperty tep = (TridasEntityProperty) p; //log.debug("Property name : "+tep.qname); if(tep.qname.equals(sampleStatus.qname)) { p.setValue(gf.getValue()); } } } } } } } @Override public void writeToObject(Object data) { // ensure pending edits are committed getTable().commitEditing(); Property[] properties = getProperties(); for (int i = 0, c = properties.length; i < c; i++) { properties[i].writeToObject(data); } Property[] prop2 = this.getProperties(); for(Property p : prop2) { // Find any properties called 'files' if(p.getName().equals("files")) { Object files = p.getValue(); if(data instanceof TridasObject) { ((TridasObject)data).setFiles((List<TridasFile>) files); } else if(data instanceof TridasElement) { ((TridasElement)data).setFiles((List<TridasFile>) files); } else if(data instanceof TridasSample) { ((TridasSample)data).setFiles((List<TridasFile>) files); } } if(p instanceof TridasProjectDictionaryProperty) { TridasProjectDictionaryProperty tgfp = (TridasProjectDictionaryProperty) p; TellervoGenericFieldProperty.addOrReplaceGenericField((TridasEntity)data, tgfp.getTridasGenericField()); } if(p instanceof TellervoGenericFieldProperty) { TellervoGenericFieldProperty tgfp = (TellervoGenericFieldProperty) p; TellervoGenericFieldProperty.addOrReplaceGenericField((TridasEntity)data, tgfp.getTridasGenericField()); } // Look inside custom fields category TridasEntityProperty tep2 = (TridasEntityProperty) p; if(tep2.lname.equals("custom fields")) { for(Property p3 : tep2.getChildProperties()) { if(p3 instanceof TellervoGenericFieldProperty) { TellervoGenericFieldProperty tgfp = (TellervoGenericFieldProperty) p3; TellervoGenericFieldProperty.addOrReplaceGenericField((TridasEntity)data, tgfp.getTridasGenericField()); } } } } } }
package cn.canlnac.onlinecourse.data.entity; import com.google.gson.annotations.SerializedName; import java.util.List; /** * 关注. */ public class FollowerEntity { @SerializedName("total") private int total; @SerializedName("users") private List<LoginEntity> users; public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public List<LoginEntity> getUsers() { return users; } public void setUsers(List<LoginEntity> users) { this.users = users; } }
package com.ahmetkizilay.yatlib4j.datatypes; import java.math.BigInteger; import java.util.ArrayList; import java.util.Date; import java.util.Hashtable; import com.ahmetkizilay.yatlib4j.utils.GenericUtils; import net.minidev.json.JSONObject; import net.minidev.json.JSONValue; public class Tweet { private Object annotations; private ArrayList<Contributor> contributors; private Coordinates coordinates; private String createdAt; private Object currentUserRetweet; private Entities entities; private Integer favoriteCount; private Boolean favorited; private String filterLevel; private Object geo; private BigInteger id; private String idStr; private String inReplyToScreenName; private BigInteger inReplyToStatusId; private String inReplyToStatusIdStr; private BigInteger inReplyToUserId; private String inReplyToUserIdStr; private String lang; private Places place; private Boolean possiblySensitive; private Hashtable<String, String> scope; private int retweetCount; private boolean retweeted; private String source; private String text; private boolean truncated; private Object users; // TODO to be implemented private boolean withheldCopyright; // TODO to be implemented private Object witheldInCountries; // TODO to be implemented private String withheldScope; // TODO to be implemented private String jsonString; public String getJSONString() { return this.jsonString; } private void setJSONString(String jsonString) { this.jsonString = jsonString; } public Object getAnnotations() { return this.annotations; } /*** * Unused. Future/beta home for status annotations.<p> * @param annotations */ public void setAnnotations(Object annotations) { this.annotations = annotations; } public ArrayList<Contributor> getContributors() { return this.contributors; } /*** * Nullable. An collection of brief user objects (usually only one) indicating<p> * users who contributed to the authorship of the tweet, on behalf of the official tweet author<p> * @param contributors */ public void setContributors(ArrayList<Contributor> contributors) { this.contributors = contributors; } public Coordinates getCoordinates() { return this.coordinates; } /*** * Nullable. Represents the geographic location of this Tweet as reported by the user or client<p> * application. The inner coordinates array is formatted as geoJSON (longitude first, then latitude).<p> * * @param coordinates */ public void setCoordinates(Coordinates coordinates) { this.coordinates = coordinates; } public Object getCurrentUserRetweet() { return this.currentUserRetweet; } /*** * Perspectival. Only surfaces on methods supporting the include_my_retweet parameter, when set<p> * to true. Details the Tweet ID of the user's own retweet (if existent) of this Tweet.<p> * * TODO Not Really Implemented Yet * * @param currentUserRetweet */ public void setCurrentUserRetweet(Object currentUserRetweet) { this.currentUserRetweet = currentUserRetweet; } public Entities getEntities() { return this.entities; } /*** * Entities which have been parsed out of the text of the Tweet. Additionally see Tweet Entities.<p> * * @return */ public void setEntities(Entities entities) { this.entities = entities; } public Integer getFavoriteCount() { return this.favoriteCount; } /*** * Nullable. Indicates approximately how many times this Tweet has been "favorited" by Twitter users.<p> * * @param favoriteCount */ public void setFavoriteCount(Integer favoriteCount) { this.favoriteCount = favoriteCount; } public Boolean getFavorited() { return this.favorited; } /*** * Nullable. Perspectival. Indicates whether this Tweet has been favorited by the authenticating user.<p> * * @param favorited */ public void setFavorited(Boolean favorited) { this.favorited = favorited; } public String getFilterLevel() { return this.filterLevel; } /*** * Indicates the maximum value of the filter_level parameter which may be used and still stream this Tweet.<p> * So a value of medium will be streamed on none, low, and medium streams. See this announcement for more information. <p> * * @param filterLevel */ public void setFilterLevel(String filterLevel) { this.filterLevel = filterLevel; } @Deprecated public Object getGeo() { return this.geo; } /*** * Deprecated. Nullable. Use the "coordinates" field instead<p> * * @param geo */ @Deprecated public void setGeo(Object geo) { this.geo = geo; } public BigInteger getId() { return this.id; } /*** * The integer representation of the unique identifier for this Tweet.<p> * This number is greater than 53 bits and some programming languages may<p> * have difficulty/silent defects in interpreting it. Using a signed 64 bit<p> * integer for storing this identifier is safe. Use id_str for fetching the<p> * identifier to stay on the safe side. See Twitter IDs, JSON and Snowflake.<p> * * @param id */ public void setId(BigInteger id) { this.id = id; } public String getIdStr() { return this.idStr; } /*** * The string representation of the unique identifier for this Tweet.<p> * Implementations should use this rather than the large integer in id.<p> * * @param idStr */ public void setIdStr(String idStr) { this.idStr = idStr; } public String getInReplyToScreenName() { return this.inReplyToScreenName; } /*** * Nullable. If the represented Tweet is a reply, this field will contain the screen name<p> * of the original Tweet's author.<p> * * @param inReplyToScreenName */ public void setInReplyToScreenName(String inReplyToScreenName) { this.inReplyToScreenName = inReplyToScreenName; } public BigInteger getInReplyToStatusId() { return this.inReplyToStatusId; } /*** * Nullable. If the represented Tweet is a reply, this field will contain the integer representation<p> * of the original Tweet's ID.<p> * * @param inReplyToStatusId */ public void setInReplyToStatusId(BigInteger inReplyToStatusId) { this.inReplyToStatusId = inReplyToStatusId; } public String getInReplyToStatusIdStr() { return this.inReplyToStatusIdStr; } /*** * Nullable. If the represented Tweet is a reply, this field will contain the string representation<p> * of the original Tweet's ID.<p> * * @param inReplyToStatusId */ public void setInReplyToStatusIdStr(String inReplyToStatusIdStr) { this.inReplyToStatusIdStr = inReplyToStatusIdStr; } public BigInteger getInReplyToUserId() { return this.inReplyToUserId; } /*** * Nullable. If the represented Tweet is a reply, this field will contain the integer representation<p> * of the original Tweet's author ID. This will not necessarily always be the user directly mentioned<p> * in the Tweet.<p> * * @param inReplyToStatusId */ public void setInReplyToUserId(BigInteger inReplyToUserId) { this.inReplyToUserId = inReplyToUserId; } public String getInReplyToUserIdStr() { return this.inReplyToUserIdStr; } /*** * Nullable. If the represented Tweet is a reply, this field will contain the string representation<p> * of the original Tweet's author ID. This will not necessarily always be the user directly mentioned<p> * in the Tweet.<p> * * @param inReplyToUserIdStr */ public void setInReplyToUserIdStr(String inReplyToUserIdStr) { this.inReplyToUserIdStr = inReplyToUserIdStr; } public String getLang() { return this.lang; } /*** * Nullable. When present, indicates a BCP 47 language identifier corresponding to the machine-detected<p> * language of the Tweet text, or "und" if no language could be detected.<p> * * @param lang */ public void setLang(String lang) { this.lang = lang; } public Places getPlace() { return this.place; } /*** * Nullable. When present, indicates that the tweet is associated (but not<p> * necessarily originating from) a Place.<p> * * @param place */ public void setPlace(Places place) { this.place = place; } public Boolean getPossiblySensitive() { return this.possiblySensitive; } /*** * Nullable. This field only surfaces when a tweet contains a link. The meaning<p> * of the field doesn't pertain to the tweet content itself, but instead it is an<p> * indicator that the URL contained in the tweet may contain content or media identified<p> * as sensitive content.<p> * * @param possibleSensitive */ public void setPossibleSensitive(Boolean possiblySensitive) { this.possiblySensitive = possiblySensitive; } public Hashtable<String, String> getScope() { return this.scope; } /*** * A set of key-value pairs indicating the intended contextual delivery of the containing<p> * Tweet. Currently used by Twitter's Promoted Products.<p> * * @param scope */ public void setScope(Hashtable<String, String> scope) { this.scope = scope; } public int getRetweetCount() { return this.retweetCount; } /*** * Number of times this Tweet has been retweeted. This field is no longer capped at 99<p> * and will not turn into a String for "100+"<p> * * @param retweetCount */ public void setRetweetCount(int retweetCount) { this.retweetCount = retweetCount; } public boolean isRetweeted() { return this.retweeted; } /*** * Perspectival. Indicates whether this Tweet has been retweeted by the authenticating user.<p> * * @param retweeted */ public void setRetweeted(boolean retweeted) { this.retweeted = retweeted; } public String getSource() { return this.source; } /*** * Utility used to post the Tweet, as an HTML-formatted string. Tweets from the Twitter website<p> * have a source value of web.<p> * * @param source */ public void setSource(String source) { this.source = source; } public String getText() { return this.text; } /*** * The actual UTF-8 text of the status update. See twitter-text for details on what is currently<p> * considered valid characters.<p> * * @param text */ public void setText(String text) { this.text = text; } public boolean getTruncated() { return this.truncated; } /*** * Indicates whether the value of the text parameter was truncated, for example, as a result of a retweet<p> * exceeding the 140 character Tweet length. Truncated text will end in ellipsis, like this ... Since Twitter<p> * now rejects long Tweets vs truncating them, the large majority of Tweets will have this set to false.<p> * Note that while native retweets may have their toplevel text property shortened, the original text will be<p> * available under the retweeted_status object and the truncated parameter will be set to the value of the original<p> * status (in most cases, false).<p> * * @param truncated */ public void setTruncated(boolean truncated) { this.truncated = truncated; } public String getCreatedAt() { return this.createdAt; } public Date getCreatedAtDate() throws Exception { return GenericUtils.parseDateString(this.createdAt); } public void setCreatedAt(String createdAt) { this.createdAt = createdAt; } public static Tweet fromJSONString(String jsonString) { return fromJSONString(jsonString, false); } public static Tweet fromJSONString(String jsonString, boolean keepData) { JSONObject jsonObject = (JSONObject) JSONValue.parse(jsonString); return fromJSON(jsonObject, keepData); } public static Tweet fromJSON(JSONObject jsonData) { return fromJSON(jsonData, false); } public static Tweet fromJSON(JSONObject jsonData, boolean keepData) { Tweet tweet = new Tweet(); tweet.setIdStr((String) jsonData.get("id_str")); tweet.setText((String) jsonData.get("text")); tweet.setCreatedAt((String) jsonData.get("created_at")); tweet.setSource((String)jsonData.get("source")); if(keepData) { tweet.setJSONString(jsonData.toJSONString()); } return tweet; } }
// // DO NOT EDIT THIS FILE, IT HAS BEEN GENERATED USING AndroidAnnotations 3.0.1. // package tk.woppo.sunday.ui.fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import org.androidannotations.api.view.HasViews; import org.androidannotations.api.view.OnViewChangedListener; import org.androidannotations.api.view.OnViewChangedNotifier; import tk.woppo.sunday.R.layout; public final class DrawerFragment_ extends DrawerFragment implements HasViews, OnViewChangedListener { private final OnViewChangedNotifier onViewChangedNotifier_ = new OnViewChangedNotifier(); private View contentView_; @Override public void onCreate(Bundle savedInstanceState) { OnViewChangedNotifier previousNotifier = OnViewChangedNotifier.replaceNotifier(onViewChangedNotifier_); init_(savedInstanceState); super.onCreate(savedInstanceState); OnViewChangedNotifier.replaceNotifier(previousNotifier); } public View findViewById(int id) { if (contentView_ == null) { return null; } return contentView_.findViewById(id); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { contentView_ = super.onCreateView(inflater, container, savedInstanceState); if (contentView_ == null) { contentView_ = inflater.inflate(layout.fragment_drawer, container, false); } return contentView_; } private void init_(Bundle savedInstanceState) { OnViewChangedNotifier.registerOnViewChangedListener(this); } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); onViewChangedNotifier_.notifyViewChanged(this); } public static DrawerFragment_.FragmentBuilder_ builder() { return new DrawerFragment_.FragmentBuilder_(); } @Override public void onViewChanged(HasViews hasViews) { ivWeatherImg = ((ImageView) hasViews.findViewById(tk.woppo.sunday.R.id.drawer_weather_img)); tvChuanyi = ((TextView) hasViews.findViewById(tk.woppo.sunday.R.id.drawer_chuanyi)); tvGanmao = ((TextView) hasViews.findViewById(tk.woppo.sunday.R.id.drawer_ganmao)); ivWeather = ((ImageView) hasViews.findViewById(tk.woppo.sunday.R.id.drawer_weather)); tvXiche = ((TextView) hasViews.findViewById(tk.woppo.sunday.R.id.drawer_xiche)); tvTemp = ((TextView) hasViews.findViewById(tk.woppo.sunday.R.id.drawer_temp)); tvTigan = ((TextView) hasViews.findViewById(tk.woppo.sunday.R.id.drawer_tigan)); tvWeather = ((TextView) hasViews.findViewById(tk.woppo.sunday.R.id.drawer_tv_weather)); tvZhiwaixian = ((TextView) hasViews.findViewById(tk.woppo.sunday.R.id.drawer_ziwaixian)); tvYundong = ((TextView) hasViews.findViewById(tk.woppo.sunday.R.id.drawer_yundong)); { View view = hasViews.findViewById(tk.woppo.sunday.R.id.drawer_add_city); if (view!= null) { view.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { DrawerFragment_.this.clickAddCity(); } } ); } } { View view = hasViews.findViewById(tk.woppo.sunday.R.id.drawer_del_city); if (view!= null) { view.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { DrawerFragment_.this.clickDelCity(); } } ); } } { View view = hasViews.findViewById(tk.woppo.sunday.R.id.drawwer_setting); if (view!= null) { view.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { DrawerFragment_.this.clickSetting(); } } ); } } { View view = hasViews.findViewById(tk.woppo.sunday.R.id.drawer_exit); if (view!= null) { view.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { DrawerFragment_.this.clickExit(); } } ); } } initFragment(); } public static class FragmentBuilder_ { private Bundle args_; private FragmentBuilder_() { args_ = new Bundle(); } public DrawerFragment build() { DrawerFragment_ fragment_ = new DrawerFragment_(); fragment_.setArguments(args_); return fragment_; } } }
package edu.cmu.lti.bio.alkesh.tools; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; //import java.util.Iterator; //import java.util.regex.Matcher; //import java.util.regex.Pattern; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.client.solrj.response.TermsResponse; import org.apache.solr.client.solrj.response.TermsResponse.Term; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.SolrInputDocument; import org.apache.solr.common.params.MapSolrParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.NamedList; import org.apache.uima.UIMAFramework; import org.apache.uima.cas.CAS; import org.apache.uima.cas.impl.XmiCasDeserializer; import org.apache.uima.collection.CollectionException; import org.apache.uima.resource.metadata.FsIndexDescription; import org.apache.uima.resource.metadata.TypeSystemDescription; import org.apache.uima.util.CasCreationUtils; import org.apache.uima.util.XMLInputSource; import org.jsoup.Jsoup; import org.jsoup.select.Elements; import java.util.Iterator; import edu.cmu.lti.oaqa.core.provider.solr.SolrWrapper; public class LanguageModeling { String XMI_REPOSITORY = "C:/Users/alkesh/Downloads/Trec06_annotated_xmi/"; String TYPE_DESC_XML = "src/main/resources/edu/cmu/lti/oaqa/bio/model/bioTypes.xml"; String SOLR_SERVER_URL = "http://localhost:8983/solr/genomics-legalspan/"; SolrWrapper solrWrapper = null; public LanguageModeling() { try { solrWrapper = new SolrWrapper(SOLR_SERVER_URL, null, null, null); } catch (Exception e) { e.printStackTrace(); } } public static void main(String args[]) { try { LanguageModeling main = new LanguageModeling(); //main.findSimilarity("What is the role of PrnP in mad cow disease", //""); } catch (Exception e) { e.printStackTrace(); } finally { // if (solrWrapper != null) { solrWrapper.close(); } } } public void indexPassages() throws Exception { File files[] = new File(XMI_REPOSITORY).listFiles(); //IndexingUtils indexUtils=new IndexingUtils(solrWrapper.getServer()); XMLInputSource input = new XMLInputSource(TYPE_DESC_XML); TypeSystemDescription typeDesc = UIMAFramework.getXMLParser() .parseTypeSystemDescription(input); CAS cas = CasCreationUtils.createCas(typeDesc, null, new FsIndexDescription[0]); for (int i = 0; i < files.length; i++) { if (i > 1) { break; } String currentFile = files[i].getAbsolutePath(); FileInputStream inputStream = new FileInputStream(currentFile); try { XmiCasDeserializer.deserialize(inputStream, cas, true); } catch (Exception e) { throw new CollectionException(e); } finally { inputStream.close(); } String fileName = files[i].getName(); String id = fileName.replace(".xmi", "").trim(); String htmlText = cas.getDocumentText(); Elements paraElements = Jsoup.parse(htmlText, "").select("P"); ArrayList<String> paragraphs = new ArrayList<String>(); for (int k = 0; k < paraElements.size(); k++) { String paragraph = paraElements.get(k).text(); // System.out.println(paragraph); // System.out.println("==================================="); paragraphs.add(paragraph); } String docText = Jsoup.parse(htmlText).text(); // System.out.println("Total text: "+docText.length()); // System.out.println("Para text: "+docText.length()); // System.out.println(docText); Date now = new Date(); HashMap<String, Object> hshMap = new HashMap<String, Object>(); hshMap.put("id", id); // hshMap.put("html text", htmlText); hshMap.put("text", docText); hshMap.put("paragraph", paragraphs); hshMap.put("timestamp", now); //SolrInputDocument solrDoc = indexUtils.makeSolrDocument(hshMap); //String docXML = ClientUtils.toXML(solrDoc); //indexUtils.indexDocument(docXML); // System.out.println(docText); // if (i % 50 == 0) { //solrWrapper.getServer().commit(); // Thread.sleep(1000); // } System.out.println(i + ". indexed with docno: " + id); } } /* public double findSimilarity1(String q, String p) throws Exception { double similarity = 0.0; HashMap<String, String> hshMap = new HashMap<String, String>(); hshMap.put("q", "id:10085337"); //qt=tvrh&tv.tf=true&tv.fl=contents&tv.all=true hshMap.put("qt", "tvrh"); hshMap.put("tv.tf", "true"); hshMap.put("tv.fl", "paragraph,text"); hshMap.put("tv.all", "true"); hshMap.put("fl", "paragraph,text"); SolrParams solrParams = new MapSolrParams(hshMap); QueryResponse queryResponse = solrWrapper.getServer().query(solrParams); TermsResponse termsResponse = queryResponse.getTermsResponse(); List<Term> terms = termsResponse.getTerms("text"); for (int i = 0; i < terms.size(); i++) { System.out.println(terms.get(i).getTerm() + "\t" + terms.get(i).getFrequency()); } return similarity; } public double findSimilarity(String q, String p) throws Exception { double similarity = 0.0; HashMap<String, String> hshMap = new HashMap<String, String>(); hshMap.put("q", "id:10085337"); //qt=tvrh&tv.tf=true&tv.fl=contents&tv.all=true hshMap.put("qt", "tvrh"); hshMap.put("tv.tf", "true"); hshMap.put("tv.fl", "paragraph,text"); hshMap.put("tv.all", "true"); hshMap.put("fl", "paragraph,text"); SolrParams solrParams = new MapSolrParams(hshMap); QueryResponse queryResponse = solrWrapper.getServer().query(solrParams); TermsResponse termsResponse = queryResponse.getTermsResponse(); List<Term> terms = termsResponse.getTerms("text"); for (int i = 0; i < terms.size(); i++) { System.out.println(terms.get(i).getTerm() + "\t" + terms.get(i).getFrequency()); } return similarity; } */ }
package unalcol.evolution.ga; import unalcol.search.population.TotalSelectionReplacement; import unalcol.search.population.variation.ArityTwo; import unalcol.search.selection.Selection; import unalcol.search.space.ArityOne; /** * <p>Title: SteadyStateGA</p> * <p> * <p>Description: Steady State Genetic Algorithm (GA with Steady State replacement strategy </p> * <p> * <p>Copyright: Copyright (c) 2010</p> * * @author Jonatan Gomez * @version 1.0 */ public class SteadyStateStep<T> extends GAStep<T> { public SteadyStateStep(int n, Selection<T> parent_selection, ArityOne<T> mutation, ArityTwo<T> xover, double probability) { super(n, parent_selection, mutation, xover, probability, new TotalSelectionReplacement<T>()); } }
package com.duanxr.yith.define.versionControl; /** * @author Duanran 2019/2/27 0027 */ public class VersionControl { private static final int firstBadVersion = 12; public boolean isBadVersion(int version) { return version >= firstBadVersion; } }
import biuoop.DrawSurface; import java.awt.Color; /** * Created by user on 01/06/2017. */ public class LivesIndicator implements Sprite { private Counter lifes; /** * construct a LivesIndicator with lifes. * * @param lifes the lives counter. */ public LivesIndicator(Counter lifes) { this.lifes = lifes; } /** * draw the Sprite. * * @param surface the surface which we draw on. */ public void drawOn(DrawSurface surface) { surface.setColor(Color.lightGray); surface.fillRectangle(0, 0, 200, 20); surface.setColor(Color.black); surface.drawText(0 + 50, 0 + 13, "Lives:" + Integer.toString(this.lifes.getValue()), 15); } /** *@param dt dt. */ public void timePassed(double dt) { } /** * @param g a Game. */ public void addToGame(GameLevel g) { g.addSprite(this); } /** * @param lives updating lifes with a new value. */ public void setLifes(Counter lives) { this.lifes = lifes; } }
package Test; /** * Test * * @author jh * @date 2018/9/9 18:51 * description: */ public class Person { private String name="hello"; int age=0; } class Child extends Person{ public static void main(String[] args) { Person child = new Child (); //child.age } }
package com.example.android_essential_07_hw3; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.IBinder; import java.util.concurrent.TimeUnit; public class MyService extends Service { NotificationManager nm; @Override public void onCreate() { super.onCreate(); nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); } @Override public int onStartCommand(Intent intent, int flags, int startId) { try { TimeUnit.SECONDS.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } sendNotif(); return super.onStartCommand(intent, flags, startId); } void sendNotif() { // 1-я часть Notification.Builder builder = new Notification.Builder(this); // 3-я часть Intent intent = new Intent(this, MainActivity.class); intent.putExtra(MainActivity.FILE_NAME, "somefile"); PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0); // 2-я часть builder.setContentIntent(pIntent) .setSmallIcon(R.drawable.ic_launcher_background) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setContentTitle("Title") .setContentText("Text") .setTicker("Notification"); Notification notif = builder.build(); // ставим флаг, чтобы уведомление пропало после нажатия notif.flags |= Notification.FLAG_AUTO_CANCEL; // отправляем nm.notify(1, notif); } public IBinder onBind(Intent arg0) { return null; } }
package ch.rasc.eds.starter.service; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import ch.ralscha.extdirectspring.bean.ExtDirectResponseBuilder; @Component @Lazy public class FormPostExceptionHandler implements HandlerExceptionResolver { @Override public ModelAndView resolveException(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final Exception ex) { LoggerFactory.getLogger(FormPostExceptionHandler.class).error("error", ex); ExtDirectResponseBuilder.create(request, response).setException(ex).buildAndWrite(); return null; } }
package services; import common.utils.UserUtils; import model.domain.Persoana; import model.domain.User; import model.domain.UserRole; import model.forms.PersoanaFormModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import services.user.UserService; import java.sql.Timestamp; import java.util.Date; import java.util.List; import java.util.stream.Collectors; @Service public class ProfileServiceImpl implements ProfileService { private static final Logger LOGGER = LoggerFactory.getLogger(ProfileServiceImpl.class); @Autowired private UserService userService; @Autowired private ResurseUmaneService resurseUmaneService; @Autowired private PasswordEncoder passwordEncoder; @Override public Persoana getRaindropUser(String username) { return resurseUmaneService.findByUsername(username); } @Override public Persoana getLoggedInRaindropUser() { return getRaindropUser(UserUtils.getLoggedInUsername()); } @Override public String changePassword(String password) { User userCurent = getLoggedInRaindropUser().getIdUser(); userCurent.setPassword(passwordEncoder.encode(password)); userCurent.setLastPassChange(new Timestamp(new Date().getTime())); userService.save(userCurent); LOGGER.info(String.format("Utilizatorul %s si-a schimbat parola", userCurent.getUsername())); return "Parola a fost schimbata cu success"; } @Override public List<Persoana> getEnabledUsers() { return resurseUmaneService.findAllPersoane() .stream() .filter(persoana -> persoana.getIdUser().getEnabled() == 1 && !persoana.getIdUser().getUsername().equals(UserUtils.getLoggedInUsername())) .collect(Collectors.toList()); } @Override public List<Persoana> getAllUsers() { return resurseUmaneService.findAllPersoane(); } @Override public Persoana activateUser(long idUser) { return resurseUmaneService.activateUser(idUser); } @Override public Persoana deactivateUser(long idUser) { return resurseUmaneService.deactivateUser(idUser); } @Override public List<UserRole> getRolesForUser(long idUser) { return userService.getRolesForUser(idUser); } @Override public Persoana addPersoana(PersoanaFormModel persoanaFormModel) { return null; } }
package com.ssgl.controller; import com.alibaba.fastjson.JSONArray; import com.ssgl.bean.*; import com.ssgl.service.FloorService; import com.ssgl.util.FileUtils; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /* * 功能: * User: jiajunkang * email:jiajunkang@outlook.com * Date: 2018/1/17 0017 * Time: 21:01 */ @Controller @RequestMapping("/floor/") public class FloorController { @Autowired public FloorService floorService; @RequiresPermissions("toFloorUI") @RequestMapping(value = "toFloorUI") public String toFloorUI(){ return "floor"; } @ResponseBody @RequestMapping(value = "selectAllFloors",produces = "text/json;charset=utf-8") public String selectAllFloors(){ try { return floorService.selectAllFloors(); } catch (Exception e) { e.printStackTrace(); return null; } } @ResponseBody @RequiresPermissions("deleteFloors") @RequestMapping(value = "deleteFloors") public Result deleteFloors(String ids){ try { return floorService.deleteFloors(ids); } catch (Exception e) { e.printStackTrace(); return new Result("error","删除失败"); } } @ResponseBody @RequestMapping(value = "selectFloorDormitories",produces = "text/json;charset=utf-8") public String selectFloorDormitories(Integer page, Integer rows,HttpServletRequest request){ try { Page<CustomFloor> p = floorService.selectFloorDormitories(page,rows,request); Map<String, Object> map = new LinkedHashMap<>(); if(null!=p){ map.put("total", p.getTotalRecord()); map.put("rows", p.getList()); return JSONArray.toJSONString(map); } return null; } catch (Exception e) { e.printStackTrace(); return null; } } @RequiresPermissions("addFloor") @ResponseBody @RequestMapping(value = "addFloor") public Result addFloor(Floor floor,Integer building_no){ try { return floorService.addFloor(floor,building_no); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("出错了"); } } @ResponseBody @RequestMapping(value = "getLayers") public String getLayers(HttpServletRequest request,Integer buildingNo){ try { return floorService.selectLayerByBuidingNo(buildingNo); }catch (Exception e){ e.printStackTrace(); throw new RuntimeException("出錯了"); } } @RequestMapping(value = "exportFloor") public void exportFloor(HttpServletRequest request,HttpServletResponse response) { try { List<Floor> floors = floorService.exportFloor(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFCellStyle cellStyle = workbook.createCellStyle(); HSSFSheet sheet = workbook.createSheet("楼层信息表"); HSSFRow row = sheet.createRow(0); HSSFCell cell = row.createCell(0); cell.setCellValue("楼层信息"); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); cell.setCellStyle(cellStyle); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4)); HSSFRow r = sheet.createRow(1); r.createCell(0).setCellValue("主键"); r.createCell(1).setCellValue("楼层的房间数"); r.createCell(2).setCellValue("第几层"); r.createCell(3).setCellValue("楼层的学生数"); r.createCell(4).setCellValue("剩余房间数"); for (Floor floor : floors) { HSSFRow h = sheet.createRow(sheet.getLastRowNum() + 1); h.createCell(0).setCellValue(floor.getId()); h.createCell(1).setCellValue(floor.getRoomNumber()); h.createCell(2).setCellValue(floor.getLayer()); h.createCell(3).setCellValue(floor.getStudents()); h.createCell(4).setCellValue(floor.getSpaces()); } ServletOutputStream out = response.getOutputStream(); response.setContentType("application/msexcel"); String agent = request.getHeader("User-Agent"); String filename = FileUtils.encodeDownloadFilename("楼层信息表.xls", agent); response.setHeader("content-disposition", "attachment;filename=" + filename); workbook.write(out); out.flush(); } catch (Exception e) { throw new RuntimeException(e); } } }
package org.search.flight.model; import java.math.BigDecimal; public class Flight { private Airport from; private Airport to; private String airlineCodeFlight; private Airline airline; private BigDecimal basePrice; public Flight(Airport from, Airport to, String airlineCodeFlight, Airline airline, BigDecimal basePrice) { this.from = from; this.to = to; this.airline = airline; this.airlineCodeFlight = airlineCodeFlight; this.basePrice = basePrice; } /** * @return the from */ public Airport getFrom() { return from; } /** * @param from * the from to set */ public void setFrom(Airport from) { this.from = from; } /** * @return the to */ public Airport getTo() { return to; } /** * @param to * the to to set */ public void setTo(Airport to) { this.to = to; } public String getairlineCodeFlight() { return airlineCodeFlight; } public void setairlineCodeFlight(String airlineCodeFlight) { this.airlineCodeFlight = airlineCodeFlight; } public BigDecimal getBasePrice() { return basePrice; } public void setBasePrice(BigDecimal basePrice) { this.basePrice = basePrice; } public Airline getAirline() { return airline; } public void setAirline(Airline airline) { this.airline = airline; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((airline == null) ? 0 : airline.hashCode()); result = prime * result + ((airlineCodeFlight == null) ? 0 : airlineCodeFlight.hashCode()); result = prime * result + ((basePrice == null) ? 0 : basePrice.hashCode()); result = prime * result + ((from == null) ? 0 : from.hashCode()); result = prime * result + ((to == null) ? 0 : to.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Flight other = (Flight) obj; if (airline == null) { if (other.airline != null) return false; } else if (!airline.equals(other.airline)) return false; if (airlineCodeFlight == null) { if (other.airlineCodeFlight != null) return false; } else if (!airlineCodeFlight.equals(other.airlineCodeFlight)) return false; if (basePrice == null) { if (other.basePrice != null) return false; } else if (!basePrice.equals(other.basePrice)) return false; if (from == null) { if (other.from != null) return false; } else if (!from.equals(other.from)) return false; if (to == null) { if (other.to != null) return false; } else if (!to.equals(other.to)) return false; return true; } @Override public String toString() { return "Flight [from=" + from + ", to=" + to + ", airlineCodeFlight=" + airlineCodeFlight + ", airline=" + airline + ", basePrice=" + basePrice + "]"; } }
package pl.com.garage.model; import org.springframework.stereotype.Component; @Component public class Client { private int id; private String name; private String carModel; public Client() { } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setCarModel(String carModel) { this.carModel = carModel; } public int getId() { return id; } public String getName() { return name; } public String getCarModel() { return carModel; } public Client(int id,String name, String carModel) { this.id = id; this.name = name; this.carModel = carModel; } @Override public String toString() { return "Client{" + "name='" + name + '\'' + ", carModel='" + carModel + '\'' + '}'; } }
package com.example.shopping.dto; import com.example.shopping.entity.User; import com.example.shopping.validation.PasswordValid; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; @Data @Builder @NoArgsConstructor @AllArgsConstructor @JsonInclude(JsonInclude.Include.NON_NULL) @PasswordValid public class UserDto { private Long id; @NotBlank private String firstName; @NotBlank private String lastName; @NotBlank @Email private String email; private String password; private String confirmPassword; private Integer revisionNumber; }
import java.util.Scanner; public class run{ public static void main(String[] args){ slotmachine test = new slotmachine(); test.setregisters(); boolean loop = true; float wallet = 0; float bank = 0; //System.out.println(test.getregister1()); //System.out.println(test.getregister2()); //System.out.println(test.getregister3()); int a = 0; int b = 0; int c = 0; System.out.println("Initialized"); Scanner user_input = new Scanner(System.in); //String tester = user_input.next(); //System.out.println(tester + " was entered."); while (loop == true){ System.out.println("**************"); System.out.println("Wallet: " + wallet); System.out.println("**************"); System.out.println("1. Insert Coin"); int choice = Integer.parseInt(user_input.next()); if (choice == 1){ wallet -= 0.25; bank += 0.25; test.setregisters(); a = test.getregister1(); b = test.getregister2(); c = test.getregister3(); } else {loop = false;} if (a == b && b == c){ System.out.println(a + " | " + b + " | " + c); System.out.println("Win!"); wallet += bank; bank = 0; } else { System.out.println(a + " | " + b + " | " + c); System.out.println("Lose"); } } } }
package yuste.zombis.armas; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public abstract class Arma { public static int COSTO; protected int daņo; protected float intervaloDisparos; protected int municionInicial; protected int municionActual; protected long ultimoDisparo; /*UTILIDADES PARA LA CARGA*/ private float ticksCarga; private float ticksObjetivo = 75; public Arma(int daņo, float intervaloDisparos, int municionInicial) { this.daņo = daņo; this.intervaloDisparos = intervaloDisparos; this.municionInicial = municionInicial; municionActual = municionInicial; } public void actualizar() { ticksCarga++; if(!puedeDisparar()) { if(ticksCarga == 0) { //System.out.println("Comienza la Carga"); } recargar(); } } private boolean puedeDisparar() { if(municionActual > 0) { return true; } return false; } public boolean disparar() { if(puedeDisparar()) { long ahora = System.currentTimeMillis(); if(ahora - ultimoDisparo > intervaloDisparos * 1000) { ultimoDisparo = ahora; //Generar Bala y Disparar municionActual --; if(municionActual == 0) { ticksCarga = 0; } return true; } } return false; } public void recargar() { if(puedeRecargar()) { ticksCarga = 0; municionActual = municionInicial; } } /*GETTERS*/ public int getDaņo() { return daņo; } public float getIntervaloDisparos() { return intervaloDisparos; } public int getMunicionInicial() { return municionInicial; } public int getMunicionActual() { return municionActual; } public long getUltimoDisparo() { return ultimoDisparo; } public float getTicksCarga() { return ticksCarga; } public float getTicksObjetivo() { return ticksObjetivo; } public boolean puedeRecargar() { return ticksCarga >= ticksObjetivo; } public abstract void dibujarIcono(SpriteBatch batch); }
package com.jim.multipos.ui.customer_debt; import com.jim.multipos.core.BaseView; /** * Created by Sirojiddin on 29.12.2017. */ public interface CustomerDebtActivityView extends BaseView{ }
package quizzlr.backend.UnitTests; import org.junit.*; import quizzlr.backend.*; public class AchievementTypeTest { @Test public void testAchievementTypes() { /* * TODO: presumably a big test block like * AchievementType a = AchievementType.getAchievementTypeFromID(123); * Assert.assertEquals(a, new SomeAchievementType()); */ } }
package net.sssanma.mc.data.user; public final class UserBanException extends UserException { /** * */ private static final long serialVersionUID = 1L; public UserBanException(String paramString) { super(paramString); } public UserBanException(Throwable arg0) { super(arg0); } public UserBanException(String arg0, Throwable arg1) { super(arg0, arg1); } }
package home.inna.work; import home.inna.study.Mobile; import home.inna.work.test.Test; /** * User: Alexandr * Date: 25.10.2014 */ public class Inna { // public static void main(String[] args) { // Inna inna = new Inna(); // home.inna.study.Inna inna2 = new home.inna.study.Inna(); // Mobile mob = new Mobile(); // book.Mobile mobile = new book.Mobile(); // // Andrey andrey = new Andrey(); // Test test = new Test(); // } }
package cn.codef1.apidemo.demo.app; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import cn.codef1.apidemo.demo.R; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by CoderF1 on 2017/10/16. */ public class NotificationMessageStyle extends AppCompatActivity { @BindView(R.id.style) Button style; @BindView(R.id.addHistoricMessage) Button addHistoricMessage; private NotificationManager manager; private Notification.MessagingStyle messagingStyle; private Notification.MessagingStyle.Message message = new Notification.MessagingStyle.Message("messages[0]", System.currentTimeMillis(), "s0"); private Notification.MessagingStyle.Message message1 = new Notification.MessagingStyle.Message("messages[1]", System.currentTimeMillis() + 10000, "s1"); private Notification.MessagingStyle.Message message2 = new Notification.MessagingStyle.Message("messages[2]", System.currentTimeMillis() + 20000, "s2"); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification_style); ButterKnife.bind(this); manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); messagingStyle = new Notification.MessagingStyle("style1") .addMessage(message) .addMessage(message1) .addMessage(message2); } @OnClick({R.id.style, R.id.addHistoricMessage}) public void onViewClicked(View view) { NotificationHelper notificationHelper = new NotificationHelper(this); Notification.Builder builder = notificationHelper.getNotification1(this,"Test NotificationMessageStyle", "api MessagingStyle"); switch (view.getId()) { case R.id.style: builder.setContentTitle("2 new messages wtih " + "history 1"); builder.setContentText("message style"); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),android.R.drawable.stat_sys_speakerphone)); builder.setStyle(messagingStyle) .build(); manager.notify(5000, builder.build()); break; case R.id.addHistoricMessage: builder.setContentTitle("2 new messages wtih " + "history 1"); builder.setContentText("message style"); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)); builder.setStyle(messagingStyle.addHistoricMessage(new Notification.MessagingStyle.Message("messages[3]", System.currentTimeMillis() + 20000, "s3"))) .build(); manager.notify(5001, builder.build()); break; } } }
import java.io.*; import java.util.*; public class names1{ main(){ int i=0; FileWriter fw= new FileWriter("file.txt"); } }
package com.hazelcast.map; import com.hazelcast.map.record.Record; import com.hazelcast.nio.serialization.Data; import com.hazelcast.nio.serialization.SerializationService; import com.hazelcast.query.PagingPredicate; import com.hazelcast.query.Predicate; import com.hazelcast.query.impl.QueryEntry; import com.hazelcast.query.impl.QueryResultEntryImpl; import com.hazelcast.util.SortingUtil; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Helper methods for querying map partitions. */ public class MapContextQuerySupport { private MapServiceContext mapServiceContext; public MapContextQuerySupport(MapServiceContext mapServiceContext) { this.mapServiceContext = mapServiceContext; } public QueryResult queryOnPartition(String mapName, Predicate predicate, int partitionId) { final QueryResult result = new QueryResult(); final PartitionContainer container = mapServiceContext.getPartitionContainer(partitionId); final RecordStore recordStore = container.getRecordStore(mapName); final Map<Data, Record> records = recordStore.getReadonlyRecordMapByWaitingMapStoreLoad(); final SerializationService serializationService = mapServiceContext.getNodeEngine().getSerializationService(); final PagingPredicate pagingPredicate = predicate instanceof PagingPredicate ? (PagingPredicate) predicate : null; List<QueryEntry> list = new LinkedList<QueryEntry>(); for (Record record : records.values()) { Data key = record.getKey(); Object value = record.getValue(); if (value == null) { continue; } QueryEntry queryEntry = new QueryEntry(serializationService, key, key, value); if (predicate.apply(queryEntry)) { if (pagingPredicate != null) { Map.Entry anchor = pagingPredicate.getAnchor(); if (anchor != null && SortingUtil.compare(pagingPredicate.getComparator(), pagingPredicate.getIterationType(), anchor, queryEntry) >= 0) { continue; } } list.add(queryEntry); } } list = getPage(list, pagingPredicate); for (QueryEntry entry : list) { result.add(new QueryResultEntryImpl(entry.getKeyData(), entry.getKeyData(), entry.getValueData())); } return result; } private List getPage(List<QueryEntry> list, PagingPredicate pagingPredicate) { if (pagingPredicate == null) { return list; } final Comparator<Map.Entry> wrapperComparator = SortingUtil.newComparator(pagingPredicate); Collections.sort(list, wrapperComparator); if (list.size() > pagingPredicate.getPageSize()) { list = list.subList(0, pagingPredicate.getPageSize()); } return list; } }
package cryptography; import java.math.BigInteger; public class STS_Agent { public DSA_Agent dsa_agent; public DH_Agent dh_agent; /* Signature variables*/ private BigInteger prv_key; public Point pub_key; /* Shared key establishment variables*/ private BigInteger dh_prv_key; // a public Point dh_pub_key; // aP public Point frgn_pub_key;// bP private Point scrt_key; // abP public STS_Agent() { // TODO Auto-generated constructor stub } public STS_Agent(String curveFileName) { // TODO Auto-generated constructor stub //Initialise equation //Generate DSA Key Pair dsa_agent = new DSA_Agent(curveFileName); //Generate DH Key establishment parameters dh_agent = new DH_Agent(curveFileName, 45); //AES encryption parameters init } }
package polydungeons.entity; import net.dblsaiko.qcommon.croco.Mat4; import net.dblsaiko.qcommon.croco.Vec3; import net.fabricmc.api.EnvType; import net.fabricmc.api.Environment; import net.minecraft.block.BlockState; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.ai.control.LookControl; import net.minecraft.entity.ai.goal.FollowTargetGoal; import net.minecraft.entity.ai.goal.Goal; import net.minecraft.entity.ai.goal.LookAtEntityGoal; import net.minecraft.entity.ai.goal.RevengeGoal; import net.minecraft.entity.ai.goal.WanderAroundFarGoal; import net.minecraft.entity.attribute.DefaultAttributeContainer; import net.minecraft.entity.attribute.EntityAttributes; import net.minecraft.entity.damage.DamageSource; import net.minecraft.entity.data.DataTracker; import net.minecraft.entity.data.TrackedData; import net.minecraft.entity.data.TrackedDataHandlerRegistry; import net.minecraft.entity.mob.HostileEntity; import net.minecraft.entity.mob.MobEntity; import net.minecraft.entity.mob.MobEntityWithAi; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvent; import net.minecraft.sound.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraft.world.World; public class SlugSlimeEntity extends MobEntityWithAi implements IMobEntity { private static final TrackedData<Float> LEFT_EYE_YAW = DataTracker.registerData(SlugSlimeEntity.class, TrackedDataHandlerRegistry.FLOAT); private float prevLeftEyeYaw; private static final TrackedData<Float> LEFT_EYE_PITCH = DataTracker.registerData(SlugSlimeEntity.class, TrackedDataHandlerRegistry.FLOAT); private float prevLeftEyePitch; private static final TrackedData<Float> RIGHT_EYE_YAW = DataTracker.registerData(SlugSlimeEntity.class, TrackedDataHandlerRegistry.FLOAT); private float prevRightEyeYaw; private static final TrackedData<Float> RIGHT_EYE_PITCH = DataTracker.registerData(SlugSlimeEntity.class, TrackedDataHandlerRegistry.FLOAT); private float prevRightEyePitch; private static final TrackedData<Float> SNOUT_YAW = DataTracker.registerData(SlugSlimeEntity.class, TrackedDataHandlerRegistry.FLOAT); private float prevSnoutYaw; private static final TrackedData<Float> SNOUT_PITCH = DataTracker.registerData(SlugSlimeEntity.class, TrackedDataHandlerRegistry.FLOAT); private float prevSnoutPitch; private LookControl snoutLookControl; private LookControl headLookControl; protected SlugSlimeEntity(EntityType<? extends MobEntityWithAi> entityType, World world) { super(entityType, world); lookControl = new SlugSlimeLookControl(this); snoutLookControl = new SnoutLookControl(this); headLookControl = new HeadLookControl(this); } public SlugSlimeEntity(World world) { this(PolyDungeonsEntities.SLUG_SLIME, world); } @Override protected void initDataTracker() { super.initDataTracker(); dataTracker.startTracking(LEFT_EYE_YAW, 0f); dataTracker.startTracking(LEFT_EYE_PITCH, 0f); dataTracker.startTracking(RIGHT_EYE_YAW, 0f); dataTracker.startTracking(RIGHT_EYE_PITCH, 0f); dataTracker.startTracking(SNOUT_YAW, 0f); dataTracker.startTracking(SNOUT_PITCH, 0f); } @Override protected void initGoals() { super.initGoals(); goalSelector.add(4, new SlugSlimeAttackGoal(this)); goalSelector.add(5, new WanderAroundFarGoal(this, 1)); goalSelector.add(6, new LookAtEntityGoal(this, PlayerEntity.class, 8)); targetSelector.add(1, new RevengeGoal(this)); targetSelector.add(2, new FollowTargetGoal<>(this, PlayerEntity.class, true)); } public static DefaultAttributeContainer.Builder createSlugSlimeAttributes() { return HostileEntity.createHostileAttributes() .add(EntityAttributes.GENERIC_ATTACK_DAMAGE, 2) .add(EntityAttributes.GENERIC_MOVEMENT_SPEED, 0.23); } @Override public void baseTick() { prevLeftEyeYaw = getLeftEyeYaw(); prevLeftEyePitch = getLeftEyePitch(); prevRightEyeYaw = getRightEyeYaw(); prevRightEyePitch = getRightEyePitch(); prevSnoutYaw = getSnoutYaw(); prevSnoutPitch = getSnoutPitch(); super.baseTick(); } @Override public void polydungeons_onControlTick() { world.getProfiler().push("slugSlimeSnoutLook"); snoutLookControl.tick(); world.getProfiler().swap("slugSlimeHead"); headLookControl.tick(); world.getProfiler().pop(); } public void shootAt(LivingEntity target) { Mat4 transform = Mat4.IDENTITY .translate(0, 22/16f, 0) .rotate(0, 1, 0, headYaw) .rotate(1, 0, 0, pitch) .translate(0, -22/16f, 0) .translate(0, 31/16f, 3/16f) .rotate(0, 1, 0, getSnoutYaw() - headYaw) .rotate(1, 0, 0, getSnoutPitch() - pitch) .translate(0, -7/16f, 0); Vec3d snoutEnd = getPos().add(transform.mul(Vec3.ORIGIN).toVec3d()); Vec3d targetVelocity = target.getVelocity(); double dx = target.getX() + targetVelocity.x - snoutEnd.x; double dy = target.getY() - snoutEnd.y; double dz = target.getZ() + targetVelocity.z - snoutEnd.z; SlingshotProjectileEntity projectile = new SlingshotProjectileEntity(this, world); projectile.updatePosition(snoutEnd.x, snoutEnd.y, snoutEnd.z); projectile.setVelocity(dx, dy + MathHelper.sqrt(dx * dx + dz * dz), dz, 0.75f, 8); world.spawnEntity(projectile); if (!isSilent()) { world.playSound(null, getX(), getY(), getZ(), SoundEvents.ENTITY_ARROW_SHOOT, SoundCategory.HOSTILE, 1, 0.8f + random.nextFloat() * 0.4f); } } @Override protected SoundEvent getHurtSound(DamageSource source) { return SoundEvents.ENTITY_SLIME_HURT; } @Override protected SoundEvent getDeathSound() { return SoundEvents.ENTITY_SLIME_DEATH; } @Override protected void playStepSound(BlockPos pos, BlockState state) { if (!state.getMaterial().isLiquid()) { // TODO: slither } } public float getLeftEyeYaw() { return dataTracker.get(LEFT_EYE_YAW); } public void setLeftEyeYaw(float leftEyeYaw) { dataTracker.set(LEFT_EYE_YAW, leftEyeYaw); } public float getLeftEyePitch() { return dataTracker.get(LEFT_EYE_PITCH); } public void setLeftEyePitch(float leftEyePitch) { dataTracker.set(LEFT_EYE_PITCH, leftEyePitch); } public float getRightEyeYaw() { return dataTracker.get(RIGHT_EYE_YAW); } public void setRightEyeYaw(float rightEyeYaw) { dataTracker.set(RIGHT_EYE_YAW, rightEyeYaw); } public float getRightEyePitch() { return dataTracker.get(RIGHT_EYE_PITCH); } public void setRightEyePitch(float rightEyePitch) { dataTracker.set(RIGHT_EYE_PITCH, rightEyePitch); } public float getSnoutYaw() { return dataTracker.get(SNOUT_YAW); } public void setSnoutYaw(float snoutYaw) { dataTracker.set(SNOUT_YAW, snoutYaw); } public float getSnoutPitch() { return dataTracker.get(SNOUT_PITCH); } public void setSnoutPitch(float snoutPitch) { dataTracker.set(SNOUT_PITCH, snoutPitch); } @Environment(EnvType.CLIENT) public float getLeftEyeYaw(float tickDelta) { return MathHelper.lerpAngleDegrees(tickDelta, prevLeftEyeYaw, getLeftEyeYaw()); } @Environment(EnvType.CLIENT) public float getLeftEyePitch(float tickDelta) { return MathHelper.lerpAngleDegrees(tickDelta, prevLeftEyePitch, getLeftEyePitch()); } @Environment(EnvType.CLIENT) public float getRightEyeYaw(float tickDelta) { return MathHelper.lerpAngleDegrees(tickDelta, prevRightEyeYaw, getRightEyeYaw()); } @Environment(EnvType.CLIENT) public float getRightEyePitch(float tickDelta) { return MathHelper.lerpAngleDegrees(tickDelta, prevRightEyePitch, getRightEyePitch()); } @Environment(EnvType.CLIENT) public float getSnoutYaw(float tickDelta) { return MathHelper.lerpAngleDegrees(tickDelta, prevSnoutYaw, getSnoutYaw()); } @Environment(EnvType.CLIENT) public float getSnoutPitch(float tickDelta) { return MathHelper.lerpAngleDegrees(tickDelta, prevSnoutPitch, getSnoutPitch()); } private static class SlugSlimeAttackGoal extends Goal { private final SlugSlimeEntity entity; private LivingEntity target; private int updateCountdownTicks = -1; private final double mobSpeed = 1; private int seenTargetTicks; private final int minIntervalTicks = 15; private final int maxIntervalTicks = 30; private final float maxShootRange = 10; private final float maxShootRangeSq = maxShootRange * maxShootRange; public SlugSlimeAttackGoal(SlugSlimeEntity entity) { this.entity = entity; } @Override public boolean canStart() { LivingEntity target = entity.getTarget(); if (target == null || !target.isAlive()) { return false; } this.target = target; return true; } @Override public boolean shouldContinue() { return canStart() || !entity.getNavigation().isIdle(); } @Override public void stop() { target = null; seenTargetTicks = 0; updateCountdownTicks = -1; } @Override public void tick() { double distanceSqToTarget = entity.squaredDistanceTo(target.getX(), target.getY(), target.getZ()); boolean canSeeTarget = entity.getVisibilityCache().canSee(target); if (canSeeTarget) { seenTargetTicks++; } else { seenTargetTicks = 0; } if (distanceSqToTarget <= maxShootRangeSq && seenTargetTicks >= 5) { entity.getNavigation().stop(); } else { entity.getNavigation().startMovingTo(target, mobSpeed); } entity.getLookControl().lookAt(target, 10, 10); entity.snoutLookControl.lookAt(target, 30, 30); if (getAngleToTarget() > 45) { entity.headLookControl.lookAt(target, 20, 20); } updateCountdownTicks--; if (updateCountdownTicks == 0) { if (!canSeeTarget) { return; } float distanceNormalized = MathHelper.sqrt(distanceSqToTarget) / maxShootRange; entity.shootAt(target); updateCountdownTicks = MathHelper.floor(distanceNormalized * (maxIntervalTicks - minIntervalTicks) + minIntervalTicks); } else if (updateCountdownTicks < 0) { float distanceNormalized = MathHelper.sqrt(distanceSqToTarget) / maxShootRange; updateCountdownTicks = MathHelper.floor(distanceNormalized * (maxIntervalTicks - minIntervalTicks) + minIntervalTicks); } } private double getAngleToTarget() { Vec3d targetRelPos = target.getCameraPosVec(1).subtract(entity.getCameraPosVec(1)); double cosine = entity.getRotationVec(1).dotProduct(targetRelPos) / targetRelPos.length(); return Math.toDegrees(Math.acos(MathHelper.clamp(cosine, -1, 1))); } } private static class SlugSlimeLookControl extends LookControl { private SlugSlimeEntity entity; private boolean movingLeftEye; private boolean movingRightEye; public SlugSlimeLookControl(SlugSlimeEntity entity) { super(entity); this.entity = entity; } @Override public void tick() { if (shouldStayHorizontal()) { entity.pitch = 0; } float targetYaw; float targetPitch; if (active) { active = false; targetYaw = getTargetYaw(); targetPitch = getTargetPitch(); } else { targetYaw = entity.bodyYaw; targetPitch = 0; } if (entity.getLeftEyeYaw() != targetYaw || entity.getLeftEyePitch() != targetPitch) { if (!movingLeftEye) { movingLeftEye = entity.random.nextInt(10) == 0; } if (movingLeftEye) { entity.setLeftEyeYaw(changeAngle(entity.getLeftEyeYaw(), targetYaw, yawSpeed)); entity.setLeftEyePitch(changeAngle(entity.getLeftEyePitch(), targetPitch, pitchSpeed)); } } else { movingLeftEye = false; } if (entity.getRightEyeYaw() != targetYaw || entity.getRightEyePitch() != targetPitch) { if (!movingRightEye) { movingRightEye = entity.random.nextInt(10) == 0; } if (movingRightEye) { entity.setRightEyeYaw(changeAngle(entity.getRightEyeYaw(), targetYaw, yawSpeed)); entity.setRightEyePitch(changeAngle(entity.getRightEyePitch(), targetPitch, pitchSpeed)); } } else { movingRightEye = false; } } } private static class SnoutLookControl extends LookControl { private SlugSlimeEntity entity; public SnoutLookControl(SlugSlimeEntity entity) { super(entity); this.entity = entity; } @Override public void tick() { if (shouldStayHorizontal()) { entity.setSnoutPitch(0); } if (active) { active = false; entity.setSnoutYaw(changeAngle(entity.getSnoutYaw(), getTargetYaw(), yawSpeed)); entity.setSnoutPitch(changeAngle(entity.getSnoutPitch(), getTargetPitch(), pitchSpeed)); } else { final double TAU = 2 * Math.PI; final float YAW_RATE = 0.03f / (float) Math.PI; float targetYaw = entity.bodyYaw + 30 * (float)Math.sin(entity.age * YAW_RATE * TAU); final float PITCH_RATE = 0.03f; float targetPitch = entity.pitch + 45 - 15 * (float)Math.sin(entity.age * PITCH_RATE * TAU - 0.5 * Math.sin(entity.age * PITCH_RATE * TAU - 0.5 * Math.sin(entity.age * PITCH_RATE * TAU))); entity.setSnoutYaw(changeAngle(entity.getSnoutYaw(), targetYaw, 10)); entity.setSnoutPitch(changeAngle(entity.getSnoutPitch(), targetPitch, 10)); } } @Override protected boolean shouldStayHorizontal() { return false; } } private static class HeadLookControl extends LookControl { public HeadLookControl(MobEntity entity) { super(entity); } @Override protected boolean shouldStayHorizontal() { return !active; } } }
package ru.android.messenger.view.adapters; import android.content.Context; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import ru.android.messenger.R; import ru.android.messenger.view.fragments.FriendsFragment; import ru.android.messenger.view.fragments.IncomingRequestsFragment; import ru.android.messenger.view.fragments.OutgoingRequestsFragment; public class FriendsFragmentPagerAdapter extends FragmentPagerAdapter { private static final int COUNT_FRAGMENTS = 3; private Context context; public FriendsFragmentPagerAdapter(FragmentManager fragmentManager, Context context) { super(fragmentManager); this.context = context; } @Override public Fragment getItem(int position) { switch (position) { case 0: return new FriendsFragment(); case 1: return new IncomingRequestsFragment(); case 2: return new OutgoingRequestsFragment(); default: return null; } } @Override public int getCount() { return COUNT_FRAGMENTS; } @Nullable @Override public CharSequence getPageTitle(int position) { switch (position) { case 0: return context.getString(R.string.friend_list_activity_friends_fragment_title); case 1: return context.getString( R.string.friend_list_activity_incoming_requests_fragment_title); case 2: return context.getString( R.string.friend_list_activity_outgoing_requests_fragment_title); default: return null; } } }
/* * 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.dom.builder.shared; import org.gwtproject.safehtml.shared.SafeUri; import org.gwtproject.safehtml.shared.annotations.IsSafeUri; /** Builds an anchor element. */ public interface AnchorBuilder extends ElementBuilderBase<AnchorBuilder> { /** * A single character access key to give access to the form control. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/interact/forms.html#adef-accesskey">W3C * HTML Specification</a> */ AnchorBuilder accessKey(String accessKey); /** * The absolute URI of the linked resource. * * @see <a href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/links.html#adef-href">W3C * HTML Specification</a> */ AnchorBuilder href(SafeUri href); /** * The absolute URI of the linked resource. * * @see <a href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/links.html#adef-href">W3C * HTML Specification</a> */ AnchorBuilder href(@IsSafeUri String href); /** * Language code of the linked resource. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/links.html#adef-hreflang">W3C * HTML Specification</a> */ AnchorBuilder hreflang(String hreflang); /** * Anchor name. * * @see <a href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/links.html#adef-name-A">W3C * HTML Specification</a> */ AnchorBuilder name(String name); /** * Forward link type. * * @see <a href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/links.html#adef-rel">W3C * HTML Specification</a> */ AnchorBuilder rel(String rel); /** * Frame to render the resource in. * * @see <a * href="http://www.w3.org/TR/1999/REC-html401-19991224/present/frames.html#adef-target">W3C * HTML Specification</a> */ AnchorBuilder target(String target); /** * Advisory content type. * * @see <a href="http://www.w3.org/TR/1999/REC-html401-19991224/struct/links.html#adef-type-A">W3C * HTML Specification</a> */ AnchorBuilder type(String type); }
package gretig.datastructuur; import gretig.StatLogger; import java.io.IOException; import java.util.*; import java.util.concurrent.ThreadLocalRandom; /** * Created by brent on 10/8/16. */ public class Graaf { private Boog[] bogen; private Top[] toppen; private HashSet<Top> toppenlijst; private int current; private int tops; private int boogs; public Graaf(int tops, int boogs){ this.tops = tops; this.boogs = boogs; toppen = new Top[tops]; bogen = new Boog[boogs]; toppenlijst = new HashSet<>(tops); current=-1; } /** * Initialiseer de volgende top voor het sequentieel lezen. * @throws IOException te veel toppen */ public void init_next() throws IOException { if(current<tops){ current++; Top t = new Top(current); toppenlijst.add(t); toppen[current] = t; } else { throw new IOException("Fout ingelezen, top teveel."); } } /** * Voeg een boog toe aan de huidige top. * @param nr boog_id */ public void add_boog(int nr) { nr = nr-1; if(bogen[nr]==null){ bogen[nr]=new Boog(nr, toppen[current]); } else { bogen[nr].addBoog(toppen[current]); } } /** * Eerst worden de toppen gesorteerd via pigeonsort (O(n)), daarna worden deze via een stapel verwerkt tot een * dominante toppenverzameling gevonden wordt. * @return String met de dominante toppenverzameling */ public String dominant(){ String out=""; Top[] tt = sortToppen(); Stack<Top> topstack = new Stack<>(); for(Top t : tt){ topstack.push(t); } HashSet<Top> all = toppenlijst; while(!all.isEmpty()&&!topstack.isEmpty()){ Top t = topstack.pop(); if(all.contains(t)){ out+=(t.getId()+1)+" "; all.removeAll(t.getBuren()); all.remove(t); } } return out.trim(); } /** * Waring Surpressed gezien enkel maar unchecked toegang binnen array, die telkens veilig bekeken wordt. * Sorteer de van meeste buren naar minste buren in O(n+l) via het duivenhokprincipe. * n: aantal toppen * l: lengte array * @return Top[] geordende lijst. */ @SuppressWarnings("unchecked") private Top[] sortToppen(){ int min = toppen[0].getBuren().size(); int max = toppen[0].getBuren().size(); for (Top t : toppen){ int s = t.getBuren().size(); min = Math.min(min, s); max = Math.max(max, s); } int size = max - min + 1; Stack<?>[] pigeon = new Stack<?>[size]; for (Top t : toppen){ int s = t.getBuren().size()-min; if(pigeon[s]==null){ pigeon[s]=new Stack<Top>(); } ((Stack<Top>)pigeon[s]).push(t); } int i = 0; Top[] out = new Top[toppen.length]; for (int count = 0; count < size; count++){ if(pigeon[count]!=null){ while(!pigeon[count].empty()){ out[i++] = ((Stack<Top>)pigeon[count]).pop(); } } } return out; } /**Map van elke top met zijn buren * @return toppen gemapt met hun buren */ private HashMap<Top,HashSet<Top>> getTopandNeighbours(){ HashMap<Top,HashSet<Top>> out = new HashMap<>(toppen.length); for(Top t : toppen){ out.put(t,t.getBuren()); } return out; } /** * Print de graaf naar stdout. */ public void graafInfo(){ System.out.println("Graaf info:"); for(Top t : toppen){ System.out.println("Top: "+(t.getId()+1)); System.out.println("Buren: "); for(Top t1 : t.getBuren()){ System.out.print((t1.getId()+1)+" "); } System.out.println(); } } public String hamilton() { Top[] t = sortToppen(); Top[] rev = new Top[t.length]; boolean found = false; /*for(int i=0;i<t.length;i++){ rev[i]=t[t.length-i-1]; }*/ rev = t; String out = ""; HashSet<Top> added = new HashSet<>(tops); Top root = rev[0]; Top current = root; int counter = 0; ArrayList<Top> curr_n_l = current.getBuren_l(); while(added.size()!=tops+1){ Top candidate = curr_n_l.get(counter); if(added.contains(candidate)){ if(candidate.equals(root)&&added.size()==tops){ found=true; break; } else if(++counter>=curr_n_l.size()){ found=false; break; } } else { added.add(candidate); counter=0; current = candidate; curr_n_l = current.getBuren_l(); out+=(current.getId()+1)+" "; } } if(found){ return out.trim(); } else { return "geen cykel gevonden"; } } boolean isBiconnected(HashSet<Top> vertices, HashSet<Top> graaf){ return false; } }
/* * Copyright © 2014 YAOCHEN Corporation, All Rights Reserved. */ package com.yaochen.address.data.mapper.address; import java.util.List; import org.apache.ibatis.annotations.Param; import com.easyooo.framework.sharding.annotation.Table; import com.yaochen.address.data.domain.address.AdRoleRes; import com.yaochen.address.support.Repository; @Repository @Table("AD_ROLE_RES") public interface AdRoleResMapper { int deleteByPrimaryKey(@Param("roleId") Integer roleId, @Param("resType") String resType, @Param("resCode") String resCode); int insert(AdRoleRes record); int insertSelective(AdRoleRes record); List<AdRoleRes> selectByRoleId(@Param("roleId") Integer roleId); }
import java.util.*; import java.io.*; public class Spavanac { public static void main(String[] args) throws IOException { Scanner nya = new Scanner(System.in); Calendar bob = new Calendar.Builder().setTimeOfDay(nya.nextInt(),nya.nextInt(),0).build(); bob.add(Calendar.MINUTE,-45); System.out.printf("%d %d",bob.get(Calendar.HOUR_OF_DAY),bob.get(Calendar.MINUTE)); } }
package server.repositories; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import server.models.Projekt; @RepositoryRestResource(path = "projekte", collectionResourceRel = "projekte") public interface ProjektRepository extends PagingAndSortingRepository<Projekt, Long> { }
package com.iamyeong.myfriendsplace.ui.home; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.icu.text.MessagePattern; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.FirebaseFirestore; import com.google.j2objc.annotations.Weak; import com.iamyeong.myfriendsplace.Comment; import com.iamyeong.myfriendsplace.CommentAdapter; import com.iamyeong.myfriendsplace.FirestoreManager; import com.iamyeong.myfriendsplace.MyRecyclerViewAdapter; import com.iamyeong.myfriendsplace.OnGetPostsListener; import com.iamyeong.myfriendsplace.OnGetUserNameListener; import com.iamyeong.myfriendsplace.Post; import com.iamyeong.myfriendsplace.R; import com.iamyeong.myfriendsplace.UserManager; import com.iamyeong.myfriendsplace.WriteActivity; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collections; import kotlinx.coroutines.CoroutineScope; import kotlinx.coroutines.Dispatchers; import kotlinx.coroutines.GlobalScope; public class HomeFragment extends Fragment implements OnGetPostsListener { private HomeViewModel homeViewModel; private RecyclerView recyclerView; private MyRecyclerViewAdapter adapter; private LinearLayoutManager layoutManager; private FloatingActionButton fab; private FirebaseFirestore db = FirebaseFirestore.getInstance(); private FirestoreManager firestoreManager; private SwipeRefreshLayout swipeRefreshLayout; private ArrayList<Post> homePostList; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class); View root = inflater.inflate(R.layout.fragment_home, container, false); swipeRefreshLayout = root.findViewById(R.id.swipe_home); fab = root.findViewById(R.id.fab_home); firestoreManager = FirestoreManager.getInstance(getActivity()); //Need not bellow code. because already writing when 'onResume' //firestoreManager.getPosts(HomeFragment.this); //getPosts and loadUserName use by Splash Activity!!!!! homePostList= new ArrayList<>(); layoutManager = new LinearLayoutManager(getActivity()); recyclerView = root.findViewById(R.id.rv_home); recyclerView.setLayoutManager(layoutManager); adapter = new MyRecyclerViewAdapter(homePostList, getActivity()); recyclerView.setAdapter(adapter); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { firestoreManager.getPosts(HomeFragment.this); swipeRefreshLayout.setRefreshing(false); Toast.makeText(getActivity(), "Refresh complete!", Toast.LENGTH_SHORT).show(); } }); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getActivity(), "FAB Click!", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(getActivity(), WriteActivity.class); startActivity(intent); } }); return root; } @Override public void onResume() { super.onResume(); firestoreManager.getPosts(HomeFragment.this); Log.d("HomeFragment : ", "onResume"); } @Override public void onGetPosts(ArrayList<Post> postList) { //Sort function add Collections.sort(postList); adapter.updateAdapterList(postList); adapter.notifyDataSetChanged(); Toast.makeText(getActivity(), "getPosts", Toast.LENGTH_SHORT).show(); } }
package mg.egg.eggc.compiler.libegg.base; import java.io.Serializable; public abstract class EltREGLE implements Serializable { private static final long serialVersionUID = 1L; protected REGLE regle; protected String nom; protected int pos; public String getNom() { return nom; } public EltREGLE(REGLE regle, String nom, int pos) { super(); this.regle = regle; this.nom = nom; this.pos = pos; } public int getPos() { return pos; } public void setPos(int i) { pos = i; } public void shiftLeft() { } public void shiftRight() { } public void remove() { } }
/** * (C) Copyright IBM Corporation 2014. * * 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 net.wasdev.wlp.ant.install; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Version implements Comparable<Version> { private final static int WILDCARD = -1; private final int major; private final int minor; private final int micro; private final String qualifier; private Version(int major, int minor, int micro, String qualifier) { this.major = major; this.minor = minor; this.micro = micro; this.qualifier = qualifier; } public static Version parseVersion(String version) { return parseVersion(version, false); } public static Version parseVersion(String version, boolean wildcard) { Pattern p = null; if (wildcard) { p = Pattern.compile("^([\\d\\+]+)(?:\\.([\\d\\+]+))?(?:\\.([\\d\\+]+))?(?:\\_(.*))?$"); } else { p = Pattern.compile("^(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?(?:\\_(.*))?$"); } Matcher m = p.matcher(version); if (m.find()) { int major = parseComponent(m.group(1)); int minor = parseComponent(m.group(2)); int micro = parseComponent(m.group(3)); String qualifier = m.group(4); return new Version(major, minor, micro, qualifier); } else { throw new IllegalArgumentException("Invalid version: " + version); } } private static int parseComponent(String version) { if (version == null) { return 0; } else if ("+".equals(version)) { return WILDCARD; } else { return Integer.parseInt(version); } } public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Version)) { return false; } return compareTo((Version)other) == 0; } public int compareTo(Version other) { if (other == this) { return 0; } int result = major - other.major; if (result != 0) { return result; } result = minor - other.minor; if (result != 0) { return result; } result = micro - other.micro; if (result != 0) { return result; } return qualifier.compareTo(other.qualifier); } public boolean match(Version version) { if (major == WILDCARD) { return true; } else if (major != version.major) { return false; } if (minor == WILDCARD) { return true; } else if (minor != version.minor) { return false; } if (micro == WILDCARD) { return true; } else if (micro != version.micro) { return false; } if ("+".equals(qualifier)) { return true; } else if (qualifier == null) { return version.qualifier == null; } else { return qualifier.equals(version.qualifier); } } public int getMajor() { return major; } public int getMinor() { return minor; } public int getMicro() { return micro; } public String getQualifier() { return qualifier; } public String toString() { StringBuilder result = new StringBuilder(); if (major == WILDCARD) { result.append('+'); } else { result.append(major); result.append('.'); if (minor == WILDCARD) { result.append('+'); } else { result.append(minor); result.append('.'); if (micro == WILDCARD) { result.append('+'); } else { result.append(micro); if (qualifier != null) { result.append('_'); result.append(qualifier); } } } } return result.toString(); } }
package org.fuserleer.utils; import java.util.Objects; /** * Utilities for manipulating primitive {@code long} values. */ public final class Longs { private Longs() { throw new IllegalStateException("Can't construct"); } /** * Create a byte array of length {@link Long#BYTES}, and * populate it with {@code value} in big-endian order. * * @param value The value to convert * @return The resultant byte array. */ public static byte[] toByteArray(long value) { return copyTo(value, new byte[Long.BYTES], 0); } /** * Copy the byte value of {@code value} into {@code bytes} * starting at {@code offset}. A total of {@link Long#BYTES} * will be written to {@code bytes}. * * @param value The value to convert * @param bytes The array to write the value into * @param offset The offset at which to write the value * @return The value of {@code bytes} */ public static byte[] copyTo(long value, byte[] bytes, int offset) { Objects.requireNonNull(bytes, "bytes is null for 'long' conversion"); for (int i = offset + Long.BYTES - 1; i >= offset; i--) { bytes[i] = (byte) (value & 0xFFL); value >>>= 8; } return bytes; } /** * Exactly equivalent to {@code fromByteArray(bytes, 0)}. * * @param bytes The byte array to decode to a long * @return The decoded long value * @see #fromByteArray(byte[], int) */ public static long fromByteArray(byte[] bytes) { return fromByteArray(bytes, 0); } /** * Decode a long from array {@code bytes} at {@code offset}. * Bytes from array {@code bytes[offset]} up to and including * {@code bytes[offset + Long.BYTES - 1]} will be read from * array {@code bytes}. * * @param bytes The byte array to decode to a long * @param offset The offset within the array to start decoding * @return The decoded long value */ public static long fromByteArray(byte[] bytes, int offset) { Objects.requireNonNull(bytes, "bytes is null for 'long' conversion"); long value = 0; for (int b = 0; b < Long.BYTES; b++) { value <<= 8; value |= bytes[offset + b] & 0xFFL; } return value; } /** * Assemble a {@code long} value from it's component bytes. * * @param b0 Most significant byte * @param b1 Next most significant byte * @param b2 &hellip; * @param b3 &hellip; * @param b4 &hellip; * @param b5 &hellip; * @param b6 Next least significant byte * @param b7 Least significant byte * @return The {@code long} value represented by the arguments. */ public static long fromBytes(byte b0, byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7) { return (b0 & 0xFFL) << 56 | (b1 & 0xFFL) << 48 | (b2 & 0xFFL) << 40 | (b3 & 0xFFL) << 32 | (b4 & 0xFFL) << 24 | (b5 & 0xFFL) << 16 | (b6 & 0xFFL) << 8 | (b7 & 0xFFL); } }
package com.example.galdino.filmespopulares.adapter; import android.databinding.DataBindingUtil; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.galdino.filmespopulares.databinding.AdapterListComentariosBinding; import com.example.galdino.filmespopulares.dominio.filmeDetalhe.Result; import java.util.List; /** * Created by Galdino on 17/08/2017. */ public class AdapterListComentario extends RecyclerView.Adapter<AdapterListComentario.ViewHolder> { // 1 - Parametros private List<Result> mList; // 2 - Construtor public AdapterListComentario(List<Result> mList) { this.mList = mList; } // 3 - cria o viewHolder public class ViewHolder extends RecyclerView.ViewHolder { private AdapterListComentariosBinding mBinding; public ViewHolder(AdapterListComentariosBinding binding) { super(binding.getRoot()); mBinding = binding; } } // infla o holder @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { AdapterListComentariosBinding binding = AdapterListComentariosBinding.inflate(LayoutInflater.from(parent.getContext()),parent,false); return new ViewHolder(binding); } @Override public void onBindViewHolder(ViewHolder holder, int position) { if(mList != null && mList.get(position) != null && holder.mBinding != null) { Result result = mList.get(position); holder.mBinding.tvNomePessoa.setText(result.getAuthor()); holder.mBinding.tvComentario.setText(result.getContent()); } } @Override public int getItemCount() { if(mList == null) { return 0; } else { return mList.size(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.webbeans.component.creation; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.HashSet; import java.util.Set; import jakarta.enterprise.inject.Produces; import jakarta.enterprise.inject.UnproxyableResolutionException; import jakarta.enterprise.inject.spi.AnnotatedField; import jakarta.enterprise.inject.spi.AnnotatedType; import jakarta.inject.Named; import org.apache.webbeans.component.InjectionTargetBean; import org.apache.webbeans.component.ProducerFieldBean; import org.apache.webbeans.component.ResourceBean; import org.apache.webbeans.config.WebBeansContext; import org.apache.webbeans.exception.WebBeansConfigurationException; import org.apache.webbeans.portable.events.ProcessBeanAttributesImpl; import org.apache.webbeans.spi.api.ResourceReference; import org.apache.webbeans.util.AnnotationUtil; import org.apache.webbeans.util.Asserts; import org.apache.webbeans.util.WebBeansUtil; /** * @param <T> bean class type */ public class ProducerFieldBeansBuilder<T> { protected final WebBeansContext webBeansContext; protected final AnnotatedType<T> annotatedType; /** * Creates a new instance. * */ public ProducerFieldBeansBuilder(WebBeansContext webBeansContext, AnnotatedType<T> annotatedType) { Asserts.assertNotNull(webBeansContext, Asserts.PARAM_NAME_WEBBEANSCONTEXT); Asserts.assertNotNull(annotatedType, "annotated type"); this.webBeansContext = webBeansContext; this.annotatedType = annotatedType; } /** * {@inheritDoc} */ public Set<ProducerFieldBean<?>> defineProducerFields(InjectionTargetBean<T> bean) { Set<ProducerFieldBean<?>> producerBeans = new HashSet<>(); Set<AnnotatedField<? super T>> annotatedFields = annotatedType.getFields(); for(AnnotatedField<? super T> annotatedField: annotatedFields) { if(annotatedField.isAnnotationPresent(Produces.class) && annotatedField.getJavaMember().getDeclaringClass().equals(annotatedType.getJavaClass())) { Annotation[] anns = AnnotationUtil.asArray(annotatedField.getAnnotations()); Field field = annotatedField.getJavaMember(); //Producer field for resource Annotation resourceAnnotation = AnnotationUtil.hasOwbInjectableResource(anns); //Producer field for resource if(resourceAnnotation != null) { //Check for valid resource annotation //WebBeansUtil.checkForValidResources(annotatedField.getDeclaringType().getJavaClass(), field.getType(), field.getName(), anns); ResourceReference<T, Annotation> resourceRef = new ResourceReference<>(annotatedType.getJavaClass(), field.getName(), (Class<T>) field.getType(), resourceAnnotation); //Can not define EL name if(annotatedField.isAnnotationPresent(Named.class)) { throw new WebBeansConfigurationException("Resource producer annotated field : " + annotatedField + " can not define EL name"); } ProcessBeanAttributesImpl<T> processBeanAttributes = fireProcessBeanAttributes(annotatedField); if (processBeanAttributes != null) { ResourceBeanBuilder<T, Annotation> resourceBeanCreator = new ResourceBeanBuilder<>(bean, resourceRef, annotatedField, processBeanAttributes.getAttributes()); ResourceBean<T, Annotation> resourceBean = resourceBeanCreator.getBean(); resourceBean.setProducerField(field); producerBeans.add(resourceBean); webBeansContext.getWebBeansUtil().setBeanEnableFlagForProducerBean(bean, resourceBean, anns); } } else { ProcessBeanAttributesImpl<T> processBeanAttributes = fireProcessBeanAttributes(annotatedField); ProducerFieldBeanBuilder<T, ProducerFieldBean<T>> producerFieldBeanCreator = new ProducerFieldBeanBuilder<>(bean, annotatedField, processBeanAttributes.getAttributes()); ProducerFieldBean<T> producerFieldBean = producerFieldBeanCreator.getBean(); UnproxyableResolutionException lazyException = webBeansContext.getDeploymentValidationService() .validateProxyable(producerFieldBean, processBeanAttributes.isIgnoreFinalMethods()); if (lazyException != null) // should we use UnproxyableBean there too? if not required by TCK, better to fail eagerly { throw lazyException; } producerFieldBeanCreator.validate(); producerFieldBean.setProducerField(field); webBeansContext.getWebBeansUtil().setBeanEnableFlagForProducerBean(bean, producerFieldBean, anns); WebBeansUtil.checkProducerGenericType(producerFieldBean, annotatedField.getJavaMember()); producerBeans.add(producerFieldBean); } } } return producerBeans; } private ProcessBeanAttributesImpl<T> fireProcessBeanAttributes(AnnotatedField<? super T> annotatedField) { return webBeansContext.getWebBeansUtil().fireProcessBeanAttributes( annotatedField, annotatedField.getJavaMember().getType(), BeanAttributesBuilder.forContext(webBeansContext).newBeanAttibutes((AnnotatedField<T>)annotatedField).build()); } }
package com.tencent.mm.plugin.gallery.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; class AlbumPreviewUI$9 implements OnClickListener { final /* synthetic */ AlbumPreviewUI jCE; AlbumPreviewUI$9(AlbumPreviewUI albumPreviewUI) { this.jCE = albumPreviewUI; } public final void onClick(DialogInterface dialogInterface, int i) { this.jCE.startActivity(new Intent("android.settings.MANAGE_APPLICATIONS_SETTINGS")); } }
package co.th.aten.network.model; import java.io.Serializable; public class TeamBinaryReportModel implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int index; private int customerId; private String customerCode; private String customerName; private String position; private String recomment; private String honor; private String side; public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public int getCustomerId() { return customerId; } public void setCustomerId(int customerId) { this.customerId = customerId; } public String getCustomerCode() { return customerCode; } public void setCustomerCode(String customerCode) { this.customerCode = customerCode; } public String getCustomerName() { return customerName; } public void setCustomerName(String customerName) { this.customerName = customerName; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getRecomment() { return recomment; } public void setRecomment(String recomment) { this.recomment = recomment; } public String getHonor() { return honor; } public void setHonor(String honor) { this.honor = honor; } public String getSide() { return side; } public void setSide(String side) { this.side = side; } }
package com.sdl.webapp.tridion; import com.sdl.context.engine.repository.ContextRepositoryManager; import com.tridion.content.BinaryFactory; import com.tridion.dynamiccontent.DynamicMetaRetriever; import lombok.extern.slf4j.Slf4j; import org.dd4t.core.factories.ComponentPresentationFactory; import org.dd4t.core.factories.impl.ComponentPresentationFactoryImpl; import org.dd4t.providers.ComponentPresentationProvider; import org.dd4t.providers.PayloadCacheProvider; import org.dd4t.providers.impl.BrokerLinkProvider; import org.dd4t.providers.impl.BrokerPageProvider; import org.dd4t.providers.impl.BrokerTaxonomyProvider; import org.dd4t.providers.impl.NoCacheProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.context.annotation.Profile; import javax.annotation.PostConstruct; import javax.servlet.ServletContext; import java.io.File; @Configuration @ImportResource("classpath:com/sdl/context/engine/repository/beans-sdl-context-engine.xml") @ComponentScan("com.sdl.webapp.tridion") @Slf4j //todo dxa2 move to com.sdl.dxa public class SpringContextConfiguration { @Value("${dxa.tridion.2013.context.repository.url}") private String contextRepositoryUrl; @Value("${dxa.tridion.2013.context.repository.location}") private String contextRepositoryLocation; @Value("${dxa.tridion.2013.context.repository.load.enabled}") private Boolean contextRepositoryLoad; @Autowired private PayloadCacheProvider ehCacheProvider; @Autowired private ServletContext servletContext; @PostConstruct public void init() { if (contextRepositoryLoad) { loadCwdRepository(); } } private void loadCwdRepository() { String repositoryLocation = System.getProperty("repository.location", contextRepositoryLocation); if (!new File(repositoryLocation).isAbsolute()) { repositoryLocation = new File(repositoryLocation).getAbsolutePath(); log.debug("CWD repository URL is not in System properties (which is=[{}]) is null or relative, set {}", System.getProperty("repository.location"), repositoryLocation); System.setProperty("repository.location", repositoryLocation); } log.debug("Using {} CWD repository location", repositoryLocation); if (!new File(repositoryLocation).exists()) { log.info("Initialization of ContextRepositoryManager#main({}), FileCheck.repository.location: {}, System.repository.location: {}", contextRepositoryUrl, repositoryLocation, System.getProperty("repository.location")); ContextRepositoryManager.main(new String[]{contextRepositoryUrl}); } else { log.info("CWD repository {} doesn't need to be updated", repositoryLocation); } } @Bean public BrokerLinkProvider linkProvider() { BrokerLinkProvider linkProvider = new BrokerLinkProvider(); linkProvider.setContentIsCompressed("false"); return linkProvider; } @Bean public BrokerPageProvider pageProvider() { BrokerPageProvider pageProvider = new BrokerPageProvider(); pageProvider.setContentIsCompressed("false"); return pageProvider; } @Bean public BrokerTaxonomyProvider taxonomyProvider() { return new BrokerTaxonomyProvider(); } @Bean public DynamicMetaRetriever dynamicMetaRetriever() { return new DynamicMetaRetriever(); } @Bean public BinaryFactory binaryFactory() { return new BinaryFactory(); } @Bean public ComponentPresentationFactory componentPresentationFactory() { ComponentPresentationFactoryImpl presentationFactory = ComponentPresentationFactoryImpl.getInstance(); presentationFactory.setComponentPresentationProvider(componentPresentationProvider()); presentationFactory.setCacheProvider(ehCacheProvider); return presentationFactory; } @Bean public ComponentPresentationProvider componentPresentationProvider() { BrokerComponentPresentationProvider componentPresentationProvider = new BrokerComponentPresentationProvider(); componentPresentationProvider.setContentIsCompressed("false"); componentPresentationProvider.setCacheProvider(ehCacheProvider); return componentPresentationProvider; } @Configuration @Profile("dxa.no-cache") public static class NoCacheConfiguration { @Bean public PayloadCacheProvider cacheProvider() { return new NoCacheProvider(); } } }
package com.actionimpl; import java.io.InputStream; import com.javabean.User; public interface UserImpl { int register(User user); int login(String username,String password); void remove (int uid); int update(User user); User find(int uid); InputStream returnImage(int id); }
package napps.com.nearbycoffee.Contract; import napps.com.nearbycoffee.BasePresenter; import napps.com.nearbycoffee.BaseView; /** * Created by "nithesh" on 7/15/2017. */ public interface NetworkContract { interface View extends BaseView<Presenter>{ void showNetworkError(); } interface Presenter extends BasePresenter{ void checkNetworkConnection(); } }