text
stringlengths
10
2.72M
package android.support.v4.app; import android.app.NotificationManager; import android.content.ComponentName; import android.content.Context; import android.os.Build.VERSION; import android.os.IBinder; import android.provider.Settings.Secure; import java.util.HashSet; import java.util.Set; public final class ag { private static final int qm = qu.bC(); private static final Object qn = new Object(); private static String qo; private static Set<String> qp = new HashSet(); private static final Object qs = new Object(); private static h qt; public static final b qu; public final Context mContext; public final NotificationManager qr = ((NotificationManager) this.mContext.getSystemService("notification")); private static class a implements i { final int id; final String packageName; final boolean qv = false; final String tag = null; public a(String str, int i) { this.packageName = str; this.id = i; } public final void a(s sVar) { if (this.qv) { sVar.K(this.packageName); } else { sVar.b(this.packageName, this.id, this.tag); } } public final String toString() { StringBuilder stringBuilder = new StringBuilder("CancelTask["); stringBuilder.append("packageName:").append(this.packageName); stringBuilder.append(", id:").append(this.id); stringBuilder.append(", tag:").append(this.tag); stringBuilder.append(", all:").append(this.qv); stringBuilder.append("]"); return stringBuilder.toString(); } } private static class g { final ComponentName qx; final IBinder qy; public g(ComponentName componentName, IBinder iBinder) { this.qx = componentName; this.qy = iBinder; } } static { if (VERSION.SDK_INT >= 14) { qu = new e(); } else if (VERSION.SDK_INT >= 5) { qu = new d(); } else { qu = new c(); } } public static ag L(Context context) { return new ag(context); } private ag(Context context) { this.mContext = context; } public static Set<String> M(Context context) { String string = Secure.getString(context.getContentResolver(), "enabled_notification_listeners"); if (!(string == null || string.equals(qo))) { String[] split = string.split(":"); Set hashSet = new HashSet(split.length); for (String unflattenFromString : split) { ComponentName unflattenFromString2 = ComponentName.unflattenFromString(unflattenFromString); if (unflattenFromString2 != null) { hashSet.add(unflattenFromString2.getPackageName()); } } synchronized (qn) { qp = hashSet; qo = string; } } return qp; } public final void a(i iVar) { synchronized (qs) { if (qt == null) { qt = new h(this.mContext.getApplicationContext()); } } qt.mHandler.obtainMessage(0, iVar).sendToTarget(); } }
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.7 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2016.05.11 um 01:33:35 PM CEST // package com.thyssenkrupp.tks.fls.qf.server.qcs.receive.xml; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für NegativquittungType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="NegativquittungType"> * &lt;complexContent> * &lt;extension base="{http://www-fls.thyssen.com/xml/schema/qcs}SendTelegrammType"> * &lt;sequence> * &lt;element name="TksIdent" type="{http://www-fls.thyssen.com/xml/schema/qcs}TksIdentType"/> * &lt;element name="TelegrammId" type="{http://www.w3.org/2001/XMLSchema}unsignedLong" minOccurs="0"/> * &lt;element name="Fehlergrund" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Fehlertext" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "NegativquittungType", propOrder = { "tksIdent", "telegrammId", "fehlergrund", "fehlertext" }) public class NegativquittungType extends SendTelegrammType { @XmlElement(name = "TksIdent", required = true) protected String tksIdent; @XmlElement(name = "TelegrammId") @XmlSchemaType(name = "unsignedLong") protected BigInteger telegrammId; @XmlElement(name = "Fehlergrund") protected String fehlergrund; @XmlElement(name = "Fehlertext") protected String fehlertext; /** * Ruft den Wert der tksIdent-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getTksIdent() { return tksIdent; } /** * Legt den Wert der tksIdent-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setTksIdent(String value) { this.tksIdent = value; } /** * Ruft den Wert der telegrammId-Eigenschaft ab. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getTelegrammId() { return telegrammId; } /** * Legt den Wert der telegrammId-Eigenschaft fest. * * @param value * allowed object is * {@link BigInteger } * */ public void setTelegrammId(BigInteger value) { this.telegrammId = value; } /** * Ruft den Wert der fehlergrund-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getFehlergrund() { return fehlergrund; } /** * Legt den Wert der fehlergrund-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setFehlergrund(String value) { this.fehlergrund = value; } /** * Ruft den Wert der fehlertext-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getFehlertext() { return fehlertext; } /** * Legt den Wert der fehlertext-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setFehlertext(String value) { this.fehlertext = value; } }
/* * Copyright 2016 RedRoma, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tech.aroma.authentication.service.operations; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.TypeLiteral; import java.time.Duration; import java.util.function.Function; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import tech.aroma.thrift.LengthOfTime; import tech.aroma.thrift.authentication.service.CreateTokenRequest; import tech.aroma.thrift.authentication.service.CreateTokenResponse; import tech.aroma.thrift.authentication.service.GetTokenInfoRequest; import tech.aroma.thrift.authentication.service.GetTokenInfoResponse; import tech.aroma.thrift.authentication.service.InvalidateTokenRequest; import tech.aroma.thrift.authentication.service.InvalidateTokenResponse; import tech.aroma.thrift.authentication.service.VerifyTokenRequest; import tech.aroma.thrift.authentication.service.VerifyTokenResponse; import tech.aroma.thrift.functions.TimeFunctions; import tech.sirwellington.alchemy.thrift.operations.ThriftOperation; /** * * @author SirWellington */ public final class ModuleAuthenticationOperations extends AbstractModule { private final static Logger LOG = LoggerFactory.getLogger(ModuleAuthenticationOperations.class); @Override protected void configure() { bind(new TypeLiteral<ThriftOperation<CreateTokenRequest, CreateTokenResponse>>() {}) .to(CreateTokenOperation.class); bind(new TypeLiteral<ThriftOperation<GetTokenInfoRequest, GetTokenInfoResponse>>() {}) .to(GetTokenInfoOperation.class); bind(new TypeLiteral<ThriftOperation<InvalidateTokenRequest, InvalidateTokenResponse>>() {}) .to(InvalidateTokenOperation.class); bind(new TypeLiteral<ThriftOperation<VerifyTokenRequest, VerifyTokenResponse>>() {}) .to(VerifyTokenOperation.class); } @Provides Function<LengthOfTime, Duration> provideLengthOfTimeConverter() { return TimeFunctions.LENGTH_OF_TIME_TO_DURATION; } }
package com.tencent.mm.plugin.appbrand.ui; import android.support.v7.widget.RecyclerView.t; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.plugin.appbrand.appusage.k; import com.tencent.mm.plugin.appbrand.launching.AppBrandLaunchProxyUI; import com.tencent.mm.plugin.appbrand.r.c; import com.tencent.mm.plugin.appbrand.report.AppBrandStatObject; import com.tencent.mm.plugin.appbrand.s.g; import com.tencent.mm.plugin.appbrand.ui.AppBrandStarListUI.a; import com.tencent.rtmp.TXLiveConstants; final class AppBrandStarListUI$a$f extends t implements OnClickListener, OnLongClickListener { final /* synthetic */ a gvU; k gwi; ImageView gwj; TextView gwk; TextView gwl; View gwm; AppBrandStarListUI$a$f(a aVar, View view) { this.gvU = aVar; super(view); this.gwj = (ImageView) view.findViewById(g.icon); this.gwk = (TextView) view.findViewById(g.name); this.gwl = (TextView) view.findViewById(g.tag_text); this.gwm = view.findViewById(g.btn_delete); this.gwm.setOnClickListener(this); this.SU.setOnClickListener(this); this.SU.setOnLongClickListener(this); } public final void onClick(View view) { if (this.gwi != null) { if (a.e(this.gvU) && view == this.gwm) { c.Em().H(new 1(this, this.gwi.bGy, this.gwi.fig, gm())); } if (!a.e(this.gvU) && view == this.SU) { k kVar = this.gwi; AppBrandStatObject appBrandStatObject = new AppBrandStatObject(); appBrandStatObject.scene = TXLiveConstants.PUSH_EVT_OPEN_CAMERA_SUCC; AppBrandLaunchProxyUI.a(this.gvU.getActivity(), kVar.bGy, null, kVar.fig, -1, appBrandStatObject, null); } } } public final boolean onLongClick(View view) { if (a.e(this.gvU)) { return false; } a.g(this.gvU); return true; } }
package net; import state.ClientControllable; import state.Controllable; public abstract class ClientBase implements Controllable, RemoteControllable { private ClientControllable clientControllable; public void registerClientControllable(ClientControllable con) { clientControllable = con; } // pass the move player through the RemoteControllable Interface public Boolean movePlayer(Integer playerId, Integer targetNodeId, TicketType ticketType) { boolean success = this.makeServerMove(playerId, targetNodeId, ticketType); if(success && clientControllable != null) { if(!clientControllable.movePlayer(playerId, targetNodeId, ticketType)) { System.out.println("Why?"); } } return success; } // pass the call into the client controllable public Boolean initialiseGame(Integer numDetectives) { if(clientControllable != null) return clientControllable.initialiseGame(numDetectives); return false; } // pass the call into the client controllable public Integer getNodeIdFromLocation(Integer xPosition, Integer yPosition) { if(clientControllable != null) return clientControllable.getNodeIdFromLocation(xPosition, yPosition); return 0; } // pass the call into the client controllable public Boolean saveGame(String filename) { if(clientControllable != null) return clientControllable.saveGame(filename); return false; } // pass the call into the client controllable public Boolean loadGame(String filename) { if(clientControllable != null) return clientControllable.loadGame(filename); return false; } }
/** * */ package com.goodhealth.design.demo.BuilderPattern; /** * @author 24663 * @date 2018年10月21日 * @Description */ public class Client { public static void main(String[] args) { God di=new God(); try{ Chinese c1=di.getBadChinese(); c1.toString(); Chinese c2=di.getKindChinese(); c2.toString(); English e1=di.getBadEnglish(); e1.toString(); English e2=di.getKindEnglish(); e2.toString(); }catch (Exception e) { e.printStackTrace(); } } }
package com.formation.objet; public class User { private static int role; private static String login; private static User user; private static User User(int role, String login) { setRole(role); setLogin(login); return user; } public static User getUser(int role, String login){ if(user==null){ user=User(role,login); } return user; } public static int getRole() { return role; } public static void setRole(int role) { User.role = role; } public static String getLogin() { return login; } public static void setLogin(String login) { User.login = login; } public static User getUser() { return user; } public static void setUser(User user) { User.user = user; } }
package com.trainex.fragment.inmain; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Toast; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import com.trainex.R; import com.trainex.adapter.listadapter.CoachAdapter; import com.trainex.diaglog.AlertLoginDialog; import com.trainex.diaglog.CustomAlertDialog; import com.trainex.model.Coach; import com.trainex.rest.RestClient; import com.trainex.uis.main.MainActivity; public class FavoritesFragment extends Fragment { private RecyclerView lvFavorites; private View view; private ArrayList<Coach> listCoach; private CoachAdapter adapter; private String token; private SwipeRefreshLayout swipeContainer; private ImageView imgShowDrawer; @Override public void onAttach(Context context) { super.onAttach(context); listCoach = new ArrayList<>(); SharedPreferences prefs = getContext().getSharedPreferences("MY_SHARE_PREFERENCE", getContext().MODE_PRIVATE); token = prefs.getString("token", ""); getData(); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_favorites, container,false); init(); bind(); return view; } private void init(){ lvFavorites = (RecyclerView) view.findViewById(R.id.lvFavorites); swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container); imgShowDrawer = (ImageView) view.findViewById(R.id.imgShowDrawer); } private void bind(){ imgShowDrawer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { MainActivity.showMenu(); } }); RecyclerView.LayoutManager layoutManager1 = new LinearLayoutManager(getContext()); lvFavorites.setLayoutManager(layoutManager1); adapter = new CoachAdapter(getContext(),listCoach, true); lvFavorites.setAdapter(adapter); // lvFavorites.addOnScrollListener(new RecyclerView.OnScrollListener() { // @Override // public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) { // super.onScrolled(recyclerView, dx, dy); // LinearLayoutManager layoutManager1=LinearLayoutManager.class.cast(recyclerView.getLayoutManager()); // int visibleItemCount = layoutManager1.getChildCount(); // int totalItemCount = layoutManager1.getItemCount(); // int firstVisibleItemPosition= layoutManager1.findFirstVisibleItemPosition(); // // // Load more if we have reach the end to the recyclerView // if ( (visibleItemCount + firstVisibleItemPosition) >= totalItemCount && firstVisibleItemPosition >= 0) { // fakeData(); // adapter.notifyItemInserted(listCoach.size()-1); // } // } // }); view.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if( keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) { getActivity().onBackPressed(); return true; } return false; } }); swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { listCoach.clear(); getData(); } }); } private void getData(){ if (!token.equalsIgnoreCase("")){ Call<JsonElement> callGetListFavorite= RestClient.getApiInterface().getFavoritesTrainers(token); callGetListFavorite.enqueue(new Callback<JsonElement>() { @Override public void onResponse(Call<JsonElement> call, Response<JsonElement> response) { swipeContainer.setRefreshing(false); if (response.isSuccessful()){ JsonObject body = response.body().getAsJsonObject(); if (body.get("code").getAsInt()==200){ JsonArray responseList = body.get("data").getAsJsonObject().get("trainer_list").getAsJsonArray(); JsonArray listRating = body.get("data").getAsJsonObject().get("review").getAsJsonArray(); if (responseList.size()>0){ for (int i = 0; i< responseList.size(); i++){ int idTrainer = responseList.get(i).getAsJsonObject().get("trainer_id").getAsInt(); String nameTrainer=""; if (!responseList.get(i).getAsJsonObject().get("trainer_name").isJsonNull()){ nameTrainer = responseList.get(i).getAsJsonObject().get("trainer_name").getAsString(); } boolean isFeature=false; if (!responseList.get(i).getAsJsonObject().get("trainer_feature").isJsonNull()){ if (responseList.get(i).getAsJsonObject().get("trainer_feature").getAsInt()!=0){ isFeature = true; } } String location=""; if (!responseList.get(i).getAsJsonObject().get("trainer_address").isJsonNull()){ location = responseList.get(i).getAsJsonObject().get("trainer_address").getAsString(); } float rating = 0; String resAvatar=""; if (!responseList.get(i).getAsJsonObject().get("trainer_avatar").isJsonNull()){ resAvatar = responseList.get(i).getAsJsonObject().get("trainer_avatar").getAsString(); } for (JsonElement x:listRating){ if (x.getAsJsonObject().has(idTrainer+"")){ rating = x.getAsJsonObject().get(idTrainer+"").getAsFloat(); } } Coach coach = new Coach(idTrainer, nameTrainer,location, rating,true,isFeature,resAvatar); listCoach.add(coach); adapter.notifyDataSetChanged(); } }else if (body.get("code").getAsInt()==400){ CustomAlertDialog alertDialog = new CustomAlertDialog(getContext(), "Something wrong!","You don't favorite any one", "Ok") { @Override public void doSomethingWhenDismiss() { } }; alertDialog.show(); } }else{ String s = ""; if (body.has("error")){ s = body.get("error").getAsString(); } if (body.has("message")){ s = body.get("message").getAsString(); } CustomAlertDialog alertDialog = new CustomAlertDialog(getContext(),"Error!",s,"Ok") { @Override public void doSomethingWhenDismiss() { MainActivity.showHomeFromLeft(); } }; alertDialog.show(); } } } @Override public void onFailure(Call<JsonElement> call, Throwable t) { Toast.makeText(getContext(), "Lofad ailed!", Toast.LENGTH_SHORT).show(); } }); } } }
package dev.schoenberg.kicker_stats.rest.exceptionMapper; import static javax.ws.rs.core.Response.Status.*; import dev.schoenberg.kicker_stats.core.exception.NotFoundException; public class NotFoundExceptionWrapper extends GenericExceptionWrapper<NotFoundException> { public NotFoundExceptionWrapper() { super(NOT_FOUND); } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.util.Date; /** * IvMonthcheckheaderId generated by hbm2java */ public class IvMonthcheckheaderId implements java.io.Serializable { private Long monthchecktype; private String warehouseid; private String invmonthcheckid; private Date startdate; private Date enddate; private String billchecker; private String creator; private Date createtime; private String notes; private String text1; private String text2; private String text3; private String text4; private String text5; private String text6; private String text7; private String text8; private String text9; private String text10; private Short accountantYear; private Byte accountantMonth; private String invmonthcheckname; private String warehousename; private String creatorname; private String monthchecktypedesc; public IvMonthcheckheaderId() { } public IvMonthcheckheaderId(String warehouseid, String invmonthcheckid) { this.warehouseid = warehouseid; this.invmonthcheckid = invmonthcheckid; } public IvMonthcheckheaderId(Long monthchecktype, String warehouseid, String invmonthcheckid, Date startdate, Date enddate, String billchecker, String creator, Date createtime, String notes, String text1, String text2, String text3, String text4, String text5, String text6, String text7, String text8, String text9, String text10, Short accountantYear, Byte accountantMonth, String invmonthcheckname, String warehousename, String creatorname, String monthchecktypedesc) { this.monthchecktype = monthchecktype; this.warehouseid = warehouseid; this.invmonthcheckid = invmonthcheckid; this.startdate = startdate; this.enddate = enddate; this.billchecker = billchecker; this.creator = creator; this.createtime = createtime; this.notes = notes; this.text1 = text1; this.text2 = text2; this.text3 = text3; this.text4 = text4; this.text5 = text5; this.text6 = text6; this.text7 = text7; this.text8 = text8; this.text9 = text9; this.text10 = text10; this.accountantYear = accountantYear; this.accountantMonth = accountantMonth; this.invmonthcheckname = invmonthcheckname; this.warehousename = warehousename; this.creatorname = creatorname; this.monthchecktypedesc = monthchecktypedesc; } public Long getMonthchecktype() { return this.monthchecktype; } public void setMonthchecktype(Long monthchecktype) { this.monthchecktype = monthchecktype; } public String getWarehouseid() { return this.warehouseid; } public void setWarehouseid(String warehouseid) { this.warehouseid = warehouseid; } public String getInvmonthcheckid() { return this.invmonthcheckid; } public void setInvmonthcheckid(String invmonthcheckid) { this.invmonthcheckid = invmonthcheckid; } public Date getStartdate() { return this.startdate; } public void setStartdate(Date startdate) { this.startdate = startdate; } public Date getEnddate() { return this.enddate; } public void setEnddate(Date enddate) { this.enddate = enddate; } public String getBillchecker() { return this.billchecker; } public void setBillchecker(String billchecker) { this.billchecker = billchecker; } public String getCreator() { return this.creator; } public void setCreator(String creator) { this.creator = creator; } public Date getCreatetime() { return this.createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public String getNotes() { return this.notes; } public void setNotes(String notes) { this.notes = notes; } public String getText1() { return this.text1; } public void setText1(String text1) { this.text1 = text1; } public String getText2() { return this.text2; } public void setText2(String text2) { this.text2 = text2; } public String getText3() { return this.text3; } public void setText3(String text3) { this.text3 = text3; } public String getText4() { return this.text4; } public void setText4(String text4) { this.text4 = text4; } public String getText5() { return this.text5; } public void setText5(String text5) { this.text5 = text5; } public String getText6() { return this.text6; } public void setText6(String text6) { this.text6 = text6; } public String getText7() { return this.text7; } public void setText7(String text7) { this.text7 = text7; } public String getText8() { return this.text8; } public void setText8(String text8) { this.text8 = text8; } public String getText9() { return this.text9; } public void setText9(String text9) { this.text9 = text9; } public String getText10() { return this.text10; } public void setText10(String text10) { this.text10 = text10; } public Short getAccountantYear() { return this.accountantYear; } public void setAccountantYear(Short accountantYear) { this.accountantYear = accountantYear; } public Byte getAccountantMonth() { return this.accountantMonth; } public void setAccountantMonth(Byte accountantMonth) { this.accountantMonth = accountantMonth; } public String getInvmonthcheckname() { return this.invmonthcheckname; } public void setInvmonthcheckname(String invmonthcheckname) { this.invmonthcheckname = invmonthcheckname; } public String getWarehousename() { return this.warehousename; } public void setWarehousename(String warehousename) { this.warehousename = warehousename; } public String getCreatorname() { return this.creatorname; } public void setCreatorname(String creatorname) { this.creatorname = creatorname; } public String getMonthchecktypedesc() { return this.monthchecktypedesc; } public void setMonthchecktypedesc(String monthchecktypedesc) { this.monthchecktypedesc = monthchecktypedesc; } public boolean equals(Object other) { if ((this == other)) return true; if ((other == null)) return false; if (!(other instanceof IvMonthcheckheaderId)) return false; IvMonthcheckheaderId castOther = (IvMonthcheckheaderId) other; return ((this.getMonthchecktype() == castOther.getMonthchecktype()) || (this.getMonthchecktype() != null && castOther.getMonthchecktype() != null && this.getMonthchecktype().equals(castOther.getMonthchecktype()))) && ((this.getWarehouseid() == castOther.getWarehouseid()) || (this.getWarehouseid() != null && castOther.getWarehouseid() != null && this.getWarehouseid().equals(castOther.getWarehouseid()))) && ((this.getInvmonthcheckid() == castOther.getInvmonthcheckid()) || (this.getInvmonthcheckid() != null && castOther.getInvmonthcheckid() != null && this.getInvmonthcheckid().equals(castOther.getInvmonthcheckid()))) && ((this.getStartdate() == castOther.getStartdate()) || (this.getStartdate() != null && castOther.getStartdate() != null && this.getStartdate().equals(castOther.getStartdate()))) && ((this.getEnddate() == castOther.getEnddate()) || (this.getEnddate() != null && castOther.getEnddate() != null && this.getEnddate().equals(castOther.getEnddate()))) && ((this.getBillchecker() == castOther.getBillchecker()) || (this.getBillchecker() != null && castOther.getBillchecker() != null && this.getBillchecker().equals(castOther.getBillchecker()))) && ((this.getCreator() == castOther.getCreator()) || (this.getCreator() != null && castOther.getCreator() != null && this.getCreator().equals(castOther.getCreator()))) && ((this.getCreatetime() == castOther.getCreatetime()) || (this.getCreatetime() != null && castOther.getCreatetime() != null && this.getCreatetime().equals(castOther.getCreatetime()))) && ((this.getNotes() == castOther.getNotes()) || (this.getNotes() != null && castOther.getNotes() != null && this.getNotes().equals(castOther.getNotes()))) && ((this.getText1() == castOther.getText1()) || (this.getText1() != null && castOther.getText1() != null && this.getText1().equals(castOther.getText1()))) && ((this.getText2() == castOther.getText2()) || (this.getText2() != null && castOther.getText2() != null && this.getText2().equals(castOther.getText2()))) && ((this.getText3() == castOther.getText3()) || (this.getText3() != null && castOther.getText3() != null && this.getText3().equals(castOther.getText3()))) && ((this.getText4() == castOther.getText4()) || (this.getText4() != null && castOther.getText4() != null && this.getText4().equals(castOther.getText4()))) && ((this.getText5() == castOther.getText5()) || (this.getText5() != null && castOther.getText5() != null && this.getText5().equals(castOther.getText5()))) && ((this.getText6() == castOther.getText6()) || (this.getText6() != null && castOther.getText6() != null && this.getText6().equals(castOther.getText6()))) && ((this.getText7() == castOther.getText7()) || (this.getText7() != null && castOther.getText7() != null && this.getText7().equals(castOther.getText7()))) && ((this.getText8() == castOther.getText8()) || (this.getText8() != null && castOther.getText8() != null && this.getText8().equals(castOther.getText8()))) && ((this.getText9() == castOther.getText9()) || (this.getText9() != null && castOther.getText9() != null && this.getText9().equals(castOther.getText9()))) && ((this.getText10() == castOther.getText10()) || (this.getText10() != null && castOther.getText10() != null && this.getText10().equals(castOther.getText10()))) && ((this.getAccountantYear() == castOther.getAccountantYear()) || (this.getAccountantYear() != null && castOther.getAccountantYear() != null && this.getAccountantYear().equals(castOther.getAccountantYear()))) && ((this.getAccountantMonth() == castOther.getAccountantMonth()) || (this.getAccountantMonth() != null && castOther.getAccountantMonth() != null && this.getAccountantMonth().equals(castOther.getAccountantMonth()))) && ((this.getInvmonthcheckname() == castOther.getInvmonthcheckname()) || (this.getInvmonthcheckname() != null && castOther.getInvmonthcheckname() != null && this.getInvmonthcheckname().equals(castOther.getInvmonthcheckname()))) && ((this.getWarehousename() == castOther.getWarehousename()) || (this.getWarehousename() != null && castOther.getWarehousename() != null && this.getWarehousename().equals(castOther.getWarehousename()))) && ((this.getCreatorname() == castOther.getCreatorname()) || (this.getCreatorname() != null && castOther.getCreatorname() != null && this.getCreatorname().equals(castOther.getCreatorname()))) && ((this.getMonthchecktypedesc() == castOther.getMonthchecktypedesc()) || (this.getMonthchecktypedesc() != null && castOther.getMonthchecktypedesc() != null && this.getMonthchecktypedesc().equals(castOther.getMonthchecktypedesc()))); } public int hashCode() { int result = 17; result = 37 * result + (getMonthchecktype() == null ? 0 : this.getMonthchecktype().hashCode()); result = 37 * result + (getWarehouseid() == null ? 0 : this.getWarehouseid().hashCode()); result = 37 * result + (getInvmonthcheckid() == null ? 0 : this.getInvmonthcheckid().hashCode()); result = 37 * result + (getStartdate() == null ? 0 : this.getStartdate().hashCode()); result = 37 * result + (getEnddate() == null ? 0 : this.getEnddate().hashCode()); result = 37 * result + (getBillchecker() == null ? 0 : this.getBillchecker().hashCode()); result = 37 * result + (getCreator() == null ? 0 : this.getCreator().hashCode()); result = 37 * result + (getCreatetime() == null ? 0 : this.getCreatetime().hashCode()); result = 37 * result + (getNotes() == null ? 0 : this.getNotes().hashCode()); result = 37 * result + (getText1() == null ? 0 : this.getText1().hashCode()); result = 37 * result + (getText2() == null ? 0 : this.getText2().hashCode()); result = 37 * result + (getText3() == null ? 0 : this.getText3().hashCode()); result = 37 * result + (getText4() == null ? 0 : this.getText4().hashCode()); result = 37 * result + (getText5() == null ? 0 : this.getText5().hashCode()); result = 37 * result + (getText6() == null ? 0 : this.getText6().hashCode()); result = 37 * result + (getText7() == null ? 0 : this.getText7().hashCode()); result = 37 * result + (getText8() == null ? 0 : this.getText8().hashCode()); result = 37 * result + (getText9() == null ? 0 : this.getText9().hashCode()); result = 37 * result + (getText10() == null ? 0 : this.getText10().hashCode()); result = 37 * result + (getAccountantYear() == null ? 0 : this.getAccountantYear().hashCode()); result = 37 * result + (getAccountantMonth() == null ? 0 : this.getAccountantMonth().hashCode()); result = 37 * result + (getInvmonthcheckname() == null ? 0 : this.getInvmonthcheckname().hashCode()); result = 37 * result + (getWarehousename() == null ? 0 : this.getWarehousename().hashCode()); result = 37 * result + (getCreatorname() == null ? 0 : this.getCreatorname().hashCode()); result = 37 * result + (getMonthchecktypedesc() == null ? 0 : this.getMonthchecktypedesc().hashCode()); return result; } }
package uiLayer.uiUtilities; import java.awt.BorderLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; public class UnderConstructionCard extends JPanel { /** * Create the panel. */ public UnderConstructionCard() { setLayout(new BorderLayout(0, 0)); JLabel lblDenneFunktionalitetEr = new JLabel("Denne funktionalitet er under udvikling."); lblDenneFunktionalitetEr.setHorizontalAlignment(SwingConstants.CENTER); add(lblDenneFunktionalitetEr, BorderLayout.CENTER); } }
package com.malsolo.mercury.spring.events.repository; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Date; import java.util.List; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.malsolo.mercury.spring.events.domain.Alarm; public class AlarmRepositoryTest extends AbstractIntegrationTest { final Logger logger = LoggerFactory.getLogger(AlarmRepositoryTest.class); @Autowired private AlarmRepository alarmRepository; @Test public void testMarkerMethod() { } @Test public void testSave() { Alarm alarm = getNewTransientAlarm(); assertNull(alarm.getId()); alarmRepository.save(alarm); assertNotNull(alarm.getId()); alarmsIds.add(alarm.getId()); } @Test public void testFindById() { Alarm alarm = alarmRepository.findById(alarmsIds.get(0)); assertNotNull(alarm); logger.debug("{}", alarm); } @Test public void testFindAll() { List<Alarm> alarmas = alarmRepository.findAll(); assertNotNull(alarmas); assertTrue(alarmas.size() >= alarmsIds.size()); logger.debug("{} alarmas", alarmas.size()); } public static Alarm getNewTransientAlarm() { Alarm alarm = new Alarm(); alarm.setData("data"); alarm.setDate(new Date()); alarm.setType(null); alarm.setEvents(null); return alarm; } }
package com.example.l03.projektpaszport; import java.io.Serializable; /** * Created by Bartek on 2016-10-24. */ public class Preferencja implements Serializable{ private Integer id_preferencja; private Boolean lubie; private String zdjecie; private String opis; Preferencja( Integer id_preferencja, Boolean lubie, String zdjecie, String opis ){ this.id_preferencja = id_preferencja; this.lubie = lubie; this.zdjecie = zdjecie; this.opis = opis; } public Integer getId_preferencja() { return id_preferencja; } public void setId_preferencja(Integer id_preferencja) { this.id_preferencja = id_preferencja; } public Boolean getLubie() { return lubie; } public void setLubie(Boolean lubie) { this.lubie = lubie; } public String getZdjecie() { return zdjecie; } public void setZdjecie(String zdjecie) { this.zdjecie = zdjecie; } public String getOpis() { return opis; } public void setOpis(String opis) { this.opis = opis; } public Preferencja returnObj(){ return this; } }
package Leetcode; import java.util.LinkedList; /** * 给定链表 1->2->3->4, 重新排列为 1->4->2->3. * @author AD * */ public class ReorderList { public void reorderList(ListNode head) { if (head == null) { return; } //1、寻找中间节点 ListNode slow = head; ListNode fast = head; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } //2、反转后半部分 ListNode cur2 = reverseList(slow.next); //将原链表截断 slow.next = null; ListNode cur1 = head; //3、合并两个链表 while (cur2 != null) { ListNode next2 = cur2.next; ListNode next1 = cur1.next; cur2.next = cur1.next; cur1.next = cur2; cur2 = next2; cur1 = next1; } } public ListNode reverseList(ListNode head) { ListNode pre = null; ListNode cur = head; while(cur != null) { //每次保存cur的next节点 ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } //双端队列版 public void reorderList_2(ListNode head) { LinkedList<ListNode> queue = new LinkedList<>(); ListNode cur = head; //将链表加入队列 while (cur != null) { queue.addLast(cur); cur = cur.next; } //依次弹出 while (!queue.isEmpty()) { if (cur == null) { cur = queue.pollFirst(); } else { cur.next = queue.pollFirst(); cur = cur.next; } cur.next = queue.pollLast(); cur = cur.next; } if (cur != null) { cur.next = null; } } }
package util; import com.commercetools.pspadapter.payone.domain.ctp.CustomTypeBuilder; import com.commercetools.pspadapter.payone.domain.payone.PayonePostServiceImpl; import com.commercetools.pspadapter.payone.mapping.CustomFieldKeys; import com.commercetools.pspadapter.payone.util.PayoneHash; import com.neovisionaries.i18n.CountryCode; import io.sphere.sdk.carts.CartDraft; import io.sphere.sdk.carts.CartDraftBuilder; import io.sphere.sdk.carts.commands.CartCreateCommand; import io.sphere.sdk.carts.commands.CartUpdateCommand; import io.sphere.sdk.carts.commands.updateactions.AddPayment; import io.sphere.sdk.carts.commands.updateactions.SetBillingAddress; import io.sphere.sdk.carts.commands.updateactions.SetShippingAddress; import io.sphere.sdk.client.BlockingSphereClient; import io.sphere.sdk.client.SphereClientFactory; import io.sphere.sdk.models.Address; import io.sphere.sdk.payments.Payment; import io.sphere.sdk.payments.PaymentDraft; import io.sphere.sdk.payments.PaymentDraftBuilder; import io.sphere.sdk.payments.PaymentMethodInfoBuilder; import io.sphere.sdk.payments.TransactionDraftBuilder; import io.sphere.sdk.payments.TransactionState; import io.sphere.sdk.payments.TransactionType; import io.sphere.sdk.payments.commands.PaymentCreateCommand; import io.sphere.sdk.payments.commands.PaymentUpdateCommand; import io.sphere.sdk.payments.commands.updateactions.AddTransaction; import io.sphere.sdk.types.CustomFieldsDraft; import io.sphere.sdk.utils.MoneyImpl; import javax.annotation.Nonnull; import javax.money.Monetary; import javax.money.MonetaryAmount; import java.time.Duration; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; import static com.commercetools.util.PayoneHttpClientUtil.nameValue; import static java.lang.String.format; import static java.util.regex.Pattern.CASE_INSENSITIVE; import static java.util.regex.Pattern.DOTALL; import static util.PropertiesHelperUtil.getCardPan; import static util.PropertiesHelperUtil.getClientId; import static util.PropertiesHelperUtil.getClientSecret; import static util.PropertiesHelperUtil.getPayoneKey; import static util.PropertiesHelperUtil.getPayoneMerchantId; import static util.PropertiesHelperUtil.getPayonePortalId; import static util.PropertiesHelperUtil.getPayoneSubAccId; import static util.PropertiesHelperUtil.getProjectKey; import static util.PropertiesHelperUtil.getTenant; public class PaymentRequestHelperUtil { public static final BlockingSphereClient CTP_CLIENT = createClient(); public static final String URL_PATTERN = "http://localhost:%d"; public static final String URL_START_SESSION = format("%s/%s/commercetools/start/session/", URL_PATTERN, getTenant()); public static final String URL_HANDLE_PAYMENT = format("%s/%s/commercetools/handle/payments/", URL_PATTERN, getTenant()); protected static final Random randomSource = new Random(); private static final int CTP_REQUEST_TIMEOUT = 2; private static String pseudoCardPan = null; @Nonnull public static BlockingSphereClient createClient() { return BlockingSphereClient.of( SphereClientFactory.of().createClient(getProjectKey(), getClientId(), getClientSecret()), Duration.ofMinutes(CTP_REQUEST_TIMEOUT) ); } @Nonnull public static String createPayment( @Nonnull final String paymentMethod, @Nonnull final String centAmount, @Nonnull final String currencyCode) { final MonetaryAmount monetaryAmount = createMonetaryAmountFromCent(Long.valueOf(centAmount), currencyCode); return preparePaymentWithPreauthorizedAmountAndOrder(monetaryAmount, paymentMethod); } @Nonnull private static MonetaryAmount createMonetaryAmountFromCent(@Nonnull final Long centAmount, @Nonnull final String currencyCode) { return MoneyImpl.ofCents(centAmount, currencyCode); } @Nonnull private static String preparePaymentWithPreauthorizedAmountAndOrder(@Nonnull final MonetaryAmount monetaryAmount, @Nonnull final String paymentMethod) { final Map<String, Object> customFieldKeysMap = new HashMap<>(); customFieldKeysMap.put(CustomFieldKeys.CARD_DATA_PLACEHOLDER_FIELD, getUnconfirmedVisaPseudoCardPan()); customFieldKeysMap.put(CustomFieldKeys.LANGUAGE_CODE_FIELD, Locale.ENGLISH.getLanguage()); customFieldKeysMap.put(CustomFieldKeys.REFERENCE_FIELD, getRandomOrderNumber()); customFieldKeysMap.put(CustomFieldKeys.SUCCESS_URL_FIELD, "https://example.com/success"); customFieldKeysMap.put(CustomFieldKeys.ERROR_URL_FIELD, "https://example.com/error"); final PaymentDraft paymentDraft = PaymentDraftBuilder.of(monetaryAmount) .paymentMethodInfo(PaymentMethodInfoBuilder.of() .method(paymentMethod) .paymentInterface("PAYONE") .build()) .custom(CustomFieldsDraft.ofTypeKeyAndObjects( CustomTypeBuilder.PAYMENT_CREDIT_CARD, customFieldKeysMap)) .build(); final Payment payment = CTP_CLIENT.executeBlocking(PaymentCreateCommand.of(paymentDraft)); final CartDraft cardDraft = CartDraftBuilder.of(Monetary.getCurrency("EUR")).build(); CTP_CLIENT.executeBlocking(CartUpdateCommand.of( CTP_CLIENT.executeBlocking(CartCreateCommand.of(cardDraft)), Arrays.asList( AddPayment.of(payment), SetShippingAddress.of(Address.of(CountryCode.DE)), SetBillingAddress.of(Address.of(CountryCode.DE).withLastName("Test Buyer")) ))); CTP_CLIENT.executeBlocking(PaymentUpdateCommand.of(payment, AddTransaction.of(TransactionDraftBuilder .of(TransactionType.AUTHORIZATION, monetaryAmount, ZonedDateTime.now()) .state(TransactionState.PENDING) .build()))); return payment.getId(); } @Nonnull public static String createKlarnaPayment( @Nonnull final String paymentMethod, @Nonnull final String centAmount, @Nonnull final String currencyCode) { final MonetaryAmount monetaryAmount = createMonetaryAmountFromCent(Long.valueOf(centAmount), currencyCode); final Map<String, Object> customFieldKeysMap = new HashMap<>(); customFieldKeysMap.put(CustomFieldKeys.LANGUAGE_CODE_FIELD, Locale.ENGLISH.getLanguage()); customFieldKeysMap.put(CustomFieldKeys.REFERENCE_FIELD, getRandomOrderNumber()); customFieldKeysMap.put(CustomFieldKeys.SUCCESS_URL_FIELD, "https://example.com/success"); customFieldKeysMap.put(CustomFieldKeys.ERROR_URL_FIELD, "https://example.com/error"); final PaymentDraft paymentDraft = PaymentDraftBuilder.of(monetaryAmount) .paymentMethodInfo(PaymentMethodInfoBuilder.of() .method(paymentMethod) .paymentInterface("PAYONE") .build()) .custom(CustomFieldsDraft.ofTypeKeyAndObjects( CustomTypeBuilder.PAYMENT_INVOICE_KLARNA, customFieldKeysMap)) .build(); final Payment payment = CTP_CLIENT.executeBlocking(PaymentCreateCommand.of(paymentDraft)); final CartDraft cardDraft = CartDraftBuilder.of(Monetary.getCurrency("EUR")).build(); CTP_CLIENT.executeBlocking(CartUpdateCommand.of( CTP_CLIENT.executeBlocking(CartCreateCommand.of(cardDraft)), Arrays.asList( AddPayment.of(payment), SetShippingAddress.of(Address.of(CountryCode.DE)), SetBillingAddress.of(Address.of(CountryCode.DE).withLastName("Test Buyer")) ))); return payment.getId(); } protected static String getRandomOrderNumber() { return String.valueOf(randomSource.nextInt() + System.nanoTime()); } private static String getUnconfirmedVisaPseudoCardPan() { if (pseudoCardPan == null) { pseudoCardPan = fetchPseudoCardPan( getCardPan(), getPayoneMerchantId(), getPayoneSubAccId(), getPayonePortalId(), getPayoneKey()); } return pseudoCardPan; } /** * Request a new pseudocardpan for {@code cardPan} Visa number. * <p> * <b>Note:</b> Pseudocardpan is a unique number for every merchant ID, thus ensure you tested service and these * integration tests use the same payone merchant credentials. * Verify your {@code PAYONE_MERCHANT_ID} and {@code TEST_DATA_PAYONE_MERCHANT_ID} for both applications if * you get "pseudocardpan is not found" response from Payone. * * @param cardPan Visa card number (expected to be test Visa number from Payone) * @param mid Payone Merchant Id * @param aid Payone Sub-Account Id * @param pid Payone Portal Id * @param key Payone Key (Access Token) * @return pseudocardpan string, registered in Payone merchant center * @throws RuntimeException if the response from Payone can't be parsed */ public static String fetchPseudoCardPan(String cardPan, String mid, String aid, String pid, String key) { //curl --data "request=3dscheck&mid=$PAYONE_MERCHANT_ID&aid=$PAYONE_SUBACC_ID&portalid=$PAYONE_PORTAL_ID&key=$(md5 -qs $PAYONE_KEY)&mode=test&api_version=3.9&amount=2&currency=EUR&clearingtype=cc&exiturl=http://www.example.com&storecarddata=yes&cardexpiredate=2512&cardcvc2=123&cardtype=V&cardpan=<VISA_CREDIT_CARD_3DS_NUMBER>" String cardPanResponse = null; try { cardPanResponse = PayonePostServiceImpl.executePostRequestToString("https://api.pay1.de/post-gateway/", Arrays.asList(nameValue("request", "creditcardcheck"), nameValue("mid", mid), nameValue("aid", aid), nameValue("portalid", pid), nameValue("key", PayoneHash.calculate(key)), nameValue("mode", "test"), nameValue("api_version", "3.9"), nameValue("amount", "40"), nameValue("currency", "EUR"), nameValue("clearingtype", "cc"), nameValue("exiturl", "http://www.example.com"), nameValue("storecarddata", "yes"), nameValue("cardexpiredate", "2512"), nameValue("cardcvc2", "123"), nameValue("cardtype", "V"), nameValue("cardpan", cardPan))); } catch (Throwable e) { throw new RuntimeException("Error on pseudocardpan fetch", e); } Pattern p = Pattern.compile("^.*pseudocardpan\\s*=\\s*(\\d+).*$", CASE_INSENSITIVE | DOTALL); Matcher m = p.matcher(cardPanResponse); if (!m.matches()) { throw new RuntimeException(format("Unexpected pseudocardpan response: %s", cardPanResponse)); } return m.group(1); } }
package com.cts.projectManagement.model; import java.time.LocalDate; public class TaskDetail { private Long taskId; private Long parentId; private Long userId; private String task; private Long projectId; private int priority; private String status; private LocalDate startDate; private LocalDate endDate; private String parentTask; public String getParentTask() { return parentTask; } public void setParentTask(String parentTask) { this.parentTask = parentTask; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getTask() { return task; } public Long getTaskId() { return taskId; } public void setTaskId(Long taskId) { this.taskId = taskId; } public void setTask(String task) { this.task = task; } public Long getProjectId() { return projectId; } public void setProjectId(Long projectId) { this.projectId = projectId; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public LocalDate getStartDate() { return startDate; } public void setStartDate(LocalDate startDate) { this.startDate = startDate; } public LocalDate getEndDate() { return endDate; } public void setEndDate(LocalDate endDate) { this.endDate = endDate; } }
package services; public interface CaculationService { double calculate(double num1,double num2 ,String temp); }
import java.sql.ResultSet; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; public class StockSelector { static Integer year = null; static Date latestDBDate = null; static List<OptionData> list = new ArrayList<>(); static String replacement = null; public static void main(String[] args) throws Exception { try { CommonUtil.openDBConnection(); getDates(); year = latestDBDate.getYear() + 1900; run(latestDBDate); System.out.println("Done"); } catch (Exception e) { e.printStackTrace(); } finally { CommonUtil.closeDBConnection(); } } public static Date setTimeToMidnight(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } public static void fetchStocksAndType(String sql, Date date) throws Exception { ResultSet rs = CommonUtil.stmt.executeQuery(sql); while (rs.next()) { list.add(new OptionData(rs.getString(1), rs.getString(2))); } for (OptionData data : list) { if (data.getType().equalsIgnoreCase("PE")) { fetchPEStrikePrice(data); } else { fetchCEStrikePrice(data); } } } public static void fetchFromDB1(String sql, OptionData data) throws Exception { ResultSet rs = CommonUtil.stmt.executeQuery(sql); while (rs.next()) { data.setStrikePrice(rs.getDouble(1)); } } public static void getDates() throws Exception { String sql = "select distinct date from STable_2020 order by date desc limit 1"; ResultSet rs = CommonUtil.stmt.executeQuery(sql); rs.next(); latestDBDate = rs.getDate(1); } public static void run(Date dt) throws Exception { String date = new SimpleDateFormat("yyyy-MM-dd").format(dt); String sql = "(select a.SYMBOL,'PE' from ( " + "(select oh.SYMBOL,sum(oh.CHG_IN_OI)/sum(oh.OPEN_INT) as ch " + "from Option_History_V2_" + year + " oh " + "where oh.date = '" + date + "' and oh.OPTION_TYP = 'CE' " + "group by oh.SYMBOL having sum(oh.CHG_IN_OI) > 0 " + "order by sum(oh.CHG_IN_OI)/sum(oh.OPEN_INT) desc) a " + "inner join " + "(select oh.SYMBOL,sum(oh.CHG_IN_OI)/sum(oh.OPEN_INT) as ch " + "from Option_History_V2_" + year + " oh " + "where oh.date = '" + date + "' and oh.OPTION_TYP = 'PE' " + "group by oh.SYMBOL having sum(CHG_IN_OI) < 0 " + "order by sum(CHG_IN_OI)/sum(OPEN_INT) asc) b " + "on a.SYMBOL = b.SYMBOL) order by (a.ch + (b.ch * -1)) desc limit 10) " + "union " + "(select a.SYMBOL,'CE' from ( " + "(select oh.SYMBOL,sum(oh.CHG_IN_OI)/sum(oh.OPEN_INT) as ch " + "from Option_History_V2_" + year + " oh " + "where oh.date = '" + date + "' and oh.OPTION_TYP = 'PE' " + "group by oh.SYMBOL having sum(oh.CHG_IN_OI) > 0 " + "order by sum(oh.CHG_IN_OI)/sum(oh.OPEN_INT) desc) a " + "inner join " + "(select oh.SYMBOL,sum(oh.CHG_IN_OI)/sum(oh.OPEN_INT) as ch " + "from Option_History_V2_" + year + " oh " + "where oh.date = '" + date + "' and oh.OPTION_TYP = 'CE' " + "group by oh.SYMBOL having sum(CHG_IN_OI) < 0 " + "order by sum(CHG_IN_OI)/sum(OPEN_INT) asc) b " + "on a.SYMBOL = b.SYMBOL) order by (a.ch + (b.ch * -1)) desc limit 10)"; // System.out.println(sql); fetchStocksAndType(sql, dt); } public static void fetchPEStrikePrice(OptionData data) throws Exception { String date = new SimpleDateFormat("yyyy-MM-dd").format(latestDBDate); String sql = "select STRIKE_PR from Option_History_V2_" + year + " oh " + "where oh.SYMBOL = '" + data.getSymbol() + "' and oh.`date` = '" + date + "' " + "and oh.STRIKE_PR < (select s.`close` from STable_" + year + " s where s.name = '" + data.getSymbol() + "' and `date` = '" + date + "') " + "order by STRIKE_PR desc limit 1"; // System.out.println(sql); fetchFromDB1(sql, data); } public static void fetchCEStrikePrice(OptionData data) throws Exception { String date = new SimpleDateFormat("yyyy-MM-dd").format(latestDBDate); String sql = "select STRIKE_PR from Option_History_V2_" + year + " oh " + "where oh.SYMBOL = '" + data.getSymbol() + "' and oh.`date` = '" + date + "' " + "and oh.STRIKE_PR > (select s.`close` from STable_" + year + " s where s.name = '" + data.getSymbol() + "' and `date` = '" + date + "') " + "order by STRIKE_PR asc limit 1"; // System.out.println(sql); fetchFromDB1(sql, data); } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.cmsfacades.cmsitems.populators; import static de.hybris.platform.cmsfacades.constants.CmsfacadesConstants.*; import de.hybris.platform.cms2.cloning.service.predicate.CMSItemCloneablePredicate; import de.hybris.platform.converters.Populator; import de.hybris.platform.core.model.ItemModel; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import java.util.Map; import org.springframework.beans.factory.annotation.Required; /** * Populator that verifies that the ItemModel is cloneable and prepares the cloneable field */ public class CMSItemCloneableModelToDataAttributePopulator implements Populator<ItemModel, Map<String, Object>> { private CMSItemCloneablePredicate cmsItemCloneablePredicate; @Override public void populate(final ItemModel itemModel, final Map<String, Object> itemMap) throws ConversionException { if (getCmsItemCloneablePredicate().test(itemModel)) { itemMap.put(FIELD_CLONEABLE_NAME, true); } else { itemMap.put(FIELD_CLONEABLE_NAME, false); } } protected CMSItemCloneablePredicate getCmsItemCloneablePredicate() { return cmsItemCloneablePredicate; } @Required public void setCmsItemCloneablePredicate(final CMSItemCloneablePredicate cmsItemCloneablePredicate) { this.cmsItemCloneablePredicate = cmsItemCloneablePredicate; } }
package pl.coderslab.Controller.Solution; import pl.coderslab.Dao.ExerciseDao; import pl.coderslab.Dao.SolutionDao; import pl.coderslab.Entity.Exercise; import pl.coderslab.Entity.Solution; import pl.coderslab.Entity.User; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; @WebServlet(name = "SolutionAdd", urlPatterns = {"/solutions/add", "/solutions/add/"}) public class SolutionAdd extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(false); if (session != null) { User user = (User) session.getAttribute("session_user"); if (user == null) // cos jest nie tak { session.invalidate(); response.sendRedirect("/login"); return; } else { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String exercise_id = request.getParameter("exercise_id"); Integer intExercise_id; try { intExercise_id = Integer.parseInt(exercise_id); ExerciseDao exerciseDao = new ExerciseDao(); if (exerciseDao.getById(intExercise_id) == null) { addFailed(request, response); return; } } catch (NumberFormatException e) { addFailed(request, response); return; } Exercise exercise = new Exercise(); exercise.setId(intExercise_id); Solution solution = new Solution(); solution.setCreated(now.format(formatter)); solution.setDescription(request.getParameter("solution")); solution.setExercise(exercise); solution.setUser(user); SolutionDao solutionDao = new SolutionDao(); solutionDao.save(solution); request.setAttribute("form_info", "<p style='color: green;'>Dodano rowiązanie.</p>"); } } else { addFailed(request, response); return; } doGet(request, response); } private void addFailed(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("form_info", "<p style='color: red;'>Dodanie rozwiązania nie powiodło się.</p>"); doGet(request, response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ExerciseDao exerciseDao = new ExerciseDao(); List<Exercise> exercises = exerciseDao.findAll(); request.setAttribute("exercises", exercises); getServletContext().getRequestDispatcher("/WEB-INF/views/solution/add.jsp").forward(request, response); } }
package de.julian.main; public class HomeWork { private String task; private boolean isDone = false; public boolean isDone() { return isDone; } public void setDone(boolean done) { isDone = done; } public String getTask() { return task; } public void setTask(String task) { this.task = task; } }
package ru.otus.adapters.function; import org.junit.Assert; import org.junit.Test; import ru.otus.models.GroupEntity; import java.util.function.Function; public class CreateGroupEntityTest { @Test(expected = IndexOutOfBoundsException.class) public void exeption() { Function<String[], GroupEntity> f = new CreateGroupEntity(); f.apply(new String[]{"13", "test"}); } @Test public void apply() { GroupEntity expected = new GroupEntity(); expected.setId(13L); expected.setGroupname("test"); expected.setLogin("test"); Function<String[], GroupEntity> f = new CreateGroupEntity(); GroupEntity entity = f.apply(new String[]{"13", "test", "test"}); Assert.assertEquals(expected, entity); } }
package org.research.zookeeper; import lombok.extern.slf4j.Slf4j; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.data.ACL; import java.io.IOException; import java.util.List; @Slf4j public class ZkNodeOperator implements Watcher { public ZooKeeper zk = null; private static final Integer timeout = 5000; public ZkNodeOperator() { } public ZkNodeOperator(String connectString) { try { zk = new ZooKeeper(connectString, timeout, this); } catch (IOException e) { log.warn("e", e); if (zk != null) { try { zk.close(); } catch (InterruptedException ex) { log.warn("e", e); } } } } public String createNode(String path, byte[] data, List<ACL> aclList) { String result = ""; /** * 同步或者异步创建节点,都不支持子节点的递归创建,异步有一个callback函数 * 参数: * path:创建的路径 * data:存储的数据的byte[] * acl:控制权限策略 * Ids.OPEN_ACL_UNSAFE --> world:anyone:cdrwa * CREATOR_ALL_ACL --> auth:user:password:cdrwa * createMode:节点类型, 是一个枚举 * PERSISTENT:持久节点 * PERSISTENT_SEQUENTIAL:持久顺序节点 * EPHEMERAL:临时节点 * EPHEMERAL_SEQUENTIAL:临时顺序节点 */ //同步创建临时节点 // result = zk.create(path, data, aclList, CreateMode.EPHEMERAL); try { String ctx = "{'create':'success'}"; // 异步创建 zk.create(path, data, aclList, CreateMode.PERSISTENT, (rc, p, c, name) -> { log.warn("创建节点:{}", path); log.warn("rc:{},ctx:{},name:{}", rc, c, name); }, ctx); log.warn("create result:{}", result); //fixme 睡眠为了防止节点还没创建成功,zk客户端就断开连接 Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } return result; } /** * 修改节点数据 * * @param path * @param data * @param version */ public void setNode(String path, byte[] data, int version) {/* try { //同步修改 Stat stat = zk.setData(path, data, version); log.warn("stat:{}", stat); } catch (KeeperException | InterruptedException e) { e.printStackTrace(); }*/ //异步修改 String ctx = "{'create':'success'}"; zk.setData(path, data, version, (rc, p, c, name) -> { log.warn("创建节点:{}", p); log.warn("rc:{},ctx:{},name:{}", rc, c, name); }, ctx); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } public void deleteNode(String path, int version) { try { //同步删除 zk.delete(path, version); //异步删除 //zk.delete(path, version, (i, s, o) -> log.warn("创建节点:{},{}.{}", i,s,o), "zhangsan"); } catch (InterruptedException | KeeperException e) { e.printStackTrace(); } } @Override public void process(WatchedEvent watchedEvent) { log.warn("event:{}", watchedEvent); } }
package com.tree.heap; import java.util.Arrays; import java.util.Random; public class Max10FromFileWithBillons { public static void main(String[] args) { Max10FromFileWithBillons app = new Max10FromFileWithBillons(); int[] arr = app.readNextFromFile(1000); HeapTree tree = HeapTree.buildHeap(arr); int[] top10 = new int[10]; for (int i = 0; i < 10; i++) { top10[i] = tree.deleteMax(); } for (int i = 0; i < 10000000; i++) { top10 = app.operation(top10); } app.print(top10); } private int[] operation(int[] top10){ int[] arr = readNextFromFile(990); arr = merge(top10, arr); HeapTree tree = HeapTree.buildHeap(arr); top10 = new int[10]; for (int i = 0; i < 10; i++) { top10[i] = tree.deleteMax(); } return top10; } private int[] merge(int[] top10, int[] arr) { int[] merged = Arrays.copyOf(arr, 1000); for (int i = 0; i < top10.length; i++) { merged[990 + i] = top10[i]; } return merged; } private int[] readNextFromFile(int size){ Random random = new Random(); int[] arr = new int[size]; for (int i = 0; i < size; i++) { arr[i] = random.nextInt(); } return arr; } private void print(int[] arr) { for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); } System.out.println(); } }
package com.thewalletlist.addressbook; import android.app.Activity; import android.app.ListActivity; import android.os.Bundle; import android.widget.ListView; import android.view.View; import android.view.ViewGroup; import android.view.LayoutInflater; import android.content.Context; import android.content.res.Resources; import java.util.ArrayList; import java.util.List; import android.view.MenuItem; import android.view.MenuInflater; import android.view.Menu; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView; import android.widget.TextView; import android.widget.ImageView; import android.util.Log; public class AddressEntryAdapter extends ArrayAdapter { private int mResource; private LayoutInflater mInflater; private Context mContext; public AddressEntryAdapter (Context c, int resourceId) { super(c, resourceId); mResource = resourceId; mInflater = LayoutInflater.from(c); mContext = c; } @Override public View getView(int position, View convertView, ViewGroup parent) { /* create a new view of my layout and inflate it in the row */ convertView = (LinearLayout) mInflater.inflate(mResource, null); /* Extract the object to show */ AddressEntry ae = (AddressEntry) getItem(position); /* Take the TextView from layout and set the label */ TextView txtName = (TextView) convertView.findViewById(R.id.TextLabel); txtName.setText(ae.getLabel()); /* Take the ImageView from layout and set the image */ ImageView iView = (ImageView) convertView.findViewById(R.id.ImageCoin); Resources res = mContext.getResources(); if (ae.getKind() == AddressEntry.KIND_BITCOIN) { iView.setImageDrawable(res.getDrawable(R.drawable.bitcoin)); } else if (ae.getKind() == AddressEntry.KIND_LITECOIN) { iView.setImageDrawable(res.getDrawable(R.drawable.litecoin)); } return convertView; } }
package edu.kit.pse.osip.core.opcua.server; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.io.Files; import java.util.EnumSet; import java.util.concurrent.ExecutionException; import org.eclipse.milo.opcua.sdk.server.OpcUaServer; import org.eclipse.milo.opcua.sdk.server.api.config.OpcUaServerConfig; import org.eclipse.milo.opcua.sdk.server.identity.AnonymousIdentityValidator; import org.eclipse.milo.opcua.stack.core.Stack; import org.eclipse.milo.opcua.stack.core.UaException; import org.eclipse.milo.opcua.stack.core.application.DefaultCertificateManager; import org.eclipse.milo.opcua.stack.core.application.DefaultCertificateValidator; import org.eclipse.milo.opcua.stack.core.security.SecurityPolicy; import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue; import org.eclipse.milo.opcua.stack.core.types.builtin.DateTime; import org.eclipse.milo.opcua.stack.core.types.builtin.LocalizedText; import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId; import org.eclipse.milo.opcua.stack.core.types.structured.BuildInfo; /** * Simplifies the interface of Milo. Automatically adds a namespace and provides methods * to directly manage the namespace, because multiple namespaces are not needed in our case. * Allows to access variables based on their path instead of using the NodeId. * * @author Hans-Peter Lehmann * @version 1.0 */ public abstract class UAServerWrapper { /** * The used namespace of the OPC UA server. */ private UANamespaceWrapper namespace; /** * The actual used OPC UA server. */ private final OpcUaServer server; /** * Wraps a milo server to simplify handling. * * @param namespaceName The name of the namespace that is automatically generated. * @param port The port to listen to. */ public UAServerWrapper(String namespaceName, int port) { server = createServer(namespaceName, port); String namespaceUri = "urn:edu:kit:pse:osip:namespace:" + namespaceName; server.getNamespaceManager().registerAndAdd( namespaceUri, idx -> { namespace = new UANamespaceWrapper(server, idx); namespace.namespaceUri = namespaceUri; return namespace; }); } /** * Creates a new server that can be used to publish data over OPC UA. * * @return a server that can directly be started. * @param namespaceName The name of the default namespace. * @param port The port to listen to. */ private OpcUaServer createServer(String namespaceName, int port) { String productUri = "urn:edu:kit:pse:osip:product:" + namespaceName; OpcUaServerConfig serverConfig = OpcUaServerConfig.builder() .setApplicationUri("urn:edu:kit:pse:osip:application:" + namespaceName) .setApplicationName(LocalizedText.english("OSIP Tank server")) .setBindAddresses(Lists.newArrayList("0.0.0.0")) .setBindPort(port) .setBuildInfo( new BuildInfo( productUri, "OSIP", "OSIP server", OpcUaServer.SDK_VERSION, "1.0", DateTime.now())) .setCertificateManager(new DefaultCertificateManager()) .setCertificateValidator(new DefaultCertificateValidator(Files.createTempDir())) .setIdentityValidator(AnonymousIdentityValidator.INSTANCE) .setProductUri(productUri) .setServerName("osip") .setSecurityPolicies(EnumSet.of(SecurityPolicy.None)) .setUserTokenPolicies( ImmutableList.of( OpcUaServerConfig.USER_TOKEN_POLICY_ANONYMOUS, OpcUaServerConfig.USER_TOKEN_POLICY_USERNAME)) .build(); return new OpcUaServer(serverConfig); } /** * Starts the server. * * @throws ExecutionException If Milo has problems connecting to the remote machine. * @throws InterruptedException If Milo has problems connecting to the remote machine. */ public void start() throws InterruptedException, ExecutionException { server.startup().get(); } /** * Stops the server. Can not be restarted afterwards. * * @throws ExecutionException If Milo has problems stopping the server. * @throws InterruptedException If Milo has problems stopping the server. */ public void stop() throws InterruptedException, ExecutionException { server.shutdown().get(); } /** * Adds a folder to the default namespace. * * @param path Slash separated path of the folder. * @param displayName Name of the folder that is displayed to users. * @throws UaException If the folder can not be added. */ protected void addFolder(String path, String displayName) throws UaException { namespace.addFolder(path, displayName); } /** * Adds a variable to the default namespace. * * @param path Slash separated path of the folder. * @param displayName Name of the variable that is displayed to users. * @param type The variable type, for example Identifiers.Float. * @throws UaException If the variable can not be added. */ protected void addVariable(String path, String displayName, NodeId type) throws UaException { namespace.addVariable(path, displayName, type); } /** * Sets the value of a variable in the default namespace. * * @param path Slash separated path of the folder. * @param value Value of the variable. */ protected void setVariable(String path, DataValue value) { namespace.updateValue(path, value); } /** * Releases all resources used by milo. It is impossible to start servers afterwards. */ public static void releaseSharedResources() { Stack.releaseSharedResources(); } }
package com.t.s.model.dto; public class MoimUserDto { //테이블 명 MOIMUSER private int moimno; private String userid; private int groupno; private int moimq1; private int moimq2; private int moimq3; private int moimq4; private int moimq5; private String moimq6; public MoimUserDto() { //super(); } //파라미터 포함된 생성자는 만들어서 사용하세요 말씀해주시고요 public int getMoimno() { return moimno; } public void setMoimno(int moimno) { this.moimno = moimno; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public int getGroupno() { return groupno; } public void setGroupno(int groupno) { this.groupno = groupno; } public int getMoimq1() { return moimq1; } public void setMoimq1(int moimq1) { this.moimq1 = moimq1; } public int getMoimq2() { return moimq2; } public void setMoimq2(int moimq2) { this.moimq2 = moimq2; } public int getMoimq3() { return moimq3; } public void setMoimq3(int moimq3) { this.moimq3 = moimq3; } public int getMoimq4() { return moimq4; } public void setMoimq4(int moimq4) { this.moimq4 = moimq4; } public int getMoimq5() { return moimq5; } public void setMoimq5(int moimq5) { this.moimq5 = moimq5; } public String getMoimq6() { return moimq6; } public void setMoimq6(String moimq6) { this.moimq6 = moimq6; } }
/* * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.io.PrintWriter; import java.lang.instrument.*; import jdk.test.lib.compiler.InMemoryJavaCompiler; /* * Helper class to write tests that redefine classes. * When main method is run, it will create a redefineagent.jar that can be used * with the -javaagent option to support redefining classes in jtreg tests. * * See sample test in test/testlibrary_tests/RedefineClassTest.java */ public class RedefineClassHelper { public static Instrumentation instrumentation; public static void premain(String agentArgs, Instrumentation inst) { instrumentation = inst; } /** * Redefine a class * * @param clazz Class to redefine * @param javacode String with the new java code for the class to be redefined */ public static void redefineClass(Class clazz, String javacode) throws Exception { byte[] bytecode = InMemoryJavaCompiler.compile(clazz.getName(), javacode); redefineClass(clazz, bytecode); } /** * Redefine a class * * @param clazz Class to redefine * @param bytecode byte[] with the new class */ public static void redefineClass(Class clazz, byte[] bytecode) throws Exception { instrumentation.redefineClasses(new ClassDefinition(clazz, bytecode)); } /** * Main method to be invoked before test to create the redefineagent.jar */ public static void main(String[] args) throws Exception { ClassFileInstaller.main("RedefineClassHelper"); PrintWriter pw = new PrintWriter("MANIFEST.MF"); pw.println("Premain-Class: RedefineClassHelper"); pw.println("Can-Redefine-Classes: true"); pw.close(); sun.tools.jar.Main jarTool = new sun.tools.jar.Main(System.out, System.err, "jar"); if (!jarTool.run(new String[] { "-cmf", "MANIFEST.MF", "redefineagent.jar", "RedefineClassHelper.class" })) { throw new Exception("jar operation failed"); } } }
package headfirst.com.projectapplication; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.TaskStackBuilder; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class DisplayNotifications extends AppCompatActivity { private static final int NOTIFICATION_ID = 5453; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String notifID = getIntent().getExtras().getString("NotifID"); triggerNotification(notifID); finish(); } private void triggerNotification(final String text){ //Notification Triggering Function Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.iitlogo); Intent intent = new Intent(this, LoginActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(LoginActivity.class); // Creates a virtual stack so that when back key is pressed main activity will be displayed stackBuilder.addNextIntent(intent); PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT ); Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); CharSequence tickerText="Time To Look At The Courses"; Notification notification = new Notification.Builder(this) .setLargeIcon(bm) .setSmallIcon(R.drawable.iitlogo) // Setting Notification Icon .setContentTitle(getString(R.string.notification))// Setting Title of Notification .setAutoCancel(true)// Makes this notification automatically dismissed when the user touches it .setPriority(Notification.PRIORITY_MAX) // Setting priority to Max .setContentIntent(pendingIntent) .setTicker(text) .setContentText(text) .setLights(0xFF0000FF, 100, 3000) .setSound(soundUri) .build(); notification.defaults |= Notification.DEFAULT_VIBRATE; notification.defaults |= Notification.DEFAULT_SOUND; NotificationManager notificationManager = //Notification Manager (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, notification); // Log.d(TAG, "Notification sent successfully."); } }
package permute; import triangle.Triangle; import java.util.ArrayList; import java.util.List; /** This program tests the permutation generator. */ public class PermutationTester { public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); list.add("e"); list.add("a"); list.add("t"); PermutationGenerator<String> generator = new PermutationGenerator<String>(list); ArrayList<List<String>> permutations = generator.getPermutations(); System.out.println(permutations.get(0)); System.out.println("Expected: [e, a, t]"); System.out.println(permutations.get(1)); System.out.println("Expected: [e, t, a]"); System.out.println(permutations.get(2)); System.out.println("Expected: [a, e, t]"); System.out.println(permutations.get(3)); System.out.println(permutations.get(4)); System.out.println(permutations.get(5)); System.out.println(permutations.size()); System.out.println("Expected: 6"); ArrayList<Triangle> tList = new ArrayList<Triangle>(); tList.add(new Triangle(12)); tList.add(new Triangle(16)); tList.add(new Triangle(24)); PermutationGenerator<Triangle> tGenerator = new PermutationGenerator<Triangle>(tList); ArrayList<List<Triangle>> tPermutations = tGenerator.getPermutations(); System.out.println(tPermutations.get(0)); System.out.println(tPermutations.get(1)); System.out.println(tPermutations.get(2)); System.out.println(tPermutations.get(3)); System.out.println(tPermutations.get(4)); System.out.println(tPermutations.get(5)); } }
package com.nibado.fastcollections.matcher; import it.unimi.dsi.fastutil.ints.IntOpenHashSet; import java.util.Collection; public class MatcherNew { private final IntOpenHashSet category; private final State state; private final int group; public MatcherNew(Collection<Integer> category, State state, Integer group) { this.category = new IntOpenHashSet(category.size(), 0.25f); this.category.addAll(category); this.state = state; this.group = group; } public boolean matches(OfferNew offer) { return category.contains(offer.getCategory()) && state == offer.getState() && offer.hasGroup(group); } }
package com.itheima.core; import entity.PageResult; public interface SpecificationCheckService { PageResult search(Integer page, Integer rows); void updateStatus(Long[] ids, String status); }
package botenanna.display; import botenanna.game.Situation; import botenanna.prediction.Rigidbody; import javafx.scene.paint.Color; /** A display for the ball info. */ public class BallInfoDisplay extends InfoDisplay { private static final Color HEADER_COLOR = new Color(0.7, 0.7, 0.7, 1); public BallInfoDisplay() { super("Ball", HEADER_COLOR); } /** Update info display. A new situation must be provided. */ public void update(Situation input) { if (input == null) return; Rigidbody ball = input.getBall(); infoLabel.setText(String.format( "Pos: %s\n" + "Vel: %s\n" + "Lands: %s\n" + "LandsIn: %f sec", ball.getPosition().toStringFixedSize(), ball.getVelocity().toStringFixedSize(), input.getBallLandingPosition().toStringFixedSize(), input.getBallLandingTime())); } }
package writers; import dataStructures.BlockInfo; import dataStructures.Lexicon; import dataStructures.Posting; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import compression.Compression; /** * Class for writing data to intermediate index files. * */ public class PostingWriter { private int indexFileNumber, currentOffset; private List<Posting> postingList; private Lexicon lexicon; private OutputStream stream; private static int indexCounter = 0; public static int getIndexCounter() { return indexCounter; } private synchronized int incrIndexCounter() { indexCounter++; return indexCounter; } public PostingWriter(List<Posting> postingList, Lexicon lexicon, String path) throws FileNotFoundException { this.indexFileNumber = incrIndexCounter(); this.currentOffset = 0; this.postingList = postingList; this.lexicon = lexicon; this.stream = new FileOutputStream(new File(path,(String.valueOf(indexFileNumber)))); } public void write() { System.out.println("Writing index no. " + indexFileNumber); Collections.sort(postingList); Integer prevWordID = postingList.get(0).getWordID(); Integer prevDocID = postingList.get(0).getDocID(); List<Integer> docVector = new ArrayList<Integer>(10000); List<Integer> freqVector = new ArrayList<Integer>(10000); //List<Integer> offsetInfoStart = new LinkedList<Integer>(); //List<Integer> offsetInfoLength = new LinkedList<Integer>(); List<Integer> offsetVector = new LinkedList<Integer>(); List<String> contextVector = new LinkedList<String>(); int freqCounter = 0; //List<Integer> tempOffsetList = new ArrayList<Integer>(); int index = 0; Posting currentPosting; while (index < postingList.size()) { currentPosting = postingList.get(index); index++; if (currentPosting.getWordID() == prevWordID) { if (currentPosting.getDocID() != prevDocID) { docVector.add(prevDocID); freqVector.add(freqCounter); freqCounter = 0; prevDocID = currentPosting.getDocID(); } freqCounter++; } else { try { docVector.add(prevDocID); freqVector.add(freqCounter); freqCounter = 0; prevDocID = currentPosting.getDocID(); currentOffset = PostingWriter.writePosting(prevWordID, docVector, freqVector, stream, currentOffset, indexCounter, lexicon); prevWordID = currentPosting.getWordID(); freqCounter++; } catch (IOException e) { e.printStackTrace(); } } } try { System.out.println("Size of Lexicon(in No.of Terms) :"+ lexicon.size()); stream.close(); System.out.println("Writing " + indexCounter + " Done."); } catch (IOException e) { e.printStackTrace(); } } public static int writePosting(int wordID, List<Integer> docVector, List<Integer> freqVector, OutputStream stream, int currentOffset, Integer fileNumber, Lexicon lexicon) throws IOException { int start = currentOffset; List<Integer> tempList = new ArrayList<Integer>( (docVector.size() * 2)); for(int temp:Compression.deltaCompress(docVector)) tempList.add(temp); tempList.addAll(freqVector); byte[] bytes = Compression.encode(tempList); stream.write(bytes, 0, bytes.length); currentOffset += bytes.length; int mid = currentOffset; tempList = new ArrayList<Integer>(); int sum = 0; for(int i=0;i<freqVector.size();i++) sum+=freqVector.get(i); lexicon.put(wordID, sum, new BlockInfo( fileNumber, start, mid)); docVector.clear(); freqVector.clear(); return currentOffset; } }
package datastructures; import datastructures.concrete.DoubleLinkedList; import datastructures.interfaces.IList; import misc.BaseTest; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import static org.junit.Assert.assertTrue; /** * This file provides some helper methods for DoubleLinkedList tests. * * Changes in this file will be ignored during grading. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) // This annotation makes JUnit run tests in alphabetical order public class BaseTestDoubleLinkedList extends BaseTest { /** * This method creates a simple list containing three elements to help minimize * redundancy later in our tests. */ protected IList<String> makeBasicList() { IList<String> list = new DoubleLinkedList<>(); list.add("a"); list.add("b"); list.add("c"); return list; } /** * This function checks whether a list is a valid doubly-linked list and * contains exactly the same elements as the "expected" array. * * See the tests provided for example usage, and see the other two helper methods * for more details on how they work. * @see TestDoubleLinkedList */ protected <T> void assertListValidAndMatches(T[] expected, IList<T> actual) { assertListValid(expected, actual); assertListMatches(expected, actual); } /** * This function checks whether the node pointers inside the given list form a * valid doubly-linked list, and checks that the data in each node corresponds * to the values in the "expected" array. */ private <T> void assertListValid(T[] expected, IList<T> actual) { // Extract the front and back fields from the list Object front = getField(actual, "front"); Object back = getField(actual, "back"); // Handle edge cases: empty and single-element lists if (expected.length == 0) { assertEquals("Actual list has more elements than expected array.", null, front); assertEquals("Actual list has more elements than expected array.", null, back); return; } else if (expected.length == 1) { assertEquals("List nodes do not form a valid linked list.", null, getPrev(front)); assertEquals("List nodes do not form a valid linked list.", null, getNext(back)); assertEquals("List node contains incorrect data.", expected[0], getData(front)); assertEquals("Actual list has more elements than expected array.", front, back); return; } // Handle regular cases // Check front node (front.prev, front.next.prev, front.data) assertEquals("List nodes do not form a valid linked list.", null, getPrev(front)); assertEquals("List nodes do not form a valid linked list.", front, getPrev(getNext(front))); assertEquals("List node contains incorrect data.", expected[0], getData(front)); // Check whether middle nodes are correct int size = 1; Object curr = getNext(front); while (curr != back) { // Make sure that we haven't reached the end of the expected values yet assertTrue("Actual list has more elements than expected array.",size < expected.length); // Check that: // curr.prev.next points to curr // curr.next.prev points to curr Object prev = getPrev(curr); Object next = getNext(curr); assertEquals("List nodes do not form a valid linked list.", curr, getNext(prev)); assertEquals("List nodes do not form a valid linked list.", curr, getPrev(next)); assertEquals("List node contains incorrect data.", expected[size], getData(curr)); size++; curr = next; } // Make sure that we haven't reached the end of the expected values yet assertTrue("Actual list has more elements than expected array.", size < expected.length); // Check back node (back.next, back.prev.next, back.data) assertEquals("List nodes do not form a valid linked list.", null, getNext(curr)); assertEquals("List nodes do not form a valid linked list.", curr, getNext(getPrev(curr))); assertEquals("List node contains incorrect data.", expected[size], getData(curr)); size++; // Make sure that we've reached the end of the expected values assertEquals("Actual list has fewer elements than expected array.", expected.length, size); } /** * This function checks whether a list contains exactly the same elements as * the "expected" array using the get method. */ private <T> void assertListMatches(T[] expected, IList<T> actual) { assertEquals(expected.length, actual.size()); assertEquals(expected.length == 0, actual.isEmpty()); for (int i = 0; i < expected.length; i++) { try { assertEquals("Item at index " + i + " does not match", expected[i], actual.get(i)); } catch (Exception ex) { String errorMessage = String.format( "Got %s when getting item at index %d (expected '%s')", ex.getClass().getSimpleName(), i, expected[i]); throw new AssertionError(errorMessage, ex); } } } /** * A helper method to extract the prev field of a node. */ private Object getPrev(Object node) { if (node == null) { throw new NullPointerException(); } return getField(node, "prev"); } /** * A helper method to extract the next field of a node. */ private Object getNext(Object node) { if (node == null) { throw new NullPointerException(); } return getField(node, "next"); } /** * A helper method to extract the data field of a node. */ private Object getData(Object node) { if (node == null) { throw new NullPointerException(); } return getField(node, "data"); } }
package com.packtpub.javaee8.validation; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.validation.Valid; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; import javax.ws.rs.*; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.Optional; @ApplicationScoped @Path("/validation/books") @Produces(MediaType.APPLICATION_JSON) public class BooksResource { private Map<String, Book> books = new HashMap<>(); @PostConstruct public void initialize() { books.put("0345391802", new Book("0345391802", "The Hitchhiker's Guide to the Galaxy")); } @GET public Response books() { return Response.ok(books.values()).build(); } @GET @Path("/{isbn}") public Response book(@PathParam("isbn") @Pattern(regexp = "[0-9]{10}") String isbn) { Book book = Optional.ofNullable(books.get(isbn)).orElseThrow(NotFoundException::new); return Response.ok(book).build(); } @POST @Consumes(MediaType.APPLICATION_JSON) public Response create(@Valid Book book, @Context UriInfo uriInfo) { books.put(book.isbn, book); URI uri = uriInfo.getBaseUriBuilder().path(BooksResource.class).path(book.isbn).build(); return Response.created(uri).build(); } public static class Book { @Pattern(regexp = "[0-9]{10}") private String isbn; @NotBlank private String title; public Book() { } Book(String isbn, String title) { this.isbn = isbn; this.title = title; } public String getIsbn() { return isbn; } public String getTitle() { return title; } public void setIsbn(String isbn) { this.isbn = isbn; } public void setTitle(String title) { this.title = title; } } }
public class Overriding { //this happens when the object B show() overrides the object A show() public static void main(String[] args) { B obj = new B(); obj.show(); } }
package com.example.android.stablefordscores; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { int scoreGolferA = 0; int scoreGolferB = 0; int scoreGolferBonusA = 0; int scoreGolferBonusB = 0; int scoreGolferFinalA = 0; int scoreGolferFinalB = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** * Increase the Bonus score for Team A by 1 point. * Increase the Final score for Team A by 1 point. */ public void addOneForBonusA(View v) { scoreGolferBonusA = scoreGolferBonusA + 1; displayForGolferBonusA(scoreGolferBonusA); scoreGolferFinalA = scoreGolferA + scoreGolferBonusA; displayForGolferFinalA(scoreGolferFinalA); } /** * Increase the score for Team A by 1 point. * Increase the Final score for Team A by 1 point. */ public void addOneForTeamA(View v) { scoreGolferA = scoreGolferA + 1; displayForGolferA(scoreGolferA); scoreGolferFinalA = scoreGolferA + scoreGolferBonusA; displayForGolferFinalA(scoreGolferFinalA); } /** * Increase the score for Team A by 2 points. * Increase the Final score for Team A by 2 points. */ public void addTwoForTeamA(View v) { scoreGolferA = scoreGolferA + 2; displayForGolferA(scoreGolferA); scoreGolferFinalA = scoreGolferA + scoreGolferBonusA; displayForGolferFinalA(scoreGolferFinalA); } /** * Increase the score for Team A by 3 points. * Increase the Final score for Team A by 3 points. */ public void addThreeForTeamA(View v) { scoreGolferA = scoreGolferA + 3; displayForGolferA(scoreGolferA); scoreGolferFinalA = scoreGolferA + scoreGolferBonusA; displayForGolferFinalA(scoreGolferFinalA); } /** * Increase the score for Team A by 4 points. * Increase the Final score for Team A by 4 points. */ public void addFourForTeamA(View v) { scoreGolferA = scoreGolferA + 4; displayForGolferA(scoreGolferA); scoreGolferFinalA = scoreGolferA + scoreGolferBonusA; displayForGolferFinalA(scoreGolferFinalA); } /** * Increase the score for Team A by 5 points. * Increase the Final score for Team A by 5 points. */ public void addFiveForTeamA(View v) { scoreGolferA = scoreGolferA + 5; displayForGolferA(scoreGolferA); scoreGolferFinalA = scoreGolferA + scoreGolferBonusA; displayForGolferFinalA(scoreGolferFinalA); } /** * Increase the Bonus score for Team B by 1 point. * Increase the Final score for Team B by 1 point. */ public void addOneForBonusB(View v) { scoreGolferBonusB = scoreGolferBonusB + 1; displayForGolferBonusB(scoreGolferBonusB); scoreGolferFinalB = scoreGolferB + scoreGolferBonusB; displayForGolferFinalB(scoreGolferFinalB); } /** * Increase the score for Team B by 1 point. * * Increase the Final score for Team B by 1 point. */ public void addOneForTeamB(View v) { scoreGolferB = scoreGolferB + 1; displayForGolferB(scoreGolferB); scoreGolferFinalB = scoreGolferB + scoreGolferBonusB; displayForGolferFinalB(scoreGolferFinalB); } /** * Increase the score for Team B by 2 points. * * Increase the Final score for Team B by 2 point. */ public void addTwoForTeamB(View v) { scoreGolferB = scoreGolferB + 2; displayForGolferB(scoreGolferB); scoreGolferFinalB = scoreGolferB + scoreGolferBonusB; displayForGolferFinalB(scoreGolferFinalB); } /** * Increase the score for Team B by 3 points. * * Increase the Final score for Team B by 3 point. */ public void addThreeForTeamB(View v) { scoreGolferB = scoreGolferB + 3; displayForGolferB(scoreGolferB); scoreGolferFinalB = scoreGolferB + scoreGolferBonusB; displayForGolferFinalB(scoreGolferFinalB); } /** * Increase the score for Team B by 4 points. * * Increase the Final score for Team B by 4 point. */ public void addFourForTeamB(View v) { scoreGolferB = scoreGolferB + 4; displayForGolferB(scoreGolferB); scoreGolferFinalB = scoreGolferB + scoreGolferBonusB; displayForGolferFinalB(scoreGolferFinalB); } /** * Increase the score for Team B by 5 points. * * Increase the Final score for Team B by 5 point. */ public void addFiveForTeamB(View v) { scoreGolferB = scoreGolferB + 5; displayForGolferB(scoreGolferB); scoreGolferFinalB = scoreGolferB + scoreGolferBonusB; displayForGolferFinalB(scoreGolferFinalB); } /** * Reset all the score for Team A and B. */ public void setToZero(View v) { scoreGolferA = 0; scoreGolferB = 0; scoreGolferBonusA = 0; scoreGolferBonusB = 0; displayForGolferA(scoreGolferA); displayForGolferB(scoreGolferB); displayForGolferBonusA(scoreGolferBonusA); displayForGolferBonusB(scoreGolferBonusB); } /** * Displays the given score for Team A Bonus. */ public void displayForGolferBonusA(int score) { TextView scoreView = (TextView) findViewById(R.id.golfer_a_score_bonus); scoreView.setText(String.valueOf(score)); } /** * Displays the given score for Team B Bonus. */ public void displayForGolferBonusB(int score) { TextView scoreView = (TextView) findViewById(R.id.golfer_b_score_bonus); scoreView.setText(String.valueOf(score)); } /** * Displays the given score for Team A. */ public void displayForGolferA(int score) { TextView scoreView = (TextView) findViewById(R.id.golfer_a_score); scoreView.setText(String.valueOf(score)); } /** * Displays the given score for Team B. */ public void displayForGolferB(int score) { TextView scoreView = (TextView) findViewById(R.id.golfer_b_score); scoreView.setText(String.valueOf(score)); } /** * Displays the given Final score for Team A. */ public void displayForGolferFinalA(int score) { TextView scoreView = (TextView) findViewById(R.id.golfer_a_score_final); scoreView.setText(String.valueOf(score)); } /** * Displays the given Final score for Team A. */ public void displayForGolferFinalB(int score) { TextView scoreView = (TextView) findViewById(R.id.golfer_b_score_final); scoreView.setText(String.valueOf(score)); } }
package com.gxuwz.attend.entity; /** * Sheet entity. @author MyEclipse Persistence Tools */ public class Sheet implements java.io.Serializable { // Fields private Integer id; private String teacherId; private String courseId; private String studentId; //add private Student student; // Constructors /** default constructor */ public Sheet() { } /** minimal constructor */ public Sheet(Integer id) { this.id = id; } /** full constructor */ public Sheet(Integer id, String teacherId, String courseId, String studentId) { this.id = id; this.teacherId = teacherId; this.courseId = courseId; this.studentId = studentId; } // Property accessors public Integer getId() { return this.id; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public void setId(Integer id) { this.id = id; } public String getTeacherId() { return this.teacherId; } public void setTeacherId(String teacherId) { this.teacherId = teacherId; } public String getCourseId() { return this.courseId; } public void setCourseId(String courseId) { this.courseId = courseId; } public String getStudentId() { return this.studentId; } public void setStudentId(String studentId) { this.studentId = studentId; } }
package com.example.michael.animaxlist; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.Objects; /** * Created by Michael on 2015/9/22. */ public class LineAdapter extends BaseAdapter { private LayoutInflater mInflater; String[] title,subtitle; int[] epso; int[] max_epso; public LineAdapter(Context context,String[] title,String[] subtitle,int[] epso,int[] max_epso){ mInflater=LayoutInflater.from(context); this.title=title; this.subtitle=subtitle; this.epso=epso; this.max_epso=max_epso; } @Override public int getCount(){ return title.length; } @Override public String getItem(int position){ return title[position]; } @Override public long getItemId(int arg0){ return arg0; } @Override public View getView(int position,View view,ViewGroup viewgrop){ view=mInflater.inflate(R.layout.line_set,null); TextView title=(TextView)view.findViewById(R.id.line_title); TextView subtitle=(TextView)view.findViewById(R.id.line_subtitle); TextView epso=(TextView)view.findViewById(R.id.line_epso); title.setText(this.title[position]); subtitle.setText(this.subtitle[position]); if (this.max_epso[position]==0) { epso.setText("" + this.epso[position]); }else{ epso.setText(this.epso[position]+"/"+this.max_epso[position]); } return view; } }
package com.cakcaraka.android.sqlitemanager.demo; import android.database.sqlite.SQLiteOpenHelper; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.cakcaraka.android.sqlitemanager.SQLiteManagerActivity; public class SQLiteActivity extends SQLiteManagerActivity { @Override protected SQLiteOpenHelper getSQLiteHelper() { return new DBManager(this); } }
/* * Copyright (C) 2015 Miquel Sas * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package com.qtplaf.library.trading.data.info; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.qtplaf.library.app.Session; import com.qtplaf.library.trading.data.Data; import com.qtplaf.library.trading.data.Instrument; import com.qtplaf.library.trading.data.Period; import com.qtplaf.library.util.FormatUtils; import com.qtplaf.library.util.StringUtils; /** * Base information that describes data in a data list. * * @author Miquel Sas */ public class DataInfo { /** Name. */ private String name; /** A title to use in list or tool tips. */ private String title; /** An optional long description that completely describes the data. */ private String description; /** Instrument of data if applicable. */ private Instrument instrument; /** Period. */ private Period period; /** The pip scale used for the data in this data list. If -1, take it from the instrument. */ private int pipScale = -1; /** The tick scale used for the data in this data list. If -1, take it from the instrument. */ private int tickScale = -1; /** The list of informations about outputs. */ private List<OutputInfo> outputs = new ArrayList<>(); /** Map of output indexes. */ private Map<String, Integer> mapIndexes = new HashMap<>(); /** The working session. */ private Session session; /** * Constructor. * * @param session The working session. */ public DataInfo(Session session) { super(); this.session = session; } /** * Check whether this data info is equal to the argument object. * * @return A boolean. */ @Override public boolean equals(Object obj) { if (obj instanceof DataInfo) { DataInfo info = (DataInfo) obj; if (!getName().equals(info.getName())) { return false; } if (!getInstrument().equals(info.getInstrument())) { return false; } if (!getPeriod().equals(info.getPeriod())) { return false; } if (getPipScale() != info.getPipScale()) { return false; } if (getTickScale() != info.getTickScale()) { return false; } int count = getOutputCount(); if (count != info.getOutputCount()) { return false; } for (int i = 0; i < count; i++) { if (!getOutput(i).equals(info.getOutput(i))) { return false; } } return true; } return false; } /** * Returns the working session. * * @return The working session. */ public Session getSession() { return session; } /** * Adds an output data information to the list of outputs. * * @param name The output name. * @param shortName The output short name. * @param index The index in the data. */ public void addOutput(String name, String shortName, int index) { addOutput(new OutputInfo(name, shortName, index)); } /** * Add the output and map the index to the name. * * @param output The output. */ private void addOutput(OutputInfo output) { outputs.add(output); mapIndexes.put(output.getName(), output.getIndex()); } /** * Returns the output index given the name of the output. * * @param name The name of the output. * @return The output index or -1 if the name is not valid. */ public int getOutputIndex(String name) { Integer index = mapIndexes.get(name); if (index == null) { return -1; } return index.intValue(); } /** * Returns the output info by data index or null if not found. * * @param index The data index. * @return Teh output info. */ public OutputInfo getOutputByDataIndex(int index) { for (OutputInfo output : outputs) { if (output.getIndex() == index) { return output; } } return null; } /** * Adds an output to the list of outputs. * * @param name The output name. * @param shortName The output short name. * @param index The index in the data. * @param description The output description. */ public void addOutput(String name, String shortName, int index, String description) { outputs.add(new OutputInfo(name, shortName, index, description)); } /** * Returns the number of outputs. * * @return The number of outputs. */ public int getOutputCount() { return outputs.size(); } /** * Returns the output at the given index. * * @param index The output index. * @return The output. */ public OutputInfo getOutput(int index) { if (index < outputs.size()) { return outputs.get(index); } return null; } /** * Returns the data instrument. * * @return The data instrument. */ public Instrument getInstrument() { return instrument; } /** * Sets the data instrument. * * @param instrument The data instrument. */ public void setInstrument(Instrument instrument) { this.instrument = instrument; } /** * Returns the data period. * * @return The data period. */ public Period getPeriod() { return period; } /** * Sets the data period. * * @param period The data period. */ public void setPeriod(Period period) { this.period = period; } /** * Returns the identifier or name. * * @return The unique identifier or name, like for instance <b>SMA</b>. */ public String getName() { return name; } /** * Sets the unique identifier or name, like for instance <b>SMA</b>. * * @param id The unique identifier or name, like for instance <b>SMA</b>. */ public void setName(String id) { this.name = id; } /** * Returns the title to use in list or tool tips. * * @return The title to use in list or tool tips. */ public String getTitle() { return title; } /** * Sets the title to use in list or tool tips. * * @param title The title to use in list or tool tips. */ public void setTitle(String title) { this.title = title; } /** * Returns the long description. * * @return The long description. */ public String getDescription() { return description; } /** * Sets the long description. * * @param description The long description. */ public void setDescription(String description) { this.description = description; } /** * Returns the pip scale to use. * * @return The pip scale. * @throws UnsupportedOperationException If the pip scale can not be resolved. */ public int getPipScale() { if (pipScale >= 0) { return pipScale; } if (instrument != null) { return instrument.getPipScale(); } throw new UnsupportedOperationException("Pip scale can not be resolved"); } /** * Sets the pip scale for the data in this data list. If -1, retrieve it from the instrument. * * @param pipScale The pip scale. */ public void setPipScale(int pipScale) { this.pipScale = pipScale; } /** * Returns the tick scale to use. * * @return The tick scale. * @throws UnsupportedOperationException If the tick scale can not be resolved. */ public int getTickScale() { if (tickScale >= 0) { return tickScale; } if (instrument != null) { return instrument.getTickScale(); } throw new UnsupportedOperationException("Tick scale can not be resolved"); } /** * Returns the volume scale or -1 if it can not be resolved. * * @return The volume scale. */ public int getVolumeScale() { if (instrument != null) { return instrument.getVolumeScale(); } return -1; } /** * Sets the tick or minimum value scale. * * @param tickScale The tick or minimum value scale. */ public void setTickScale(int tickScale) { this.tickScale = tickScale; } /** * Returns a display information of the given data. * * @param data The data. * @return The display info. */ public String getInfoData(Data data) { boolean priceInfo = (this instanceof PriceInfo); boolean addVolumeValue = (priceInfo && Data.getVolume(data) != 0); StringBuilder b = new StringBuilder(); int count = getOutputCount(); for (int i = 0; i < count; i++) { OutputInfo output = getOutput(i); int index = output.getIndex(); boolean addValue = true; if (index == Data.VOLUME) { addValue = addVolumeValue; } if (addValue) { if (i > 0) { b.append(", "); } String shortName = output.getShortName(); if (shortName != null) { b.append(shortName); b.append(": "); } b.append( FormatUtils.formattedFromDouble(data.getValue(index), getTickScale(), getSession().getLocale())); } } return b.toString(); } /** * Returns a string representation of this data info. * * @return A string representation. */ @Override public String toString() { StringBuilder info = new StringBuilder(); StringUtils.append(info, getInstrument()); StringUtils.appendSep(info, getPeriod(), ", "); StringUtils.appendSep(info, getName(), ", "); return info.toString(); } }
/* * 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 TabularFunctions; import org.w3c.dom.Element; /** * * @author Will_and_Sara */ public interface IWriteToXML { abstract public void ReadFromXMLElement(Element ele); abstract public Element WriteToXMLElement(); }
package tp.tbert12.cola; import org.junit.Test; import static org.junit.Assert.assertEquals; public class NodeTest { @Test(expected = AssertionError.class) public void crearNodoNulo() { NullNode elNodo = new NullNode(); elNodo.getContent(); elNodo.getNextNode().getContent(); } @Test public void pruebaAppendearAlNodoOtroNodo() { Node<Integer> elNodo = new Node<>(3); elNodo.appendNext(new Node<>(4)); Node siguienteNodo = (Node)elNodo.getNextNode(); assertEquals((int)siguienteNodo.getContent(),4); } @Test public void pruebaAppendearProfundamenteHastaElUltimo() { Node<Integer> elNodo = new Node<>(3); elNodo.appendNext(new Node<>(4)); elNodo.appendNext(new Node<>(5)); Node siguiente = (Node)elNodo.getNextNode(); assertEquals((int)siguiente.getContent(),4); Node siguienteDelSiguiente = (Node)siguiente.getNextNode(); assertEquals((int)siguienteDelSiguiente.getContent(),5); } @Test public void pruebaDeTamanoAppendearProfundamenteHastaElUltimo() { Node<Integer> elNodo = new Node<>(0); for (int i = 1; i < 40; i++) { elNodo.appendNext(new Node<>(i) ); } assertEquals((int)elNodo.getContent(),0); InterfaceNode nodoSiguiente = elNodo.getNextNode(); for (int i = 1; i < 40; i++) { assertEquals((int)nodoSiguiente.getContent(),i); nodoSiguiente = nodoSiguiente.getNextNode(); } } @Test public void pruebaContarSiguientes() { Node<Integer> elNodo = new Node<>(0); for (int i = 1; i < 40; i++) { elNodo.appendNext(new Node<>(i)); } assertEquals(elNodo.countNexts(),40); } }
package com.mmall.concurrency.example.singleton; import com.mmall.concurrency.annotation.NotThreadSafe; /** * @Auther: Mr.Dong * @Date: 2019/3/1 09:59 * @Description: 懒汉模式 -> 双重同步锁单例模式 */ @NotThreadSafe public class SingletonExample4 { private static SingletonExample4 instance = null; private SingletonExample4() { } // instance = new SingletonExample4(); 实例化步骤 // 1、分配对象内存空间 // 2、初始化对象 // 3、设置instance指向刚分配的内存 // JVM和CPU优化,发生了指令重排 // 1、分配对象内存空间 // 3、设置instance指向刚分配的内存 // 2、初始化对象 // 静态的工厂方法 public static SingletonExample4 getInstance() { if (instance == null) { // 双重检测机制 synchronized (SingletonExample4.class) { // 同步锁 if (instance == null) { instance = new SingletonExample4(); } } } return instance; } }
import java.util.Scanner; class CzyNalezy { public static void main(String[] args){ Scanner s = new Scanner(System.in); System.out.println("Podaj współrzędne punktu P: xp oraz yp"); double xp = s.nextDouble(); double yp = s.nextDouble(); Punkt p = new Punkt(xp, yp); Punkt p1 = new Punkt(1, 1); Kolo k1 = new Kolo(p1, 1); Punkt p2 = new Punkt(-1, 1); Kolo k2 = new Kolo(p2, 1); Punkt p3 = new Punkt(-1, -1); Kolo k3 = new Kolo(p3, 1); Punkt p4 = new Punkt(1, -1); Kolo k4 = new Kolo(p4, 1); if(k1.Nalezy(p)){ System.out.println("Punkt P należy do koła żółtego K1"); } else if(k2.Nalezy(p)){ System.out.println("Punkt P należy do koła pomarańczowego K2"); } else if(k3.Nalezy(p)){ System.out.println("Punkt P należy do koła czerwonego K3"); } else if(k4.Nalezy(p)){ System.out.println("Punkt P należy do koła brązowego K4"); } else { System.out.println("Punkt P nie należy do żadnych z kół"); } s.close(); } }
package com.thoughtpropulsion.fj; @FunctionalInterface public interface F0<A> { A apply(); static <A> F0<A> constantly(final A x) { return () -> x; } }
package com.kush.lib.expressions.types.factory; import static com.kush.lib.expressions.types.factory.TypedValueFactory.value; import com.kush.commons.markers.ImpactedByAutoBoxing; import com.kush.lib.expressions.types.TypedValue; import com.kush.lib.expressions.types.handlers.TypeHandler; @SuppressWarnings("boxing") @ImpactedByAutoBoxing class NonNullTypedValueGenerator extends TypeHandler<TypedValue> { private final Object value; public NonNullTypedValueGenerator(Object value) { this.value = value; } @Override protected TypedValue handleBoolean() { return value((Boolean) value); } @Override protected TypedValue handleByte() { return value((Byte) value); } @Override protected TypedValue handleShort() { return value((Short) value); } @Override protected TypedValue handleChar() { return value((Character) value); } @Override protected TypedValue handleInt() { return value((Integer) value); } @Override protected TypedValue handleLong() { return value((Long) value); } @Override protected TypedValue handleFloat() { return value((Float) value); } @Override protected TypedValue handleDouble() { return value((Double) value); } @Override protected TypedValue handleString() { return value((String) value); } @Override protected TypedValue handleObject() { throw new UnsupportedOperationException(); } }
package com.cg.empapp.service; import java.util.HashMap; import com.cg.empapp.dao.EmployeeDaoImpl; import com.cg.empapp.dto.Employee; import com.cg.empapp.exception.EmployeeException; public class EmployeeServiceImpl implements EmployeeService { EmployeeDaoImpl ed; Employee emp; public EmployeeServiceImpl() { ed = new EmployeeDaoImpl(); emp = new Employee(); } @Override public void insertEmployee(Employee emp) { // TODO Auto-generated method stub ed.insertEmployee(emp); } @Override public HashMap<Integer, Employee> getAllEmployees() throws EmployeeException { HashMap<Integer, Employee> map=ed.getAllEmployees(); return map; } @Override public Employee getEmployeeById(int id) throws EmployeeException { emp= ed.getEmployeeById(id); return emp; } }
/* Violet - A program for editing UML diagrams. Copyright (C) 2007 Cay S. Horstmann (http://horstmann.com) Alexandre de Pellegrin (http://alexdp.free.fr); 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 com.horstmann.violet.framework.userpreferences; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.URL; import javax.jnlp.BasicService; import javax.jnlp.FileContents; import javax.jnlp.PersistenceService; import javax.jnlp.ServiceManager; import javax.jnlp.UnavailableServiceException; import com.horstmann.violet.framework.injection.bean.ManiocFramework.ManagedBean; /** * A preferences service that uses WebStart "muffins". */ @ManagedBean(registeredManually=true) public class JNLPUserPreferencesDao implements IUserPreferencesDao { public String get(PreferencesConstant key, String defval) { try { BasicService basic = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService"); URL codeBase = basic.getCodeBase(); PersistenceService service = (PersistenceService) ServiceManager.lookup("javax.jnlp.PersistenceService"); URL keyURL = new URL(codeBase, key.toString()); FileContents contents = service.get(keyURL); InputStream in = contents.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8")); String r = reader.readLine(); if (r != null) return r; } catch (UnavailableServiceException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return defval; } public void put(PreferencesConstant key, String value) { try { BasicService basic = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService"); URL codeBase = basic.getCodeBase(); PersistenceService service = (PersistenceService) ServiceManager.lookup("javax.jnlp.PersistenceService"); URL keyURL = new URL(codeBase, key.toString()); try { service.delete(keyURL); } catch (Exception ex) { } byte[] bytes = value.getBytes("UTF-8"); service.create(keyURL, bytes.length); FileContents contents = service.get(keyURL); OutputStream out = contents.getOutputStream(true); out.write(bytes); out.close(); } catch (UnavailableServiceException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void reset() { try { BasicService basic = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService"); URL codeBase = basic.getCodeBase(); PersistenceService service = (PersistenceService) ServiceManager.lookup("javax.jnlp.PersistenceService"); for (int i = 0; i < PreferencesConstant.LIST.length; i++) { URL keyURL = new URL(codeBase, PreferencesConstant.LIST[i].toString()); try { service.delete(keyURL); } catch (Exception ex) { } } } catch (UnavailableServiceException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } } }
package com.aiyamamoto.transforemerapp.network; import com.aiyamamoto.transforemerapp.model.TransformersList; import com.aiyamamoto.transforemerapp.network.body.CreateTransformerBody; import com.aiyamamoto.transforemerapp.network.response.TransformerResponse; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Path; /** * Created by aiyamamoto on 2018-09-13. */ public interface TransformerApi { @GET("allspark") Call<String> getAllsparkToken(@Header("accept") String accept); @POST("transformers") Call<TransformerResponse> createTransformer(@Header("Authorization")String authorization, @Body CreateTransformerBody body); @PUT("transformers") Call<TransformerResponse> editTransformer(@Header("Authorization")String authorization, @Body CreateTransformerBody body); @GET("transformers") Call<TransformersList> getTransformersList(@Header("Authorization")String authorization); @DELETE("transformers/{transformerId}") Call<Void> deleteTransformer(@Header("Authorization")String authorization, @Path("transformerId") String transformerId); }
package test; /** * 测试是否有指令重排序 * @author gq * @time 2017年6月16日 */ public class ReorderTest { private static int number=1000; public static void main(String[] args) { Thread[] ts=new Thread[number]; for (int i = 0; i < number; i++) { ts[i]=new Thread(){ @Override public void run() { print(); } }; ts[i].start(); } } static void print(){ String name=Thread.currentThread().getName(); synchronized (name) { System.out.println("线程"+name+"说:我是A"); } System.out.println("线程"+name+"说:我是B"); // System.out.println("线程"+name+"说:我是C"); // System.out.println("线程"+name+"说:我是D"); // System.out.println("线程"+name+"说:我是E"); } }
package com.pfchoice.springboot.service; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import com.pfchoice.springboot.model.PlaceOfService; public interface PlaceOfServiceService { PlaceOfService findById(Integer id); PlaceOfService findByDescription(String description); PlaceOfService findByCode(String code); void savePlaceOfService(PlaceOfService placeOfService); void updatePlaceOfService(PlaceOfService placeOfService); void deletePlaceOfServiceById(Integer id); void deleteAllPlaceOfServices(); Page<PlaceOfService> findAllPlaceOfServicesByPage(Specification<PlaceOfService> spec, Pageable pageable); boolean isPlaceOfServiceExist(PlaceOfService placeOfService); }
package com.mideas.rpg.v2.game.mail; import java.util.ArrayList; import java.util.HashSet; import com.mideas.rpg.v2.callback.CallbackMgr; public class MailMgr { private final static ArrayList<Mail> mailList = new ArrayList<Mail>(); private final static HashSet<Long> loadedMail = new HashSet<Long>(); public final static int SUBJECT_MAX_LENGTH = 55; public final static int UPDATE_EXPIRE_TIMER_FREQUENCE = 60000; public static void addMail(Mail mail) { mailList.add(0, mail); } public static void clearMailList() { mailList.clear(); } public static boolean wasLoadRequested(long GUID) { return (loadedMail.contains(GUID)); } public static void addLoadedMail(long GUID) { loadedMail.add(GUID); } public static void clearLoadedMail() { loadedMail.clear(); } public static Mail getMail(long GUID) { int i = -1; while (++i < mailList.size()) if (mailList.get(i).getGUID() == GUID) return (mailList.get(i)); return (null); } public static void removeMail(long GUID) { int i = -1; while (++i < mailList.size()) if (mailList.get(i).getGUID() == GUID) { CallbackMgr.onMailDeleted(mailList.get(i)); mailList.remove(i); return; } } public static void mailOpened(long GUID) { int i = -1; while (++i < mailList.size()) if (mailList.get(i).getGUID() == GUID) { mailList.get(i).readed(); return; } } public static void updateMailExpireDateTimer() { int i = -1; while (++i < mailList.size()) mailList.get(i).updateExpireDateString(); } public static ArrayList<Mail> getMailList() { return (mailList); } }
package com.checkroom.plugin.crashlytics; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.crashlytics.android.Crashlytics; import android.util.Log; public class CrashlyticsPlugin extends CordovaPlugin { private final String pluginName = "CrashlyticsPlugin"; @Override public boolean execute(final String action, final JSONArray data, final CallbackContext callbackContext) { Log.d(pluginName, pluginName + " called with options: " + data); if (action.equals("sendCrash")) { sendCrash(data, callbackContext); } else if (action.equals("addLog")) { addLog(data, callbackContext); } else if (action.equals("setUserIdentifier")) { setUserIdentifier(data, callbackContext); } else if (action.equals("setUserName")) { setUserName(data, callbackContext); } else if (action.equals("setUserEmail")) { setUserEmail(data, callbackContext); } else if (action.equals("setStringValueForKey")) { setStringValueForKey(data, callbackContext); } else if (action.equals("setIntValueForKey")) { setIntValueForKey(data, callbackContext); } else if (action.equals("setBoolValueForKey")) { setBoolValueForKey(data, callbackContext); } else if (action.equals("setFloatValueForKey")) { setFloatValueForKey(data, callbackContext); } return true; } private void sendCrash(final JSONArray data, final CallbackContext callbackContext) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { throw new RuntimeException("This is a crash"); } }); } private void sendNonFatalCrash(final JSONArray data, final CallbackContext callbackContext) { this.cordova.getActivity().runOnUiThread(new Runnable() { @Override public void run() { Crashlytics.logException(new Throwable( "Sending non fatal crash from JS")); } }); } private void addLog(final JSONArray data, final CallbackContext callbackContext) { try { JSONObject obj = data.getJSONObject(0); String message; if (obj.has("message")) { message = obj.getString("message"); Crashlytics.log(message); } } catch (JSONException e) { e.printStackTrace(); } } private void setUserIdentifier(final JSONArray data, final CallbackContext callbackContext) { String identifier = getValueFromData(data); if (identifier != null) { Crashlytics.setUserIdentifier(identifier); } } private void setUserName(final JSONArray data, final CallbackContext callbackContext) { String userName = getValueFromData(data); if (userName != null) { Crashlytics.setUserName(userName); } } private void setUserEmail(final JSONArray data, final CallbackContext callbackContext) { String email = getValueFromData(data); if (email != null) { Crashlytics.setUserEmail(email); } } private void setStringValueForKey(final JSONArray data, final CallbackContext callbackContext) { String value = getValueFromData(data); String key = getKeyFromData(data); if (value != null && key != null) { Crashlytics.setString(key, value); } } private void setIntValueForKey(final JSONArray data, final CallbackContext callbackContext) { int value = -1; try { JSONObject obj = data.getJSONObject(0); if (obj.has("value")) { value = obj.getInt("value"); } } catch (JSONException e) { e.printStackTrace(); } String key = getKeyFromData(data); if (value != -1 && key != null) { Crashlytics.setInt(key, value); } } private void setBoolValueForKey(final JSONArray data, final CallbackContext callbackContext) { boolean value = true; try { JSONObject obj = data.getJSONObject(0); if (obj.has("value")) { value = obj.getBoolean("value"); } } catch (JSONException e) { e.printStackTrace(); } String key = getKeyFromData(data); if (key != null) { Crashlytics.setBool(key, value); } } private void setFloatValueForKey(final JSONArray data, final CallbackContext callbackContext) { float value = -1; try { JSONObject obj = data.getJSONObject(0); if (obj.has("value")) { value = obj.getLong("value"); } } catch (JSONException e) { e.printStackTrace(); } String key = getKeyFromData(data); if (value != -1 && key != null) { Crashlytics.setFloat(key, value); } } private String getValueFromData(JSONArray data) { try { JSONObject obj = data.getJSONObject(0); if (obj.has("value")) { return obj.getString("value"); } } catch (JSONException e) { e.printStackTrace(); } return null; } private String getKeyFromData(JSONArray data) { try { JSONObject obj = data.getJSONObject(0); if (obj.has("key")) { return obj.getString("key"); } } catch (JSONException e) { e.printStackTrace(); } return null; } }
package com.rishi.baldawa.iq; import org.junit.Test; import static org.junit.Assert.assertEquals; public class MaxProfitFromStockManyTransactionsTest { @Test public void maxProfit() throws Exception { assertEquals(new MaxProfitFromStockManyTransactions().maxProfit(new int[]{7, 1, 5, 3, 0, 6, 4}), 10); } }
/* * 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 ps3presentation.business; import ps3presentation.business.GenericDataClass; import java.util.ArrayList; import ps3preservation.data.Ps3SQLDatabase; /** * * @author Marin */ public class Packages extends GenericDataClass { private int id; //not null private String name; //not null private String filename; //not null private String source_url; //DEFAULT -> NULL private PackageType package_type; //DEFAULT -> NULL private Type type; //not null private PackageChannel package_channel; //not null private double version; //not null private double sys_version; //not null private int size; //not null private byte[] hash; //not null private int license_id; //DEFAULT -> NULL private byte verified; //not null private static final String[] COLUMN_NAMES = {"filename", "hash", "id", "license_id", "name", "type", "package_type", "size", "source_url", "sys_version", "package_channel", "verified", "version"}; private Ps3SQLDatabase database; public Packages(int id, String name, String filename, String source_url, String package_type, String type, String package_channel, double sys_version, double version, int size, byte[] hash, int license_id, byte verified) { this.id = id; this.name = name; this.filename = filename; this.source_url = source_url; enumHandler(package_type); enumHandler(type); enumHandler(package_channel); this.version = version; this.sys_version = sys_version; this.size = size; this.hash = hash; this.license_id = license_id; this.verified = verified; super.populateAttributeList(); } public Packages(int id, Ps3SQLDatabase database) { this.id = id; this.database = database; } public boolean getPackageData() { boolean returned = false; ArrayList<ArrayList<String>> results = database.getData("select * from " + "packages where id = " + id); if (results.size() > 0) { returned = true; this.name = results.get(0).get(1); this.filename = results.get(0).get(2); this.source_url = results.get(0).get(3); enumHandler(results.get(0).get(4)); enumHandler(results.get(0).get(5)); enumHandler(results.get(0).get(6)); this.version = Double.parseDouble(results.get(0).get(7)); this.sys_version = Double.parseDouble(results.get(0).get(8)); this.size = Integer.parseInt(results.get(0).get(9)); //this.hash = Integer.parseInt(results.get(0).get(10)); if (results.get(0).get(11) != null) { this.license_id = Integer.parseInt(results.get(0).get(11)); } //this.verified = Integer.parseInt(results.get(0).get(12)); } return returned; } enum Type { UPDATE, SOUNDTRACK, EDAT, THEME, DEMO, DLC, VIDEO, WALLPAPER, MANUAL, AVATAR, CORE }; enum PackageType { ISO, PKG }; enum PackageChannel { RETAIL, DEBUG }; public void enumHandler(String enumValue) { for (Type element : Type.values()) { if (element.name().equals(enumValue)) { this.type = Type.valueOf(enumValue); return; } else { this.type = Type.DEMO; } } for (PackageType packType : PackageType.values()) { if (packType.name().equals(enumValue)) { this.package_type = PackageType.valueOf(enumValue); return; } else { this.package_type = PackageType.ISO; } } for (PackageChannel packChann : PackageChannel.values()) { if (packChann.name().equals(enumValue)) { this.package_channel = PackageChannel.valueOf(enumValue); return; } else { this.package_channel = PackageChannel.DEBUG; } } } @Override public String[] attributeNamesGetter() { return COLUMN_NAMES; } @Override public String tableNameGetter() { return "packages"; } @Override public void setAllTheAttributes(ArrayList<ArrayList<String>> array) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public String primaryKeyNameGetter() { return "id"; } @Override public String primaryKeyValueGetter() { return "" + getId(); } public int getId() { return id; } public String getName() { return name; } public String getFilename() { return filename; } public String getSource_url() { return source_url; } public String getPackage_type() { return package_type.name(); } public String getType() { return type.name(); } public String getPackage_channel() { return package_channel.name(); } public double getVersion() { return version; } public double getSys_version() { return sys_version; } public int getSize() { return size; } public byte[] getHash() { return hash; } public int getLicense_id() { return license_id; } public byte getVerified() { return verified; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setFilename(String filename) { this.filename = filename; } public void setSource_url(String source_url) { this.source_url = source_url; } public void setPackage_type(PackageType package_type) { enumHandler(package_type.name()); } public void setType(Type type) { enumHandler(type.name()); } public void setPackage_channel(PackageChannel package_channel) { enumHandler(package_channel.name()); } public void setVersion(double version) { this.version = version; } public void setSys_version(double sys_version) { this.sys_version = sys_version; } public void setSize(int size) { this.size = size; } public void setHash(byte[] hash) { this.hash = hash; } public void setLicense_id(int license_id) { this.license_id = license_id; } public void setVerified(byte verified) { this.verified = verified; } }
package wallFollower; import lejos.hardware.motor.EV3LargeRegulatedMotor; public class PController implements UltrasonicController { private final int bandCenter, bandwidth; private EV3LargeRegulatedMotor leftMotor, rightMotor; private int distance; private int filterControl; //CONSTANTS private final int motorStraight = 130, FILTER_OUT = 50; private final int BANDCENTER_CONSTANT = 7, BANDWIDTH_CONSTANT = 2; private final int MAX_DISTANCE = 255; private final int DELTA_CONSTANT = 6; private final int MIN_SPEED = 0; private final int MAX_LEFT_SPEED = 250; private final int MAX_RIGHT_SPEED = 270; private final int LOW_SPEED = 50; public PController(EV3LargeRegulatedMotor leftMotor, EV3LargeRegulatedMotor rightMotor, int bandCenter, int bandwidth) { // Default Constructor this.bandCenter = bandCenter + BANDCENTER_CONSTANT; this.bandwidth = bandwidth - BANDWIDTH_CONSTANT; this.leftMotor = leftMotor; this.rightMotor = rightMotor; leftMotor.setSpeed(motorStraight); // Initalize motor rolling forward rightMotor.setSpeed(motorStraight); leftMotor.forward(); rightMotor.forward(); filterControl = 0; } @Override public void processUSData(int distance) { // rudimentary filter - toss out invalid samples corresponding to null // signal. // (n.b. this was not included in the Bang-bang controller, but easily // could have). // //MAKE SURE THAT ALL VALUES ABOVE 255 ARE READ AS 255 distance = (distance > MAX_DISTANCE) ? MAX_DISTANCE: distance; if (distance == MAX_DISTANCE && filterControl < FILTER_OUT) { // bad value, do not set the distance var, however do increment the // filter value filterControl++; this.leftMotor.setSpeed(motorStraight); this.rightMotor.setSpeed(motorStraight); this.leftMotor.forward(); this.rightMotor.forward(); System.out.println(filterControl); return; } else if (distance == MAX_DISTANCE) { // true MAX_DISTANCE, therefore set distance to MAX_DISTANCE this.distance = distance; } else { // distance went below MAX_DISTANCE, therefore reset everything. filterControl = 0; this.distance = distance; } //CALCULATION OF THE ADJUSTMENT CONSTANT int delta = DELTA_CONSTANT * (((Math.abs(distance - this.bandCenter) - this.bandwidth) < 0)? 0 : (Math.abs(distance - this.bandCenter) - this.bandwidth)); // delta = (Math.abs(delta) > 200)?(int)Math.signum(delta) * 150 : delta; //ADJUSTMENT OF THE SPEED OF THE WHEELS BASED ON THE CALCULATED ADJUSTMENT CONSTANT DELTA int leftAdjustedSpeed = motorStraight + ((distance < this.bandCenter - this.bandwidth)? +delta : -delta); int rightAdjustedSpeed = motorStraight + ((distance < this.bandCenter - this.bandwidth)? -delta : +delta); //WE MAKE SURE THAT THE SPEED OF THE WHEELS DOES NOT EXCEED A DEFINED MIN AND MAX if (leftAdjustedSpeed < MIN_SPEED) leftAdjustedSpeed = MIN_SPEED; if (rightAdjustedSpeed < MIN_SPEED) rightAdjustedSpeed = MIN_SPEED; if (leftAdjustedSpeed > MAX_LEFT_SPEED) leftAdjustedSpeed = MAX_LEFT_SPEED; if (rightAdjustedSpeed > MAX_RIGHT_SPEED) rightAdjustedSpeed = MAX_RIGHT_SPEED; //SET UP THE SPEED OF THE WHEELS BASED ON THE ADJUSTMENTS ABOVE this.leftMotor.setSpeed((leftAdjustedSpeed < MIN_SPEED)? LOW_SPEED: leftAdjustedSpeed); this.rightMotor.setSpeed((rightAdjustedSpeed < MIN_SPEED)? LOW_SPEED : rightAdjustedSpeed); this.leftMotor.forward(); this.rightMotor.forward(); // TODO: process a movement based on the us distance passed in (P style) } @Override public int readUSDistance() { return this.distance; } }
package com.cnk.travelogix.suppliers.service; import com.cnk.travelogix.supplier.mappings.country.model.SupplierCountryModel; /** * @author I077988 */ public interface SupplierCountryMappingService { /** * @return boolean */ public boolean getAllSupplierCountry(); /** * @param supplierCountryModelReq * @return boolean */ public boolean mapUpdatedSupplierCountry(final SupplierCountryModel supplierCountryModelReq); }
package com.tencent.mm.plugin.honey_pay.ui; import com.tencent.mm.ab.l; import com.tencent.mm.wallet_core.c.h.a; class HoneyPayMainUI$13 implements a { final /* synthetic */ HoneyPayMainUI klC; HoneyPayMainUI$13(HoneyPayMainUI honeyPayMainUI) { this.klC = honeyPayMainUI; } public final void g(int i, int i2, String str, l lVar) { } }
package mum.lesson5.problem2; import java.time.LocalDate; public class Professor extends DeptEmployee { private int numberOfPublications; public Professor(double salary, String name,LocalDate hireDate,int numberOfPublications) { super(salary, name, hireDate); this.numberOfPublications = numberOfPublications; } public int getNumberOfPublications() { return numberOfPublications; } public void setNumberOfPublications(int numberOfPublications) { this.numberOfPublications = numberOfPublications; } public double computeSalary(){ return this.salary; } }
package ru.osipmd.rss.parameters; import com.rometools.rome.feed.synd.SyndEntry; /** * It's class of Description parameter RSS channel * @author Mikhail Osipov */ public class Description extends RssParameter { private static final String NAME = "description"; @Override String getInfoFromRssItem(SyndEntry item) { if (item.getDescription() == null) { return null; } return item.getDescription().getValue(); } @Override String getParameterName() { return NAME; } }
package com.example.testjson.api; public class Constants { /** * 通信関係の定数クラス * * @author */ public static final class ApiParams { //schema public static final String CM_HTTPS = "https"; //domain public static final String CM_DOMAIN = "watasama.com"; //path public static final String CM_PATH_COVER = "/ec/classy-api/coverContents.php"; //接続タイムアウト public static final int CONN_TIMEOUT = 60 * 1000;//15 * 1000;//サーバーの反応が鈍いので } public static final class ApiStatus { /** Success */ public static final String SUCCESS = "1"; public static final String SUCCESS_NO_RESULT = "10"; /** Other Network unknown error */ public static final String OTHER_UNKNOWN = "0"; /** not found */ public static final String NOT_FOUND = "404"; /** Internal server error */ public static final String INTERNAL_SERVER_ERROR = "500"; /** Service unavailable */ public static final String SERVICE_UNAVAILAVLE = "503"; /** network disable */ public static final String NETWORK_DISABLE = "-1"; } }
package com.semester_project.smd_project.Activities; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ImageView; import android.widget.ProgressBar; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.semester_project.smd_project.Areas; import com.semester_project.smd_project.Guider_info; import com.semester_project.smd_project.R; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import Models.TripInfo; import MyRecycleView.MyRvAdapter; public class TourGuideSelection extends AppCompatActivity implements Serializable { //Button proceedtopay; private ProgressBar progress; ImageView gotocatalogue; EditText searchguider; FirebaseDatabase mDatabase; DatabaseReference dbReference; RecyclerView rv; MyRvAdapter adapter; List<Guider_info> guiders; String USERID; List<Areas> area = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tourguideselection); guiders = new ArrayList<>(); //proceedtopay = findViewById(R.id.proceedtopayment); gotocatalogue = findViewById(R.id.barsid); searchguider = findViewById(R.id.searchguide); mDatabase = FirebaseDatabase.getInstance(); dbReference = mDatabase.getReference("GUIDER"); USERID = FirebaseAuth.getInstance().getCurrentUser().getEmail(); progress = findViewById(R.id.progressbar7); ReceiveGuiders(); rv=findViewById(R.id.rv); LinearLayoutManager lm = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, true); lm.setStackFromEnd(true); rv.setLayoutManager(lm); adapter = new MyRvAdapter(guiders,this, (TripInfo) getIntent().getSerializableExtra("mytripinfo"), USERID); rv.setAdapter(adapter); gotocatalogue.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent in = new Intent (getApplicationContext(), Add_Cataloges.class); finish(); HideKeyboard(); startActivity(in); } }); searchguider.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { filter(s.toString()); } }); } public void filter(String txt) { ArrayList<Guider_info> lst = new ArrayList<>(); for(Guider_info item : guiders) { if(item.getName().toLowerCase().contains(txt.toLowerCase())) { lst.add(item); } else if (item.getExperience().toLowerCase().contains(txt.toLowerCase())) { lst.add(item); } else if (item.getPrice().toLowerCase().contains(txt.toLowerCase())) { lst.add(item); } } adapter.filteredlst(lst); } public void ReceiveGuiders() { progress.setVisibility(View.VISIBLE); dbReference.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { for (DataSnapshot d: snapshot.getChildren()) { String name = d.child("username").getValue(String.class); String age = d.child("age").getValue(String.class); String profilepic = d.child("profilepic").getValue(String.class); String experience = d.child("experience").getValue(String.class); String budget = d.child("budget").getValue(String.class); String useremail = d.child("useremail").getValue(String.class); String phone = d.child("phone").getValue(String.class); String address = d.child("address").getValue(String.class); String country = d.child("country").getValue(String.class); guiders.add(new Guider_info(name, age, profilepic, experience, budget, useremail, phone, address, country)); adapter.notifyDataSetChanged(); progress.setVisibility(View.GONE); } } @Override public void onCancelled(@NonNull DatabaseError error) { progress.setVisibility(View.GONE); } }); progress.setVisibility(View.GONE); } protected void HideKeyboard() { InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); View view = getCurrentFocus(); if (view == null) { view = new View(getApplicationContext()); } imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } }
package com.diozero.devices; /* * #%L * Organisation: diozero * Project: diozero - Core * Filename: McpEeprom.java * * This file is part of the diozero project. More information about this project * can be found at https://www.diozero.com/. * %% * Copyright (C) 2016 - 2023 diozero * %% * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * #L% */ import org.tinylog.Logger; import com.diozero.api.DeviceInterface; import com.diozero.api.I2CDevice; import com.diozero.api.RuntimeIOException; import com.diozero.util.SleepUtil; /** * See the <a href="http://www.microchip.com/ParamChartSearch/chart.aspx?branchID=1100111">Microchip website</a>. * <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/21754M.pdf">Datasheet</a>. * Connections: * <pre> * Notch * GND A0 1 8 Vcc 3v3 * GND A1 2 7 WP (Write Protect Input, Vss=write enabled, Vcc=write disabled) * GND A2 3 6 SCL * GND Vss 4 5 SDA * </pre> */ public class McpEeprom implements DeviceInterface { public static enum Type { MCP_24xx256(2, 64, 5, 256), MCP_24xx512(2, 128, 5, 512); private int addressSizeBytes; private int pageSizeBytes; private int writeCycleTimeMillis; private int memorySizeBits; private int memorySizeBytes; private Type(int addressSizeBytes, int pageSizeBytes, int writeCycleTimeMillis, int memorySizeKibibits) { this.addressSizeBytes = addressSizeBytes; this.pageSizeBytes = pageSizeBytes; this.writeCycleTimeMillis = writeCycleTimeMillis; memorySizeBits = memorySizeKibibits * 1024; memorySizeBytes = memorySizeBits / 8; } public int getAddressSizeBytes() { return addressSizeBytes; } public int getPageSizeBytes() { return pageSizeBytes; } public int getWriteCycleTimeMillis() { return writeCycleTimeMillis; } public int getMemorySizeBits() { return memorySizeBits; } public int getMemorySizeBytes() { return memorySizeBytes; } } public static final int DEFAULT_ADDRESS = 0x50; private I2CDevice device; private Type type; public McpEeprom(int controller, Type type) { this(controller, DEFAULT_ADDRESS, type); } public McpEeprom(int controller, int address, Type type) { this.type = type; device = I2CDevice.builder(address).setController(controller).build(); if (! device.probe()) { throw new RuntimeIOException("No such device " + controller + "-0x" + Integer.toHexString(address)); } } public Type getType() { return type; } public int getMemorySizeByte() { return type.getMemorySizeBytes(); } private byte[] getAddressByteArray(int address) { byte[] address_bytes = new byte[type.getAddressSizeBytes()]; for (int i=0; i<type.getAddressSizeBytes(); i++) { address_bytes[i] = (byte) ((address >> 8 * (type.getAddressSizeBytes() - (i+1))) & 0xff); } return address_bytes; } public byte readCurrentAddress() { return device.readByte(); } public byte readByte(int address) { device.writeBytes(getAddressByteArray(address)); return device.readByte(); } public byte[] readBytes(int address, int length) { device.writeBytes(getAddressByteArray(address)); return device.readBytes(length); } public void writeByte(int address, int data) { writeByte(address, (byte) data); } public void writeByte(int address, byte data) { byte[] addr_bytes = getAddressByteArray(address); byte[] buffer = new byte[addr_bytes.length+1]; System.arraycopy(addr_bytes, 0, buffer, 0, addr_bytes.length); buffer[addr_bytes.length] = data; device.writeBytes(buffer); SleepUtil.sleepMillis(type.getWriteCycleTimeMillis()); } public void writeBytes(int address, byte[] data) { if ((address + data.length) > type.getMemorySizeBytes()) { Logger.error("Attempt to write beyond memory size - no data written"); return; } int page = address / type.getPageSizeBytes(); int bytes_remaining = data.length; do { int remaining_page_size = type.getPageSizeBytes() - (address % type.getPageSizeBytes()); int bytes_to_write = remaining_page_size < bytes_remaining ? remaining_page_size : bytes_remaining; byte[] addr_bytes = getAddressByteArray(address); byte[] buffer = new byte[addr_bytes.length+bytes_to_write]; System.arraycopy(addr_bytes, 0, buffer, 0, addr_bytes.length); System.arraycopy(data, data.length - bytes_remaining, buffer, addr_bytes.length, bytes_to_write); device.writeBytes(buffer); bytes_remaining -= bytes_to_write; page++; address = page * type.getPageSizeBytes(); SleepUtil.sleepMillis(type.getWriteCycleTimeMillis()); } while (bytes_remaining > 0); } @Override public void close() { device.close(); } }
package com.tencent.mm.ac; import android.os.Looper; import com.tencent.mm.ab.e; import com.tencent.mm.ab.l; import com.tencent.mm.kernel.g; import com.tencent.mm.protocal.c.aas; import com.tencent.mm.protocal.c.blr; import com.tencent.mm.protocal.c.fh; import com.tencent.mm.protocal.c.ia; import com.tencent.mm.sdk.e.i; import com.tencent.mm.sdk.e.k; import com.tencent.mm.sdk.platformtools.bi; public final class c extends i<b> implements e { public static fh dKB; public static final String[] diD = new String[]{i.a(b.dhO, "BizEnterprise")}; private final k<a, a> dKC = new 1(this); private com.tencent.mm.sdk.e.e diF; public c(com.tencent.mm.sdk.e.e eVar) { super(eVar, b.dhO, "BizEnterprise", null); this.diF = eVar; eVar.fV("BizEnterprise", "CREATE INDEX IF NOT EXISTS BizEnterpriseUserNameIndex ON BizEnterprise ( userName )"); g.Eh().dpP.a(1343, this); g.Eh().dpP.a(1228, this); } public final void a(a aVar, Looper looper) { this.dKC.a(aVar, looper); } public final void a(a aVar) { if (this.dKC != null) { this.dKC.remove(aVar); } } public final b kn(String str) { if (bi.oW(str)) { return null; } b bVar = new b(); bVar.field_userName = str; if (super.b(bVar, new String[0])) { return bVar; } a(str, null); return null; } public final b ko(String str) { b kn = kn(str); if (kn != null) { return kn; } kn = new b(); kn.field_userName = str; kn.field_qyUin = 0; kn.field_userUin = 0; kn.field_userFlag = 0; kn.field_wwExposeTimes = 0; kn.field_wwMaxExposeTimes = 0; kn.field_wwUserVid = 0; kn.field_wwCorpId = 0; kn.field_chatOpen = false; kn.field_wwUnreadCnt = 0; return kn; } public final int kp(String str) { b kn = kn(str); if (kn == null) { return 0; } return kn.field_qyUin; } public final boolean jy(String str) { boolean z = false; if (!bi.oW(str)) { b bVar = new b(); bVar.field_userName = str; z = super.a(bVar, new String[]{"userName"}); if (z) { a aVar = new a(); aVar.dKF = str; aVar.dKE = b.dKI; aVar.dKG = bVar; this.dKC.ci(aVar); this.dKC.doNotify(); } } return z; } private boolean a(b bVar) { if (bVar == null) { return false; } boolean b = super.b(bVar); int i = b.dKH; if (!b) { b = super.a(bVar); i = b.dKJ; } if (!b) { return b; } a aVar = new a(); aVar.dKF = bVar.field_userName; aVar.dKE = i; aVar.dKG = bVar; this.dKC.ci(aVar); this.dKC.doNotify(); return b; } private boolean a(ia iaVar) { b ko = ko(iaVar.riK); ko.field_userName = iaVar.riK; ko.field_qyUin = iaVar.riU; ko.field_userUin = iaVar.riV; ko.field_wwMaxExposeTimes = iaVar.riX; ko.field_wwUserVid = iaVar.riY; ko.field_wwCorpId = iaVar.riZ; ko.field_userType = iaVar.rja; ko.field_chatOpen = iaVar.rjb; ko.field_wwUnreadCnt = iaVar.rjc; ko.field_show_confirm = iaVar.rjd; ko.field_use_preset_banner_tips = iaVar.rjf; dKB = iaVar.rje; if (iaVar.riY == 0 && iaVar.riZ == 0 && iaVar.riU != 0) { ko.field_wwUserVid = (long) iaVar.riV; ko.field_wwCorpId = (long) iaVar.riU; } iaVar.riW &= -9; ko.field_userFlag = iaVar.riW | (ko.field_userFlag & 8); return a(ko); } public static boolean a(String str, e eVar) { if (bi.oW(str)) { return false; } int i; if (f.kM(str)) { i = 1; } else if (!f.kL(str)) { return false; } else { i = 2; } return g.Eh().dpP.a(new s(str, i, eVar), 0); } public static y a(String str, boolean z, e eVar) { ia iaVar = new ia(); iaVar.riK = str; iaVar.riW = z ? 1 : 0; iaVar.riU = 0; y yVar = new y(iaVar, eVar); return g.Eh().dpP.a(yVar, 0) ? yVar : null; } public final void kq(String str) { b ko = ko(str); if (ko.field_wwExposeTimes < ko.field_wwMaxExposeTimes) { ko.field_wwExposeTimes++; a(ko); } } public static void a(y yVar) { g.Eh().dpP.c(yVar); yVar.data = null; } public final boolean kr(String str) { b kn = kn(str); return (kn == null || (kn.field_userFlag & 1) == 0) ? false : true; } public static String ht(int i) { if (dKB == null) { dKB = new fh(); } switch (i) { case 0: return dKB.rgh; case 1: return dKB.rgi; case 2: return dKB.rgj; default: return null; } } public final void a(int i, int i2, String str, l lVar) { int i3 = -1; if (i == 0 && i2 == 0) { e eVar; if (lVar instanceof s) { s sVar = (s) lVar; aas aas = (sVar.diG == null || sVar.diG.dIE.dIL == null) ? null : (aas) sVar.diG.dIE.dIL; if (aas != null && aas.riQ != null && aas.riQ.ret == 0 && aas.rFY != null) { if (!a(aas.rFY)) { i2 = -1; } eVar = (e) sVar.data; if (eVar != null) { eVar.a(i, i2, str, lVar); } } else { return; } } if (lVar instanceof y) { y yVar = (y) lVar; blr blr = (yVar.diG == null || yVar.diG.dIE.dIL == null) ? null : (blr) yVar.diG.dIE.dIL; if (blr != null && blr.riQ != null && blr.riQ.ret == 0 && blr.rFY != null) { if (a(blr.rFY)) { i3 = i2; } eVar = (e) yVar.data; if (eVar != null) { eVar.a(i, i3, str, lVar); } } } } } }
package application.model; import javafx.collections.*; public class DataModel { // 스테이지를 담는 클래스 (데이터를 한 곳에 저장) public static ObservableList<String> list = FXCollections.observableArrayList(); }
package com.tencent.mm.plugin.dbbackup; import com.tencent.mm.R; import com.tencent.mm.plugin.dbbackup.c.1; import com.tencent.mm.ui.base.h; class c$1$1 implements Runnable { final /* synthetic */ int hZq; final /* synthetic */ 1 hZr; c$1$1(1 1, int i) { this.hZr = 1; this.hZq = i; } public final void run() { int i; if (this.hZr.hZo != null) { this.hZr.hZo.dismiss(); } switch (this.hZq) { case -3: i = R.l.recover_db_no_datafile; break; case -2: i = R.l.recover_db_no_enough_space; break; case 0: i = R.l.recover_db_success; break; default: i = R.l.recover_db_fail; break; } h.i(this.hZr.val$context, i, R.l.app_tip); } }
package evm.dmc.core.api; import evm.dmc.api.model.FunctionDstModel; import evm.dmc.core.api.exceptions.StoreDataException; public interface DMCDataSaver { void save(Data<?> data) throws StoreDataException; FunctionDstModel getDstModel(); DMCDataSaver setDstModel(FunctionDstModel model); DMCDataSaver setDestination(String filename); }
package com.frcteam1939.killerrabbit.robot; import com.frcteam1939.killerrabbit.robot.subsystems.Ears; import com.frcteam1939.killerrabbit.robot.subsystems.Drivetrain; import com.frcteam1939.killerrabbit.robot.subsystems.Shooter; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; public class Robot extends IterativeRobot { public static final Ears ears = new Ears(); public static final Drivetrain drivetrain = new Drivetrain(); public static final Shooter shooter= new Shooter(); public static OI oi; @Override public void robotInit() { oi = new OI(); } @Override public void disabledInit() { } @Override public void disabledPeriodic() { Scheduler.getInstance().run(); } @Override public void autonomousInit() { } @Override public void autonomousPeriodic() { Scheduler.getInstance().run(); } @Override public void teleopInit() { } @Override public void teleopPeriodic() { Scheduler.getInstance().run(); } @Override public void testPeriodic() { LiveWindow.run(); } }
package com.haibo.mapper; import com.haibo.pojo.Coach; import com.haibo.pojo.Exam; import org.apache.ibatis.annotations.Param; /** * Created with IDEA. * User:haibo. * DATE:2018/5/6/006 */ public interface ExamMapper { //添加考试信息 public void addExam(Exam exam); }
package b_secondexp; import java.util.Scanner; public class FishTank { // 标记数组 private static int[] size = new int[1001]; public static void main(String[] args) { int minSize, maxSize, n, count = 0; size[0] = 1; Scanner scanner = new Scanner(System.in); System.out.print("输入新放入鱼最小尺寸:"); minSize = scanner.nextInt(); System.out.print("输入新放入鱼最大尺寸:"); maxSize = scanner.nextInt(); System.out.print("输入原鱼塘鱼的数量:"); n = scanner.nextInt(); int[] fishSize = new int[n]; System.out.println("输入原鱼塘鱼的尺寸大小:"); // 原来的鱼的size for (int i = 0; i < n; i++) { fishSize[i] = scanner.nextInt(); } // 将原鱼塘内的鱼 吃与被吃的范围内size值置 for (int i = 0; i < n; i++) { int left = (int) Math.ceil(fishSize[i] / 10); int right = (int) Math.floor(fishSize[i] / 2); for (int j = left; j <= right; j++) { size[j] = 1; } if (fishSize[i] * 10 >= 1000) { right = 1000; } else { right = fishSize[i] * 10; } for (int j = fishSize[i] * 2; j <= right; j++) { size[j] = 1; } } // 每当检测到size值为0,则count加一 for (int i = minSize; i <= maxSize; i++) { if (size[i] == 0) { System.out.print(i + " "); count++; } } System.out.println("可放入鱼的数量" + count); } }
/* * UserinfoModel.java * Copyright(c) 2007 BroadText Inc. * ALL Rights Reserved. */ package com.takshine.wxcrm.model; import java.util.Date; import com.takshine.wxcrm.base.model.BaseModel; /** * 微信用户基本信息表 Model * * @author liulin */ public class SocialUserInfoModel extends BaseModel { private String uid = null; private String subscribe = null; private String nickname = null; private String name = null; //友好显示名称 private String sex = null; private String city = null; private String country = null; private String province = null; private String language = null; private String headimgurl = null; private Date subscribeTime = null; private String wbname = null; private String followers_count = null; //关注数 private String friends_count = null; //粉丝数 private String social_type = null; private String access_token = null; private String expires_in =null; private String location = null; private String statuses_count = null;//微博数 private String desc; private String url; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getStatuses_count() { return statuses_count; } public void setStatuses_count(String statuses_count) { this.statuses_count = statuses_count; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public String getExpires_in() { return expires_in; } public void setExpires_in(String expires_in) { this.expires_in = expires_in; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getSocial_type() { return social_type; } public void setSocial_type(String social_type) { this.social_type = social_type; } public String getWbname() { return wbname; } public void setWbname(String wbname) { this.wbname = wbname; } public String getFollowers_count() { return followers_count; } public void setFollowers_count(String followers_count) { this.followers_count = followers_count; } public String getFriends_count() { return friends_count; } public void setFriends_count(String friends_count) { this.friends_count = friends_count; } public String getSubscribe() { return subscribe; } public void setSubscribe(String subscribe) { this.subscribe = subscribe; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getHeadimgurl() { return headimgurl; } public void setHeadimgurl(String headimgurl) { this.headimgurl = headimgurl; } public Date getSubscribeTime() { return subscribeTime; } public void setSubscribeTime(Date subscribeTime) { this.subscribeTime = subscribeTime; } }
package com.computer; public class KeyBoard extends Parts{ private String type; //private String maker; //public KeyBoard(){} public KeyBoard(String maker, int price, String type) { super(maker,price); this.type = type; } public void typing(){ System.out.println("KeyBoard typing..."); System.out.println("----------"); } public void info() { super.info(); System.out.println("type: " + type); System.out.println("------------------------"); } public String getType() { return type; } public void setType(String type) { this.type = type; } }
/* * Copyright (c) 2013 University of Tartu */ package org.jpmml.manager; import org.dmg.pmml.*; import static com.google.common.base.Preconditions.*; public class RuleSetModelManager extends ModelManager<RuleSetModel> { private RuleSetModel ruleSetModel = null; public RuleSetModelManager(){ } public RuleSetModelManager(PMML pmml){ this(pmml, find(pmml.getContent(), RuleSetModel.class)); } public RuleSetModelManager(PMML pmml, RuleSetModel ruleSetModel){ super(pmml); this.ruleSetModel = ruleSetModel; } @Override public String getSummary(){ return "Rule set model"; } @Override public RuleSetModel getModel(){ checkState(this.ruleSetModel != null); return this.ruleSetModel; } /** * @see #getModel() */ public RuleSetModel createModel(){ checkState(this.ruleSetModel == null); this.ruleSetModel = new RuleSetModel(new MiningSchema(), new RuleSet(), MiningFunctionType.CLASSIFICATION); getModels().add(this.ruleSetModel); return this.ruleSetModel; } public RuleSet getRuleSet(){ RuleSetModel ruleSetModel = getModel(); return ruleSetModel.getRuleSet(); } }
/**HW - Decorator * Cesar Hernandez * cherna83 * */ //============================================================= public class Decorator { public static void main(String[] args) { System.out.println("\nChoose between 5 burger decorators to build your burger:"); System.out.println("GrilledOnions, FriedEgg, Bacon, Avocado & RoastedPeppers\n"); //order #1 Burger order = new Avocado(new FriedEgg (new GrilledOnions(new basicBurger()))); double cost = order.makeBurger(); System.out.println("Total: $" + cost); System.out.println("\n"); //order #2 Burger order2 = new FriedEgg(new GrilledOnions(new basicBurger())); double cost2 = order2.makeBurger(); System.out.println("Total: $" + cost2 ); System.out.println("\n"); //order #3 Burger order3 = new RoastedPeppers(new FriedEgg(new Bacon(new GrilledOnions(new Avocado(new basicBurger()))))); double cost3 = order3.makeBurger(); System.out.println("Total: $" + cost3); } } //============================================================= //--------------------------------------------------------- //interface one operator //Interface = Burger interface Burger { public double makeBurger(); } //--------------------------------------------------------- //base class //concrete component class basicBurger implements Burger { private double cost = 6.50; public double makeBurger() { System.out.println("Basic Burger: $6.50"); return cost; } } //--------------------------------------------------------- //aggragates an interface //abstract class //decorator abstract class BurgerDecorator implements Burger { protected Burger specialBurger; public BurgerDecorator(Burger specialBurger) { this.specialBurger = specialBurger; } //single abstract method public double makeBurger() { return specialBurger.makeBurger(); } } //--------------------------------------------------------- //decorator #1 class FriedEgg extends BurgerDecorator { private double cost = 1.50; public FriedEgg(Burger specialBurger) { super(specialBurger); } public double makeBurger() { return specialBurger.makeBurger() + addFriedEgg(); } public double addFriedEgg() { System.out.println(" + FriedEgg: $1.50"); return cost; } } //--------------------------------------------------------- //decorator #2 class Avocado extends BurgerDecorator { private double cost = .75; public Avocado(Burger specialBurger) { super(specialBurger); } public double makeBurger() { return specialBurger.makeBurger() + addAvocado(); } public double addAvocado() { System.out.println(" + Avocado: $.75"); return cost; } } //--------------------------------------------------------- //Concrete //Decorator #3 class Bacon extends BurgerDecorator { private double cost = 2.00; public Bacon(Burger specialBurger) { super(specialBurger); } public double makeBurger() { return specialBurger.makeBurger() + addBacon(); } public double addBacon() { System.out.println(" + Bacon: $2.00"); return cost; } } //--------------------------------------------------------- //decorator #4 class GrilledOnions extends BurgerDecorator { private double cost = 1.00; public GrilledOnions(Burger specialBurger) { super(specialBurger); } public double makeBurger() { return specialBurger.makeBurger() + addGrilledOnions(); } public double addGrilledOnions() { System.out.println(" + GrilledOnions: $1.00"); return cost; } } //--------------------------------------------------------- //decorator #5 class RoastedPeppers extends BurgerDecorator { private double cost = 5.00; public RoastedPeppers(Burger specialBurger) { super(specialBurger); } public double makeBurger() { return specialBurger.makeBurger() + addRoastedPeppers(); } public double addRoastedPeppers() { System.out.println(" + RoastedPeppers: $5.00"); return cost; } } //--------------------------------------------------------- //=======================================================================
package sessionbean; import entidade.Usuario; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author wender */ @Stateless public class UsuarioSBean { @PersistenceContext(unitName = "JavaWebPU") private EntityManager em; public void salvar(Usuario usuario) throws Exception { try { em.merge(usuario); } catch (Exception ex) { throw new Exception("Ouve um error ao Salvar o Usuario"); } } public void excluir(Usuario usuario) throws Exception { try { em.remove(em.find(Usuario.class, usuario.getId())); } catch (Exception ex) { throw new Exception("Ouve um erro ao excluir o Usuario."); } } public Usuario pesquisar(Long id) throws Exception { try { return em.find(Usuario.class, id); } catch (Exception ex) { throw new Exception("Ouve um erro ao pesquisar Usuario."); } } public List<Usuario> pesquisar(String valorPesquisa) throws Exception { try { List<Usuario> listaUsuario; Query consulta = em.createNamedQuery("Usuario.findByNome"); consulta.setParameter("nome", valorPesquisa + "%"); listaUsuario = consulta.getResultList(); return listaUsuario; } catch (Exception ex) { throw new Exception("Ouve um erro ao pesquisar o Usuario."); } } public Usuario login(String userName, String senha) throws Exception { try { Query consulta = em.createNamedQuery("Usuario.login"); consulta.setParameter("userName", userName); consulta.setParameter("senha", senha); return (Usuario)consulta.getSingleResult(); } catch(NoResultException ex) { throw new Exception("Usuario ou senha invalido."); } catch (Exception ex) { throw new Exception("Erro ao fazer login - " + ex.getMessage()); } } }
package pe.com.tss.bean; import java.io.Serializable; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; import org.eclipse.persistence.annotations.ReturnInsert; import java.math.BigDecimal; /** * The persistent class for the CITY database table. * */ @Entity @Table(name = "CITY") @XmlRootElement @NamedQueries({ @NamedQuery(name = "City.findAll", query = "SELECT c FROM City c"), @NamedQuery(name = "City.findByName", query = "SELECT c FROM City c WHERE c.name=:name"), @NamedQuery(name = "City.exitsCity", query = "SELECT COUNT(c.name) FROM City c WHERE c.name=:name"), @NamedQuery(name = "City.getCity", query = "SELECT c FROM City c WHERE c.name=:name") }) public class City implements Serializable { private static final long serialVersionUID = 1L; //@Id //@GeneratedValue(strategy = GenerationType.IDENTITY) @Id @Column(name = "CITY_ID") @ReturnInsert(returnOnly=true) private long cityid; @Column(name = "NAME") private String name; @Column(name = "STATE_ID") private long stateid; public City() { } public long getCityid() { return this.cityid; } public void setCityid(Integer cityid) { this.cityid = cityid; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public long getStateid() { return this.stateid; } public void setStateid(long stateid) { this.stateid = stateid; } @Override public String toString() { return "City [cityid=" + cityid + ", name=" + name + ", stateid=" + stateid + "]"; } }
package com.example.codetribe1.constructionappsuite.util; import android.animation.Animator; import android.animation.AnimatorInflater; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.location.Location; import android.media.ExifInterface; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.text.Html; import android.util.Log; import android.view.Display; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.AccelerateInterpolator; import android.view.animation.Animation; import android.view.animation.OvershootInterpolator; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.ListPopupWindow; import android.widget.TextView; import android.widget.Toast; import com.example.codetribe1.constructionappsuite.R; import com.example.codetribe1.constructionappsuite.adapters.PopupListAdapter; import com.example.codetribe1.constructionappsuite.dto.CompanyStaffDTO; import com.example.codetribe1.constructionappsuite.dto.ProjectDTO; import com.example.codetribe1.constructionappsuite.dto.transfer.RequestDTO; import com.example.codetribe1.constructionappsuite.dto.transfer.ResponseDTO; import org.apache.commons.io.FileUtils; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Random; public class Util { public static final int EXEC = 1, OPS = 2, PROJ = 3, SITE = 4; public static final int FLASH_SLOW = 1, FLASH_MEDIUM = 2, FLASH_FAST = 3, INFINITE_FLASHES = 9999; public static final long HOUR = 60 * 60 * 1000; public static final long DAY = 24 * HOUR; public static final long WEEK = 7 * DAY; public static final long WEEKS = 2 * WEEK; public static final long MONTH = 30 * DAY; public static final String MONDAY = "Monday"; public static final String TUESDAY = "Tuesday"; public static final String WEDNESDAY = "Wednesday"; public static final String THURSDAY = "Thursday"; public static final String FRIDAY = "Friday"; public static final String SATURDAY = "Saturday"; public static final String SUNDAY = "Sunday"; public static final String FIRST_WEEK = "First"; public static final String SECOND_WEEK = "Second"; public static final String THIRD_WEEK = "Third"; public static final String FOURTH_WEEK = "Fourth"; static final String LOG = Util.class.getSimpleName(); static final int DURATION_FAST = 100, PAUSE_FAST = 100, DURATION_MEDIUM = 300, PAUSE_MEDIUM = 300, DURATION_SLOW = 500, PAUSE_SLOW = 500; static Random random = new Random(System.currentTimeMillis()); static int maxFlashes, count; private static int MAX_IMAGE_DIMENSION = 720; public static void showPopupBasic(Context ctx, Activity act, List<String> list, View anchorView, final UtilPopupListener listener) { final ListPopupWindow pop = new ListPopupWindow(act); pop.setAdapter(new PopupListAdapter(ctx, R.layout.xxsimple_spinner_item, list, false)); pop.setAnchorView(anchorView); pop.setModal(true); pop.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { pop.dismiss(); if (listener != null) { listener.onItemSelected(position); } } }); pop.show(); } private static int getWindowWidth(Activity ctx) { Display display = ctx.getWindowManager().getDefaultDisplay(); return display.getWidth(); } private static int getWindowHeight(Activity ctx) { Display display = ctx.getWindowManager().getDefaultDisplay(); return display.getHeight(); } public static void showPopupBasicWithHeroImage(Context ctx, Activity act, List<String> list, View anchorView, String caption, final UtilPopupListener listener) { final ListPopupWindow pop = new ListPopupWindow(act); LayoutInflater inf = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inf.inflate(R.layout.hero_image_popup, null); TextView txt = (TextView) v.findViewById(R.id.HERO_caption); if (caption != null) { txt.setText(caption); } else { txt.setVisibility(View.GONE); } ImageView img = (ImageView) v.findViewById(R.id.HERO_image); img.setImageDrawable(getRandomHeroImage(ctx)); Double b = new Double("" + getWindowWidth(act)); Double c = b / new Double("1.5"); //RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(getWindowWidth(act), 100); //img.setLayoutParams(layoutParams); pop.setPromptView(v); pop.setPromptPosition(ListPopupWindow.POSITION_PROMPT_ABOVE); pop.setAdapter(new PopupListAdapter(ctx, R.layout.xxsimple_spinner_item, list, false)); pop.setAnchorView(anchorView); pop.setModal(true); pop.setWidth(c.intValue()); pop.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { pop.dismiss(); if (listener != null) { listener.onItemSelected(position); } } }); pop.show(); } public static void showPopup(Context ctx, Activity act, List<String> list, View anchorView, View promptView, Integer width, Integer height, Integer horizontalOffset, final UtilPopupListener listener) { final ListPopupWindow pop = new ListPopupWindow(act); pop.setPromptView(promptView); pop.setPromptPosition(ListPopupWindow.POSITION_PROMPT_ABOVE); pop.setAdapter(new PopupListAdapter(ctx, R.layout.xxsimple_spinner_item, list, false)); pop.setAnchorView(anchorView); if (width != null) { pop.setWidth(width); } if (horizontalOffset != null) { pop.setHorizontalOffset(horizontalOffset); } if (height != null) { pop.setHeight(height); } pop.setModal(true); pop.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { pop.dismiss(); if (listener != null) { listener.onItemSelected(position); } } }); pop.show(); } public static void showConfirmAppInvitationDialog(final Context ctx, final Activity act, final CompanyStaffDTO companyStaff, final int type) { AlertDialog.Builder dialog = new AlertDialog.Builder(act); switch (type) { case EXEC: dialog.setTitle(ctx.getString(R.string.exec_app)); break; case OPS: dialog.setTitle(ctx.getString(R.string.operations_app)); break; case PROJ: dialog.setTitle(ctx.getString(R.string.pm_app)); break; case SITE: dialog.setTitle(ctx.getString(R.string.supervisor_app)); break; } dialog.setMessage(ctx.getResources().getString(R.string.invite_dialog)) .setPositiveButton(ctx.getResources().getString(R.string.yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { sendInvitation(ctx, act, companyStaff, type); } }) .setNegativeButton(ctx.getResources().getString(R.string.no), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }).show(); } private static void sendInvitation(final Context ctx, Activity act, final CompanyStaffDTO companyStaff, int type) { StringBuilder sba = new StringBuilder(); sba.append(getHeader(ctx, type)); switch (type) { case EXEC: sba.append(getExecLink(ctx, companyStaff)); break; case OPS: sba.append(getOperationsLink(ctx, companyStaff)); sba.append(getFooter(ctx)); break; case PROJ: sba.append(getProjectManagerLink(ctx, companyStaff)); break; case SITE: sba.append(getSiteManagerLink(ctx, companyStaff)); break; } sba.append(getFooter(ctx)); Log.w(LOG, "before send intent, sba = \n" + sba.toString()); final Intent shareIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + companyStaff.getEmail())); shareIntent.putExtra(Intent.EXTRA_SUBJECT, ctx.getResources().getString(R.string.subject)); shareIntent.putExtra( Intent.EXTRA_TEXT, Html.fromHtml(sba.toString()) ); Log.e(LOG, shareIntent.toString()); ctx.startActivity(Intent.createChooser(shareIntent, "Email:")); //update app date CompanyStaffDTO cs = new CompanyStaffDTO(); cs.setAppInvitationDate(new Date()); cs.setCompanyStaffID(companyStaff.getCompanyStaffID()); RequestDTO w = new RequestDTO(); w.setRequestType(RequestDTO.UPDATE_COMPANY_STAFF); w.setCompanyStaff(cs); WebSocketUtil.sendRequest(ctx, Statics.COMPANY_ENDPOINT, w, new WebSocketUtil.WebSocketListener() { @Override public void onMessage(final ResponseDTO response) { } @Override public void onClose() { } @Override public void onError(final String message) { } }); } private static String getHeader(Context ctx, int type) { StringBuilder sb = new StringBuilder(); sb.append("<h2>").append(SharedUtil.getCompany(ctx).getCompanyName()).append("</h2>"); sb.append("<p>").append(ctx.getResources().getString(R.string.invited)).append("</p>"); switch (type) { case EXEC: sb.append("<h3>").append(ctx.getString(R.string.exec_app)).append("</h3>"); break; case OPS: sb.append("<h3>").append(ctx.getString(R.string.operations_app)).append("</h3>"); break; case PROJ: sb.append("<h3>").append(ctx.getString(R.string.pm_app)).append("</h3>"); break; case SITE: sb.append("<h3>").append(ctx.getString(R.string.supervisor_app)).append("</h3>"); break; } return sb.toString(); } private static String getFooter(Context ctx) { StringBuilder sb = new StringBuilder(); sb.append(ctx.getString(R.string.contact_us)); sb.append("<h2>").append(ctx.getResources().getString(R.string.enjoy)).append("</h2>"); return sb.toString(); } private static String getSiteManagerLink(Context ctx, CompanyStaffDTO companyStaff) { StringBuilder sb = new StringBuilder(); sb.append("<p>").append(ctx.getResources().getString(R.string.click_link)).append("</p>"); sb.append("<p>").append(Statics.INVITE_SITE_MGR).append("</p>"); sb.append(getPinNote(ctx, companyStaff)); return sb.toString(); } private static String getProjectManagerLink(Context ctx, CompanyStaffDTO companyStaff) { StringBuilder sb = new StringBuilder(); sb.append("<p>").append(ctx.getResources().getString(R.string.click_link)).append("</p>"); sb.append("<p>").append(Statics.INVITE_PROJECT_MGR).append("</p>"); sb.append(getPinNote(ctx, companyStaff)); return sb.toString(); } private static String getPinNote(Context ctx, CompanyStaffDTO companyStaff) { StringBuilder sb = new StringBuilder(); sb.append("<p>").append(ctx.getResources().getString(R.string.pin_note)).append("</p>"); sb.append("<h4>").append(companyStaff.getPin()).append("</h4>"); return sb.toString(); } private static String getOperationsLink(Context ctx, CompanyStaffDTO companyStaff) { StringBuilder sb = new StringBuilder(); sb.append("<p>").append(ctx.getResources().getString(R.string.click_link)).append("</p>"); sb.append("<p>").append(Statics.INVITE_OPERATIONS_MGR).append("</p>"); sb.append(getPinNote(ctx, companyStaff)); return sb.toString(); } private static String getExecLink(Context ctx, CompanyStaffDTO companyStaff) { StringBuilder sb = new StringBuilder(); sb.append("<p>").append(ctx.getResources().getString(R.string.click_link)).append("</p>"); sb.append("<p>").append(Statics.INVITE_EXEC).append("</p>"); sb.append(getPinNote(ctx, companyStaff)); return sb.toString(); } public static void pretendFlash(final View v, final int duration, final int max, final UtilAnimationListener listener) { final ObjectAnimator an = ObjectAnimator.ofFloat(v, "alpha", 1, 1); an.setRepeatMode(ObjectAnimator.REVERSE); an.setDuration(duration); an.setInterpolator(new AccelerateDecelerateInterpolator()); an.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { count++; if (count > max) { count = 0; an.cancel(); if (listener != null) listener.onAnimationEnded(); return; } flashSeveralTimes(v, duration, max, listener); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); an.start(); } public static void showErrorToast(Context ctx, String caption) { LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.toast_monitor_generic, null); TextView txt = (TextView) view.findViewById(R.id.MONTOAST_text); TextView ind = (TextView) view.findViewById(R.id.MONTOAST_indicator); ind.setText("E"); ind.setBackgroundDrawable(ctx.getResources().getDrawable(R.drawable.xred_oval_small)); txt.setTextColor(ctx.getResources().getColor(R.color.absa_red)); txt.setText(caption); Toast customtoast = new Toast(ctx); customtoast.setView(view); customtoast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0); customtoast.setDuration(Toast.LENGTH_LONG); customtoast.show(); } public static void showToast(Context ctx, String caption) { LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.toast_monitor_generic, null); TextView txt = (TextView) view.findViewById(R.id.MONTOAST_text); Statics.setRobotoFontLight(ctx, txt); TextView ind = (TextView) view.findViewById(R.id.MONTOAST_indicator); ind.setText("M"); ind.setBackgroundDrawable(ctx.getResources().getDrawable(R.drawable.xblue_oval_small)); txt.setTextColor(ctx.getResources().getColor(R.color.blue)); txt.setText(caption); Toast customtoast = new Toast(ctx); customtoast.setView(view); customtoast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0); customtoast.setDuration(Toast.LENGTH_LONG); customtoast.show(); } public static void showPagerToast(Context ctx, String caption, Drawable drawable) { LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.toast_pager_instructions, null); TextView txt = (TextView) view.findViewById(R.id.TOAST_text); Statics.setRobotoFontLight(ctx, txt); ImageView img = (ImageView) view.findViewById(R.id.TOAST_image); txt.setText(caption); img.setImageDrawable(drawable); Toast customtoast = new Toast(ctx); customtoast.setView(view); customtoast.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0); customtoast.setDuration(Toast.LENGTH_LONG); customtoast.show(); } public static double getElapsed(long start, long end) { BigDecimal m = new BigDecimal(end - start).divide(new BigDecimal(1000)); return m.doubleValue(); } public static View getHeroView(Context ctx, String caption) { LayoutInflater inflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = inflater.inflate(R.layout.hero_image, null); ImageView img = (ImageView) v.findViewById(R.id.HERO_image); TextView txt = (TextView) v.findViewById(R.id.HERO_caption); img.setImageDrawable(getRandomHeroImage(ctx)); txt.setText(caption); return v; } public static void expandOrCollapse(final View view, int duration, final boolean isExpandRequired, final UtilAnimationListener listener) { TranslateAnimation an = null; if (isExpandRequired) { an = new TranslateAnimation(0.0f, 0.0f, -view.getHeight(), 0.0f); view.setVisibility(View.VISIBLE); } else { an = new TranslateAnimation(0.0f, 0.0f, 0.0f, -view.getHeight()); } an.setDuration(duration); an.setInterpolator(new AccelerateDecelerateInterpolator()); an.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { view.setVisibility(View.GONE); if (listener != null) listener.onAnimationEnded(); } @Override public void onAnimationRepeat(Animation animation) { } }); } public static void collapse(final View view, int duration, final UtilAnimationListener listener) { int finalHeight = view.getHeight(); ValueAnimator mAnimator = slideAnimator(view, finalHeight, 0); mAnimator.setDuration(duration); mAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); mAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { view.setVisibility(View.GONE); if (listener != null) listener.onAnimationEnded(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); mAnimator.start(); } public static void expand(View view, int duration, final UtilAnimationListener listener) { view.setVisibility(View.VISIBLE); final int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); final int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); view.measure(widthSpec, heightSpec); ValueAnimator mAnimator = slideAnimator(view, 0, view.getMeasuredHeight()); mAnimator.setDuration(duration); mAnimator.setInterpolator(new AccelerateDecelerateInterpolator()); mAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { if (listener != null) listener.onAnimationEnded(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); mAnimator.start(); } private static ValueAnimator slideAnimator(final View view, int start, int end) { ValueAnimator animator = ValueAnimator.ofInt(start, end); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { //Update Height int value = (Integer) valueAnimator.getAnimatedValue(); ViewGroup.LayoutParams layoutParams = view.getLayoutParams(); layoutParams.height = value; view.setLayoutParams(layoutParams); } }); return animator; } public static void resizeHeight(final View view, final int height, final long duration, final UtilAnimationListener listener) { Log.e(LOG, "##### view height is " + height); ResizeAnimation a = new ResizeAnimation(view, 0); a.setDuration(1); a.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { ResizeAnimation an = new ResizeAnimation(view, height); an.setDuration(duration); an.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (listener != null) listener.onAnimationEnded(); } @Override public void onAnimationRepeat(Animation animation) { } }); view.startAnimation(an); } @Override public void onAnimationRepeat(Animation animation) { } }); view.startAnimation(a); } public static void flashOnce(View view, long duration, final UtilAnimationListener listener) { ObjectAnimator an = ObjectAnimator.ofFloat(view, "alpha", 0, 1); an.setRepeatMode(ObjectAnimator.REVERSE); an.setDuration(duration); an.setInterpolator(new AccelerateDecelerateInterpolator()); an.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { if (listener != null) listener.onAnimationEnded(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); an.start(); } public static void flashInfinite(final View view, final long duration) { ObjectAnimator an = ObjectAnimator.ofFloat(view, "alpha", 0, 1); an.setRepeatMode(ObjectAnimator.REVERSE); an.setDuration(duration); an.setInterpolator(new AccelerateDecelerateInterpolator()); an.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { flashInfinite(view, duration); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); an.start(); } public static void flashSeveralTimes(final View view, final long duration, final int max, final UtilAnimationListener listener) { final ObjectAnimator an = ObjectAnimator.ofFloat(view, "alpha", 0, 1); an.setRepeatMode(ObjectAnimator.REVERSE); an.setDuration(duration); an.setInterpolator(new AccelerateDecelerateInterpolator()); an.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { count++; if (count > max) { count = 0; an.cancel(); if (listener != null) listener.onAnimationEnded(); return; } flashSeveralTimes(view, duration, max, listener); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); an.start(); } public static void shakeX(final View v, int duration, int max, final UtilAnimationListener listener) { final ObjectAnimator an = ObjectAnimator.ofFloat(v, "x", v.getX(), v.getX() + 20f); an.setDuration(duration); an.setRepeatMode(ObjectAnimator.REVERSE); an.setRepeatCount(max); an.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { if (listener != null) listener.onAnimationEnded(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); an.start(); } public static void flashTrafficLights(final TextView red, final TextView amber, final TextView green, final int max, final int pace) { maxFlashes = max; ObjectAnimator an = ObjectAnimator.ofFloat(red, "alpha", 0, 1); ObjectAnimator an2 = ObjectAnimator.ofFloat(amber, "alpha", 0, 1); ObjectAnimator an3 = ObjectAnimator.ofFloat(green, "alpha", 0, 1); AnimatorSet aSet = new AnimatorSet(); switch (pace) { case FLASH_FAST: an.setDuration(DURATION_FAST); aSet.setStartDelay(PAUSE_FAST); break; case FLASH_MEDIUM: an.setDuration(DURATION_MEDIUM); aSet.setStartDelay(PAUSE_MEDIUM); break; case FLASH_SLOW: an.setDuration(DURATION_SLOW); aSet.setStartDelay(PAUSE_SLOW); break; } an.setInterpolator(new AccelerateDecelerateInterpolator()); an2.setInterpolator(new AccelerateDecelerateInterpolator()); an3.setInterpolator(new AccelerateDecelerateInterpolator()); an.setRepeatMode(ObjectAnimator.REVERSE); an2.setRepeatMode(ObjectAnimator.REVERSE); an3.setRepeatMode(ObjectAnimator.REVERSE); List<Animator> animatorList = new ArrayList<>(); animatorList.add((Animator) an); animatorList.add((Animator) an2); animatorList.add((Animator) an3); aSet.playSequentially(animatorList); aSet.setInterpolator(new AccelerateDecelerateInterpolator()); aSet.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { count++; if (maxFlashes == INFINITE_FLASHES) { flashTrafficLights(red, amber, green, max, pace); return; } if (count > maxFlashes) { count = 0; return; } flashTrafficLights(red, amber, green, max, pace); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); aSet.start(); } public static void shrink(View view, long duration, final UtilAnimationListener listener) { ObjectAnimator anx = ObjectAnimator.ofFloat(view, "scaleX", 1, 0); ObjectAnimator any = ObjectAnimator.ofFloat(view, "scaleY", 1, 0); anx.setDuration(duration); any.setDuration(duration); anx.setInterpolator(new AccelerateInterpolator()); any.setInterpolator(new AccelerateInterpolator()); AnimatorSet set = new AnimatorSet(); List<Animator> animatorList = new ArrayList<>(); animatorList.add((Animator) anx); animatorList.add((Animator) any); set.playTogether(animatorList); set.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { if (listener != null) listener.onAnimationEnded(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); set.start(); } public static void explode(View view, long duration, final UtilAnimationListener listener) { ObjectAnimator anx = ObjectAnimator.ofFloat(view, "scaleX", 0, 1); ObjectAnimator any = ObjectAnimator.ofFloat(view, "scaleY", 0, 1); anx.setDuration(duration); any.setDuration(duration); anx.setInterpolator(new AccelerateInterpolator()); any.setInterpolator(new AccelerateInterpolator()); AnimatorSet set = new AnimatorSet(); List<Animator> animatorList = new ArrayList<>(); animatorList.add((Animator) anx); animatorList.add((Animator) any); set.playTogether(animatorList); set.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { if (listener != null) listener.onAnimationEnded(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); set.start(); } public static Drawable getRandomHeroImage(Context ctx) { random = new Random(System.currentTimeMillis()); int index = random.nextInt(17); switch (index) { case 0: return ctx.getResources().getDrawable(R.drawable.banner_construction10); case 1: return ctx.getResources().getDrawable( R.drawable.banner_construction3); case 2: return ctx.getResources().getDrawable( R.drawable.banner_construction4); case 3: return ctx.getResources().getDrawable( R.drawable.banner_construction5); case 4: return ctx.getResources().getDrawable( R.drawable.banner_construction5); case 5: return ctx.getResources().getDrawable( R.drawable.banner_construction7); case 6: return ctx.getResources().getDrawable( R.drawable.banner_construction8); case 7: return ctx.getResources().getDrawable( R.drawable.banner_construction9); case 8: return ctx.getResources().getDrawable( R.drawable.banner_construction10); case 9: return ctx.getResources().getDrawable( R.drawable.banner_construction11); case 10: return ctx.getResources().getDrawable( R.drawable.banner_construction13); case 11: return ctx.getResources().getDrawable( R.drawable.banner_construction14); case 12: return ctx.getResources().getDrawable( R.drawable.banner_report); case 13: return ctx.getResources().getDrawable( R.drawable.banner_report3); case 14: return ctx.getResources().getDrawable( R.drawable.banner_report2); case 15: return ctx.getResources().getDrawable( R.drawable.banner_report); case 16: return ctx.getResources().getDrawable( R.drawable.banner_report2); case 17: return ctx.getResources().getDrawable( R.drawable.banner_report3); } return ctx.getResources().getDrawable( R.drawable.banner_report2); } public static void writeLocationToExif(String filePath, Location loc) { try { ExifInterface ef = new ExifInterface(filePath); ef.setAttribute(ExifInterface.TAG_GPS_LATITUDE, decimalToDMS(loc.getLatitude())); ef.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, decimalToDMS(loc.getLongitude())); if (loc.getLatitude() > 0) ef.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, "N"); else ef.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, "S"); if (loc.getLongitude() > 0) ef.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, "E"); else ef.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, "W"); ef.saveAttributes(); Log.e(LOG, "### Exif attributes written to " + filePath); } catch (IOException e) { } } //----------------------------------------------------------------------------------- private static String decimalToDMS(double coord) { coord = coord > 0 ? coord : -coord; // -105.9876543 -> 105.9876543 String sOut = Integer.toString((int) coord) + "/1,"; // 105/1, coord = (coord % 1) * 60; // .987654321 * 60 = 59.259258 sOut = sOut + Integer.toString((int) coord) + "/1,"; // 105/1,59/1, coord = (coord % 1) * 60000; // .259258 * 60000 = 15555 sOut = sOut + Integer.toString((int) coord) + "/1000"; // 105/1,59/1,15555/1000 Log.i(LOG, "decimalToDMS coord: " + coord + " converted to: " + sOut); return sOut; } public static Location getLocationFromExif(String filePath) { String sLat = "", sLatR = "", sLon = "", sLonR = ""; try { ExifInterface ef = new ExifInterface(filePath); sLat = ef.getAttribute(ExifInterface.TAG_GPS_LATITUDE); sLon = ef.getAttribute(ExifInterface.TAG_GPS_LONGITUDE); sLatR = ef.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF); sLonR = ef.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF); } catch (IOException e) { return null; } double lat = DMSToDouble(sLat); if (lat > 180.0) return null; double lon = DMSToDouble(sLon); if (lon > 180.0) return null; lat = sLatR.contains("S") ? -lat : lat; lon = sLonR.contains("W") ? -lon : lon; Location loc = new Location("exif"); loc.setLatitude(lat); loc.setLongitude(lon); Log.i(LOG, "----> File Exif lat: " + loc.getLatitude() + " lng: " + loc.getLongitude()); return loc; } //------------------------------------------------------------------------- private static double DMSToDouble(String sDMS) { double dRV = 999.0; try { String[] DMSs = sDMS.split(",", 3); String s[] = DMSs[0].split("/", 2); dRV = (new Double(s[0]) / new Double(s[1])); s = DMSs[1].split("/", 2); dRV += ((new Double(s[0]) / new Double(s[1])) / 60); s = DMSs[2].split("/", 2); dRV += ((new Double(s[0]) / new Double(s[1])) / 3600); } catch (Exception e) { } return dRV; } public static void refreshProjectData(final Activity activity, final Context ctx, final Integer projectID, final ProjectDataRefreshListener listener) { if (activity == null || ctx == null) { Log.e(LOG, "## activity passed in is null, exit"); return; } Log.i(LOG, "######## refreshProjectData started ...."); RequestDTO w = new RequestDTO(); w.setRequestType(RequestDTO.GET_PROJECT_DATA); w.setProjectID(projectID); WebSocketUtil.sendRequest(ctx, Statics.COMPANY_ENDPOINT, w, new WebSocketUtil.WebSocketListener() { @Override public void onMessage(final ResponseDTO response) { activity.runOnUiThread(new Runnable() { @Override public void run() { if (response.getStatusCode() > 0) { Util.showErrorToast(ctx, response.getMessage()); return; } CacheUtil.cacheProjectData(ctx, response, CacheUtil.CACHE_PROJECT, projectID, new CacheUtil.CacheUtilListener() { @Override public void onFileDataDeserialized(ResponseDTO response) { } @Override public void onDataCached() { listener.onDataRefreshed(response.getProjectList().get(0)); } @Override public void onError() { listener.onError(activity.getString(R.string.unable_project_data)); } }); } }); } @Override public void onClose() { } @Override public void onError(final String message) { activity.runOnUiThread(new Runnable() { @Override public void run() { listener.onError(message); } }); } }); } public static String getTruncated(double num) { String x = "" + num; int idx = x.indexOf("."); String xy = x.substring(idx + 1); if (xy.length() > 2) { String y = x.substring(0, idx + 2); return y; } else { return x; } } public static Intent getMailIntent(Context ctx, String email, String message, String subject, File file) { Intent sendIntent = new Intent(Intent.ACTION_SEND); if (email == null) { sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"", "aubrey.malabie@gmail.com"}); } else { sendIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{email}); } if (subject == null) { sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject); } else { sendIntent.putExtra(Intent.EXTRA_SUBJECT, subject); } sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); sendIntent.putExtra(Intent.EXTRA_TEXT, message); sendIntent.setType("application/pdf"); return sendIntent; } public static double getPercentage(int totalMarks, int attained) { BigDecimal total = new BigDecimal(totalMarks); BigDecimal totStu = new BigDecimal(attained); double perc = totStu.divide(total, 3, BigDecimal.ROUND_UP).doubleValue(); perc = perc * 100; return perc; } public static String formatCellphone(String cellphone) { StringBuilder sb = new StringBuilder(); String suff = cellphone.substring(0, 3); String p1 = cellphone.substring(3, 6); String p2 = cellphone.substring(6); sb.append(suff).append(" "); sb.append(p1).append(" "); sb.append(p2); return sb.toString(); } public static void hide(View view, long duration) { ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 1, 0); ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 1, 0); AnimatorSet animSetXY = new AnimatorSet(); animSetXY.playTogether(scaleX, scaleY); animSetXY.setInterpolator(new AccelerateInterpolator()); animSetXY.setDuration(duration); if (duration == 0) { animSetXY.setDuration(200); } animSetXY.start(); } public static void show(View view, long duration) { ObjectAnimator scaleX = ObjectAnimator.ofFloat(view, "scaleX", 0, 1); ObjectAnimator scaleY = ObjectAnimator.ofFloat(view, "scaleY", 0, 1); AnimatorSet animSetXY = new AnimatorSet(); animSetXY.playTogether(scaleX, scaleY); animSetXY.setInterpolator(new OvershootInterpolator()); animSetXY.setDuration(duration); if (duration == 0) { animSetXY.setDuration(300); } animSetXY.start(); } public static void animateScaleY(View txt, long duration) { final ObjectAnimator an = ObjectAnimator.ofFloat(txt, "scaleY", 0); an.setRepeatCount(1); an.setDuration(duration); an.setRepeatMode(ValueAnimator.REVERSE); an.start(); } public static void animateRotationY(View view, long duration) { final ObjectAnimator an = ObjectAnimator.ofFloat(view, "rotation", 0.0f, 360f); //an.setRepeatCount(ObjectAnimator.REVERSE); an.setDuration(duration); an.setInterpolator(new AccelerateDecelerateInterpolator()); an.start(); } public static void animateRollup(View view, long duration) { final ObjectAnimator an = ObjectAnimator.ofFloat(view, "scaleY", 0.0f); //an.setRepeatCount(ObjectAnimator.REVERSE); an.setDuration(duration); an.setInterpolator(new AccelerateDecelerateInterpolator()); an.start(); } public static void animateSlideRight(View view, long duration) { final ObjectAnimator an = ObjectAnimator.ofFloat( view, "translate", 0, 100, 0, 100); //an.setRepeatCount(ObjectAnimator.REVERSE); an.setDuration(duration); an.setInterpolator(new AccelerateDecelerateInterpolator()); an.start(); } public static void animateFlipFade(Context ctx, View v) { AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(ctx, R.animator.flip_fade); set.setTarget(v); set.start(); } public static ArrayList<String> getRecurStrings(Date date) { Calendar cal = GregorianCalendar.getInstance(); cal.setTime(date); int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); String day = getDayOfWeek(dayOfWeek); boolean isWeekDay = false; if (dayOfWeek > 1 && dayOfWeek < 7) { isWeekDay = true; } Log.d("Util", "#########"); Log.d("Util", "dayOfWeek: " + dayOfWeek + " day: " + day + " isWeekDay: " + isWeekDay); // which week? int week = 0; int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH); if (dayOfMonth < 8) { week = 1; } if (dayOfMonth > 7 && dayOfMonth < 15) { week = 2; } if (dayOfMonth > 14 && dayOfMonth < 22) { week = 3; } if (dayOfMonth > 21) { week = 4; } Log.d("Util", "dayOfMonth: " + dayOfMonth + " week in month: " + getWeekOfMonth(week)); ArrayList<String> list = new ArrayList<String>(); list.add("One time event"); list.add("Daily Event"); list.add("Every Week day(Mon-Fri)"); list.add("Weekly on " + getDayOfWeek(dayOfWeek)); list.add("Monthly (every " + getWeekOfMonth(week) + " " + getDayOfWeek(dayOfWeek)); list.add("Monthly on day " + dayOfMonth); String month = getMonth(cal.get(Calendar.MONTH)); list.add("Yearly on " + dayOfMonth + " " + month); return list; } public static String getMonth(int mth) { switch (mth) { case 0: return "January"; case 1: return "February"; case 2: return "March"; case 3: return "April"; case 4: return "May"; case 5: return "June"; case 6: return "July"; case 7: return "August"; case 8: return "September"; case 9: return "October"; case 10: return "November"; case 11: return "December"; } return null; } public static String getWeekOfMonth(int i) { switch (i) { case 1: return FIRST_WEEK; case 2: return SECOND_WEEK; case 4: return FOURTH_WEEK; case 3: return THIRD_WEEK; } return MONDAY; } public static String getDayOfWeek(int i) { switch (i) { case 2: return MONDAY; case 3: return TUESDAY; case 4: return WEDNESDAY; case 5: return THURSDAY; case 6: return FRIDAY; case 7: return SATURDAY; case 1: return SUNDAY; } return MONDAY; } public static int[] getDateParts(Date date) { Calendar cal = GregorianCalendar.getInstance(); cal.setTime(date); int[] ints = {cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR)}; return ints; } public static File getDirectory(String dir) { File sd = Environment.getExternalStorageDirectory(); File appDir = new File(sd, dir); if (!appDir.exists()) { appDir.mkdir(); } return appDir; } public static String getLongTime(Date date) { SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss"); return df.format(date); } public static String getShortTime(Date date) { SimpleDateFormat df = new SimpleDateFormat("HH:mm"); return df.format(date); } public static int[] getTime(Date date) { SimpleDateFormat df = new SimpleDateFormat("HH"); String hr = df.format(date); df = new SimpleDateFormat("mm"); String min = df.format(date); int[] time = {Integer.parseInt(hr), Integer.parseInt(min)}; return time; } public static long getSimpleDate(Date date) { Calendar cal = GregorianCalendar.getInstance(); cal.setTime(date); cal.set(GregorianCalendar.HOUR_OF_DAY, 0); cal.set(GregorianCalendar.MINUTE, 0); cal.set(GregorianCalendar.SECOND, 0); cal.set(GregorianCalendar.MILLISECOND, 0); return cal.getTimeInMillis(); } public static long getSimpleDate(int day, int month, int year) { Calendar cal = GregorianCalendar.getInstance(); cal.set(GregorianCalendar.YEAR, year); cal.set(GregorianCalendar.MONTH, month); cal.set(GregorianCalendar.DAY_OF_MONTH, day); return getSimpleDate(cal.getTime()); } public static String getLongerDate(int day, int month, int year) { Calendar cal = GregorianCalendar.getInstance(); cal.set(GregorianCalendar.YEAR, year); cal.set(GregorianCalendar.MONTH, month); cal.set(GregorianCalendar.DAY_OF_MONTH, day); Date d = cal.getTime(); SimpleDateFormat df = new SimpleDateFormat("EEEE, dd MMMM, yyyy"); return df.format(d); } public static String getLongDate(int day, int month, int year) { Calendar cal = GregorianCalendar.getInstance(); cal.set(GregorianCalendar.YEAR, year); cal.set(GregorianCalendar.MONTH, month); cal.set(GregorianCalendar.DAY_OF_MONTH, day); Date d = cal.getTime(); SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy"); return df.format(d); } public static String getLongestDate(int day, int month, int year) { Calendar cal = GregorianCalendar.getInstance(); cal.set(GregorianCalendar.YEAR, year); cal.set(GregorianCalendar.MONTH, month); cal.set(GregorianCalendar.DAY_OF_MONTH, day); Date d = cal.getTime(); SimpleDateFormat df = new SimpleDateFormat("EEEE, dd MMM yyyy"); return df.format(d); } public static String getLongDate(Date date) { SimpleDateFormat df = new SimpleDateFormat("EEEE, dd MMM yyyy"); return df.format(date); } public static String getLongerDate(Date date) { SimpleDateFormat df = new SimpleDateFormat("EEEE, dd MMMM yyyy"); return df.format(date); } public static String getLongDateTime(Date date) { SimpleDateFormat df = new SimpleDateFormat( "EEEE, dd MMMM yyyy HH:mm:ss"); return df.format(date); } public static Calendar getLongDateTimeNoSeconds(Calendar cal) { int year = cal.get(Calendar.YEAR); int mth = cal.get(Calendar.MONTH); int day = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); Calendar c = GregorianCalendar.getInstance(); c.set(Calendar.YEAR, year); c.set(Calendar.MONTH, mth); c.set(Calendar.DAY_OF_MONTH, day); c.set(Calendar.HOUR_OF_DAY, hour); c.set(Calendar.MINUTE, minute); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); Log.d("Util", "Reset date: " + getLongDateTimeNoSeconds(c.getTime())); return c; } public static String getLongDateTimeNoSeconds(Date date) { SimpleDateFormat df = new SimpleDateFormat("EEEE, dd MMMM yyyy HH:mm"); return df.format(date); } public static String getLongDateForPDF(long date) { SimpleDateFormat df = new SimpleDateFormat("EEE dd MMM yyyy"); Date d = new Date(date); return df.format(d); } public static String getShortDateForPDF(long startDate, long endDate) { SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy"); Date dtStart = new Date(startDate); Date dtEnd = new Date(endDate); return df.format(dtStart) + " to " + df.format(dtEnd); } public static byte[] scaleImage(Context context, Uri photoUri) throws IOException { InputStream is = context.getContentResolver().openInputStream(photoUri); BitmapFactory.Options dbo = new BitmapFactory.Options(); dbo.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, dbo); is.close(); int rotatedWidth, rotatedHeight; int orientation = getOrientation(context, photoUri); if (orientation == 90 || orientation == 270) { rotatedWidth = dbo.outHeight; rotatedHeight = dbo.outWidth; } else { rotatedWidth = dbo.outWidth; rotatedHeight = dbo.outHeight; } Bitmap srcBitmap; is = context.getContentResolver().openInputStream(photoUri); if (rotatedWidth > MAX_IMAGE_DIMENSION || rotatedHeight > MAX_IMAGE_DIMENSION) { float widthRatio = ((float) rotatedWidth) / ((float) MAX_IMAGE_DIMENSION); float heightRatio = ((float) rotatedHeight) / ((float) MAX_IMAGE_DIMENSION); float maxRatio = Math.max(widthRatio, heightRatio); // Create the bitmap from file BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = (int) maxRatio; srcBitmap = BitmapFactory.decodeStream(is, null, options); } else { srcBitmap = BitmapFactory.decodeStream(is); } is.close(); /* if the orientation is not 0 (or -1, which means we don't know), we * have to do a rotation. */ if (orientation > 0) { Matrix matrix = new Matrix(); matrix.postRotate(orientation); srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true); } String type = context.getContentResolver().getType(photoUri); if (type == null) { type = "image/jpg"; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (type.equals("image/png")) { srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); } else if (type.equals("image/jpg") || type.equals("image/jpeg")) { srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); } byte[] bMapArray = baos.toByteArray(); baos.close(); return bMapArray; } public static int getOrientation(Context context, Uri photoUri) { /* it's on the external media. */ Cursor cursor = context.getContentResolver().query(photoUri, new String[]{MediaStore.Images.ImageColumns.ORIENTATION}, null, null, null); if (cursor == null) { return 1; } if (cursor.getCount() != 1) { return -1; } cursor.moveToFirst(); return cursor.getInt(0); } static public boolean hasStorage(boolean requireWriteAccess) { String state = Environment.getExternalStorageState(); Log.w("Util", "--------- disk storage state is: " + state); if (Environment.MEDIA_MOUNTED.equals(state)) { if (requireWriteAccess) { boolean writable = checkFsWritable(); Log.i("Util", "************ storage is writable: " + writable); return writable; } else { return true; } } else if (!requireWriteAccess && Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { return true; } return false; } private static boolean checkFsWritable() { // Create a temporary file to see whether a volume is really writeable. // It's important not to put it in the root directory which may have a // limit on the number of files. String directoryName = Environment.getExternalStorageDirectory().toString() + "/DCIM"; File directory = new File(directoryName); if (!directory.isDirectory()) { if (!directory.mkdirs()) { return false; } } return directory.canWrite(); } public static List<File> getImportFilesOnSD() { File extDir = Environment.getExternalStorageDirectory(); String state = Environment.getExternalStorageState(); // TODO check thru all state possibilities if (!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) { return new ArrayList<File>(); } ArrayList<File> fileList = new ArrayList<File>(); @SuppressWarnings("unchecked") Iterator<File> iter = FileUtils.iterateFiles(extDir, new String[]{ "csv", "txt"}, true); while (iter.hasNext()) { File file = iter.next(); if (file.getName().startsWith("._")) { continue; } fileList.add(0, file); Log.d(LOG, "### Import File: " + file.getAbsolutePath()); } Log.i(LOG, "### sd Import Files in list : " + fileList.size()); return fileList; } public static List<File> getImportFiles() { File extDir = Environment.getRootDirectory(); String state = Environment.getExternalStorageState(); // TODO check thru all state possibilities if (!state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) { return new ArrayList<File>(); } ArrayList<File> fileList = new ArrayList<File>(); @SuppressWarnings("unchecked") Iterator<File> iter = FileUtils.iterateFiles(extDir, new String[]{ "csv"}, true); while (iter.hasNext()) { File file = iter.next(); if (file.getName().startsWith("._")) { continue; } fileList.add(file); Log.d(LOG, "### disk Import File: " + file.getAbsolutePath()); } Log.i(LOG, "### Import Files in list : " + fileList.size()); return fileList; } public interface UtilAnimationListener { public void onAnimationEnded(); } public interface UtilPopupListener { public void onItemSelected(int index); } public interface ProjectDataRefreshListener { public void onDataRefreshed(ProjectDTO project); public void onError(String message); } }
package RestAssuredSameResponseAsJsonKeycloak; import org.junit.Test; import static io.restassured.RestAssured.given; public class RestAssuredSameResponseAsJsonKeycloakTest extends AbstractRestAssuredSameResponseAsJsonKeycloakTest { @Test public void getListOfRealms() { given(). when(). get("/admin/realms"). then(). spec(store.getLogSpec()). assertThat(). statusCode(200); assertJson.sameJsonAs(); } @Test public void getListOfRolesInMasterRealm() { given(). when(). get("/admin/realms/{realm}/roles", kc.get("realm")). then(). spec(store.getLogSpec()). assertThat(). statusCode(200); assertJson.sameJsonAs(); } @Test public void getListofUsersInMasterRealm() { given(). when(). get("/admin/realms/{realm}/users", kc.get("realm")). then(). spec(store.getLogSpec()). assertThat(). statusCode(200); assertJson.sameJsonAs(); } }
package com.dental.lab.security; import java.util.Collection; import java.util.stream.Collectors; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import com.dental.lab.data.Entities.UserEntity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Builder @Getter @Setter @NoArgsConstructor @AllArgsConstructor @ToString public class UserDetailsImpl implements UserDetails { /** * */ private static final long serialVersionUID = 1L; private Long id; private String username; private String password; private String email; private Collection<GrantedAuthority> authorities; public static UserDetailsImpl build(UserEntity user) { Collection<GrantedAuthority> authorities = user.getAuthorities().stream() .map(authority -> new SimpleGrantedAuthority(authority.getRole().toString())) .collect(Collectors.toSet()); return UserDetailsImpl.builder() .id(user.getId()) .username(user.getUsername()) .password(user.getPassword()) .email(user.getEmail()) .authorities(authorities) .build(); } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return this.authorities; } @Override public String getPassword() { return this.password; } @Override public String getUsername() { return this.username; } @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
package com.alium.ic.domains; // Generated 2013-06-19 17:36:03 by Hibernate Tools 3.4.0.CR1 import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * ObiektOsobaNiefiz generated by hbm2java */ @Entity @Table(name = "obiekt_osoba_niefiz", catalog = "finalna") public class ObiektOsobaNiefiz implements java.io.Serializable { private Integer id; private SlowMiasto slowMiasto; private SlowWojewodztwo slowWojewodztwo; private SlowPanstwo slowKraj; private String nazwa; private String regon; private String nip; private String przedrostek; private String ulica; private String nrLokal; private String nrKontoB; private boolean przetwMarket; private String nrTelefon; private String kodPoczt; private Date wd; private String op; public ObiektOsobaNiefiz() { } public ObiektOsobaNiefiz(SlowMiasto slowMiasto, SlowWojewodztwo slowWojewodztwo, SlowPanstwo slowKraj, String nazwa, String regon, String nip, String ulica, String nrKontoB, boolean przetwMarket, String nrTelefon, String kodPoczt, Date wd, String op) { this.slowMiasto = slowMiasto; this.slowWojewodztwo = slowWojewodztwo; this.slowKraj = slowKraj; this.nazwa = nazwa; this.regon = regon; this.nip = nip; this.ulica = ulica; this.nrKontoB = nrKontoB; this.przetwMarket = przetwMarket; this.nrTelefon = nrTelefon; this.kodPoczt = kodPoczt; this.wd = wd; this.op = op; } public ObiektOsobaNiefiz(SlowMiasto slowMiasto, SlowWojewodztwo slowWojewodztwo, SlowPanstwo slowKraj, String nazwa, String regon, String nip, String przedrostek, String ulica, String nrLokal, String nrKontoB, boolean przetwMarket, String nrTelefon, String kodPoczt, Date wd, String op) { this.slowMiasto = slowMiasto; this.slowWojewodztwo = slowWojewodztwo; this.slowKraj = slowKraj; this.nazwa = nazwa; this.regon = regon; this.nip = nip; this.przedrostek = przedrostek; this.ulica = ulica; this.nrLokal = nrLokal; this.nrKontoB = nrKontoB; this.przetwMarket = przetwMarket; this.nrTelefon = nrTelefon; this.kodPoczt = kodPoczt; this.wd = wd; this.op = op; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true, nullable = false) public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_miasto", nullable = false) public SlowMiasto getSlowMiasto() { return this.slowMiasto; } public void setSlowMiasto(SlowMiasto slowMiasto) { this.slowMiasto = slowMiasto; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_woj", nullable = false) public SlowWojewodztwo getSlowWojewodztwo() { return this.slowWojewodztwo; } public void setSlowWojewodztwo(SlowWojewodztwo slowWojewodztwo) { this.slowWojewodztwo = slowWojewodztwo; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "id_kraj", nullable = false) public SlowPanstwo getSlowKraj() { return this.slowKraj; } public void setSlowKraj(SlowPanstwo slowKraj) { this.slowKraj = slowKraj; } @Column(name = "nazwa", nullable = false) public String getNazwa() { return this.nazwa; } public void setNazwa(String nazwa) { this.nazwa = nazwa; } @Column(name = "regon", nullable = false, length = 14) public String getRegon() { return this.regon; } public void setRegon(String regon) { this.regon = regon; } @Column(name = "nip", nullable = false, length = 10) public String getNip() { return this.nip; } public void setNip(String nip) { this.nip = nip; } @Column(name = "przedrostek", length = 3) public String getPrzedrostek() { return this.przedrostek; } public void setPrzedrostek(String przedrostek) { this.przedrostek = przedrostek; } @Column(name = "ulica", nullable = false) public String getUlica() { return this.ulica; } public void setUlica(String ulica) { this.ulica = ulica; } @Column(name = "nr_lokal", length = 20) public String getNrLokal() { return this.nrLokal; } public void setNrLokal(String nrLokal) { this.nrLokal = nrLokal; } @Column(name = "nr_konto_b", nullable = false, length = 28) public String getNrKontoB() { return this.nrKontoB; } public void setNrKontoB(String nrKontoB) { this.nrKontoB = nrKontoB; } @Column(name = "przetw_market", nullable = false) public boolean isPrzetwMarket() { return this.przetwMarket; } public void setPrzetwMarket(boolean przetwMarket) { this.przetwMarket = przetwMarket; } @Column(name = "nr_telefon", nullable = false, length = 20) public String getNrTelefon() { return this.nrTelefon; } public void setNrTelefon(String nrTelefon) { this.nrTelefon = nrTelefon; } @Column(name = "kod_poczt", nullable = false, length = 10) public String getKodPoczt() { return this.kodPoczt; } public void setKodPoczt(String kodPoczt) { this.kodPoczt = kodPoczt; } @Temporal(TemporalType.TIMESTAMP) @Column(name = "wd", nullable = false, length = 19) public Date getWd() { return this.wd; } public void setWd(Date wd) { this.wd = wd; } @Column(name = "op", nullable = false, length = 30) public String getOp() { return this.op; } public void setOp(String op) { this.op = op; } }
package sample; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextField; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; public class Controller { private boolean hasComma = false; private double val = 0.0; private double result = 0.0; private char operator = ' '; private boolean clearText = true; private DecimalFormat df = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance() ); private double getCalcTxtVal() { double dval; try { dval = df.parse(calcTxt.getText()).doubleValue(); } catch (ParseException e) { return 0; } return dval; } private double calcResult() { switch(operator) { case ' ': return getCalcTxtVal(); case '+': return val + getCalcTxtVal(); case '-': return val - getCalcTxtVal(); case '*': return val * getCalcTxtVal(); case '/': double temp = getCalcTxtVal(); if(temp != 0) return val / temp; break; } return 0; } @FXML private TextField calcTxt; @FXML protected void numButtonPressed(ActionEvent event) { Button btn = (Button) event.getSource(); if(clearText) { calcTxt.setText(""); clearText = false; } calcTxt.setText(calcTxt.getText() + btn.getId().substring(btn.getId().length()-1)); } @FXML protected void commaButtonPressed(ActionEvent event) { if(!hasComma) { if(clearText) calcTxt.setText("0"); calcTxt.setText(calcTxt.getText() + ","); hasComma = true; clearText = false; } } @FXML protected void clearButtonPressed(ActionEvent event) { calcTxt.setText("0"); hasComma = false; clearText = true; } @FXML protected void clearAllButtonPressed(ActionEvent event) { calcTxt.setText("0"); hasComma = false; clearText = true; val = 0.0; result = 0.0; } @FXML protected void delButtonPressed(ActionEvent event) { } @FXML protected void addButtonPressed(ActionEvent event) { val = calcResult(); operator = '+'; clearText = true; hasComma = false; } @FXML protected void subButtonPressed(ActionEvent event) { val = calcResult(); operator = '-'; clearText = true; hasComma = false; } @FXML protected void divButtonPressed(ActionEvent event) { val = calcResult(); operator = '/'; clearText = true; hasComma = false; } @FXML protected void mulButtonPressed(ActionEvent event) { val = calcResult(); operator = '*'; clearText = true; hasComma = false; } @FXML protected void pow2ButtonPressed(ActionEvent event) { val = getCalcTxtVal(); clearText = true; } @FXML protected void sqrtButtonPressed(ActionEvent event) { val = getCalcTxtVal(); clearText = true; } @FXML protected void pos_negButtonPressed(ActionEvent event) { } @FXML protected void equalButtonPressed(ActionEvent event) { calcTxt.setText(df.format(calcResult())); clearText = true; hasComma = false; } }
package com.chaabane.jasperlog.controllers; import com.chaabane.jasperlog.Company; import com.chaabane.jasperlog.JasperlogApplication; import com.chaabane.jasperlog.services.CompanyRepo; import com.chaabane.jasperlog.services.ReportService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/") public class AppRestPoint { @Autowired CompanyRepo companyRepo; @Autowired ReportService reportService; Logger logger = LoggerFactory.getLogger(JasperlogApplication.class); @GetMapping("/companies") public List<Company> loadCompanies(){ logger.trace("/companies enpoint is triggered !"); return companyRepo.findAll(); } @GetMapping("/report/{companyId}") public ResponseEntity<byte[]> loadCompanies(@PathVariable Long companyId) { logger.trace("/report/{companyId} enpoint is triggered !"); try { byte[] contents = reportService.exportReport(companyId); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF); // Here you have to set the actual filename of your pdf String filename = "output.pdf"; headers.setContentDispositionFormData(filename, filename); headers.setCacheControl("must-revalidate, post-check=0, pre-check=0"); ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK); return response; } catch (Exception e) { logger.debug(e.getMessage()); return new ResponseEntity<>(null, null, HttpStatus.INTERNAL_SERVER_ERROR); } } }
package BO.customer; import DAO.customer.CustomerTypeDAO; import model.CustomerType; import java.util.ArrayList; public class CustomerTypeBO implements ICustomerTypeBO{ CustomerTypeDAO customerTypeDAO = new CustomerTypeDAO(); @Override public ArrayList<CustomerType> getAllCustomerType() { return customerTypeDAO.getAllCustomerType(); } }
package com.trs.om.auth.api; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import org.apache.log4j.Logger; import com.trs.om.rbac.AuthorizationException; import com.trs.om.rbac.ISessionManager; import com.trs.om.common.ObjectContainer; @Path("auth") @Produces("application/*") public class AuthResource { private static final Logger logger = Logger.getLogger(AuthResource.class); private ISessionManager sessionManager = (ISessionManager) ObjectContainer.getBean("sessionManager"); @GET @Path("/add") public String addBatchNewSession(@QueryParam("roleId") int roleId){ Long role_id = (long) roleId; try { sessionManager.addBatchNewSession(role_id); } catch (AuthorizationException e) { e.printStackTrace(); logger.debug("添加失败,"+e.getMessage()); } return "添加成功"; } }
package de.jmda.app.uml.advertise; public interface SpareTimeProject { }
package com.gohool.firstlook.tipcalculator; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.SeekBar; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private EditText input; private SeekBar seek; private Button okay; private TextView output; private double percent; private double tip; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); input = findViewById(R.id.inpID); seek = findViewById(R.id.seekBarID); okay = findViewById(R.id.doneID); output = findViewById(R.id.finalID); seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { Log.d("SB","OnStopTracking"); if (seekBar.getProgress() == 0) { output.setText("no tip?"); //percent = 0.10; } else if (seekBar.getProgress() == 1) { output.setText("10 percent?"); percent = 0.10; } else if (seekBar.getProgress() == 2) { output.setText("15 percent?"); percent = 0.15; } else { output.setText("20 percent?"); percent = 0.20; } } }); okay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { double cost = Double.parseDouble(input.getText().toString()); tip = percent * cost; output.setText(String.format("$" + "%.2f",tip)); } }); } }
package ArraysJavaListsAutoboxingUnboxing.Autoboxing.Challenge; import java.lang.reflect.Array; import java.util.ArrayList; public class Customer { private String name; private ArrayList<Double> transactions; public Customer(String name, double initialAmount) { this.name = name; this.transactions = new ArrayList<>(); if (addTransaction(initialAmount)) { System.out.println("Initial transaction successfully added."); } } public Customer(String name) { this(name, 0.0d); } boolean addTransaction(double amount) { if (amount > 0.0d) { this.transactions.add(amount); return true; } System.out.println("Couldn't add declared amount, must be greater than 0."); return false; } public String getName() { return name; } ArrayList<Double> getTransactions() { return transactions; } }
package javatest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ReadLine { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); System.out.print("請輸入一列文字,可包括空白: "); String text = bufferedReader.readLine(); System.out.println("輸入的文字: " + text); } }
package mouse.server.network; import mouse.server.ServerConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.*; import java.util.TimerTask; /** * User: Simon * Date: 26.03.14 */ public class BroadcastTask extends TimerTask { private static final Logger log = LoggerFactory.getLogger(BroadcastTask.class); private final ServerConfiguration serverConfiguration; private DatagramSocket socket; private byte[] message; private InetAddress groupAddress; private DatagramPacket packet; public BroadcastTask(ServerConfiguration serverConfiguration) { this.serverConfiguration = serverConfiguration; initialize(); } private void initialize() { log.debug("Initializing multicast task for broadcasting the server address."); try { socket = new DatagramSocket(serverConfiguration.getMulticastListenPort()); } catch (SocketException ex) { log.error("Unable to create multicast socket.", ex); } try { message = Inet4Address.getLocalHost().getHostAddress().getBytes(); groupAddress = InetAddress.getByName(serverConfiguration.getMulticastAddress()); } catch (UnknownHostException ex) { log.error("Unable to retrieve address.", ex); } packet = new DatagramPacket(message, message.length, groupAddress, serverConfiguration.getMulticastPort()); } @Override public void run() { try { socket.send(packet); } catch (IOException ex) { log.error("Unable to send broadcast.", ex); } } public void closeSocket() { socket.close(); } public String getSentAddress() { return new String(message); } }
package com.java8.optional; import lombok.Data; import java.util.Optional; /** * @Author 樊东方 * @Date 2020/9/4 2:09 下午 * @Description */ @Data public class Car { /** * 车可能上了保险,也可能没上保险 */ private Optional<Insurance> insurance; }
package com.SkyBlue.base.to; import com.SkyBlue.common.annotation.Dataset; import com.SkyBlue.common.to.BaseBean; import lombok.Getter; import lombok.Setter; @Dataset(name="dsOpenApi") public class OpenApiBean extends BaseBean{ @Setter @Getter private String fdPrdtNm,atcId,mdcd,fdFilePathImg,fdYmd,depPlace,fdSbjt; }
package com.carousell.marketplace.service; import com.carousell.marketplace.dao.User; /** * @author faizanmalik * creation date 3/4/20 */ public interface UserService { User registerUser(String username); User getUser(String username); }
package rhtn_homework; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; public class cheetsheet { private static int[] arr = {1,2,3,4}; private static boolean[] visited; private static int R = 2; private static int[] result; public static ArrayList<Integer> list = new ArrayList<>(); public static void main(String[] args) { result = new int[R]; visited = new boolean[arr.length]; nPr(0); System.out.println(); nPrSwap(0); System.out.println(); //System.out.println(Arrays.toString(arr)); Arrays.sort(arr); NP(); Arrays.sort(arr); System.out.println(); nCr(0,0); result = new int[R]; System.out.println(); nCrDef(4,2); System.out.println(); subSetBit(); System.out.println(); subSetList(0,0); visited = new boolean[arr.length]; subSetRecursion(0); } private static void subSetRecursion(int i) { if(i == arr.length) { print(); return; } visited[i] = false; subSetRecursion(i+1); visited[i] = true; subSetRecursion(i+1); } private static void print() { for (int i = 0; i < visited.length; i++) { if(visited[i]){ System.out.print(arr[i] + " "); } } System.out.println(); } private static void subSetList(int d, int r) { System.out.println(list); if(r == arr.length) return; for (int i = d; i < arr.length; i++) { list.add(arr[i]); subSetList(i+1, r+1); list.remove(list.size()-1); } } private static void subSetBit() { for (int i = 0; i < 1<<arr.length; i++) { List<Integer> list = new LinkedList<>(); for (int j = 0; j < arr.length; j++) { if((i & (1<<j)) > 0) list.add(arr[j]); } System.out.println(list); } } private static void nCrDef(int n, int r) { if(r == 0) { System.out.println(Arrays.toString(result)); return; }else if(n<r) { return; }else { result[r-1] = arr[n-1]; nCrDef(n-1,r-1); nCrDef(n-1,r); } } private static void nCr(int d, int r) { if(r == R) { System.out.println(Arrays.toString(result)); return; } for (int i = d; i < arr.length; i++) { result[r] = arr[i]; nCr(i+1,r+1); } } private static void NP() { do { System.out.println(Arrays.toString(arr)); }while(nPrNP()); } private static boolean nPrNP() { int i = 0; for (i = arr.length-2; i >=0 ; i--) { if(arr[i+1]>arr[i]) break; } if(i==-1) return false; int j = 0; for (j = arr.length-1; j >=0 ; j--) { if(arr[j]>arr[i]) break; } swap(i,j); for (int a = i+1, b = arr.length-1 ; a < b; a++, b--) { swap(a,b); } return true; } private static void nPrSwap(int r) { if(r == R) { System.out.println(Arrays.toString(Arrays.copyOfRange(arr, 0, R))); return; } for (int i = r; i < arr.length; i++) { swap(i,r); nPrSwap(r+1); swap(i,r); } } public static void swap(int a, int b) { int tmp = arr[a]; arr[a] = arr[b]; arr[b] = tmp; } public static void nPr(int r) { if(r == R) { System.out.println(Arrays.toString(result)); return; } for (int i = 0; i < arr.length; i++) { if(!visited[i]) { result[r] = arr[i]; visited[i] = true; nPr(r+1); visited[i] = false; } } } }
package com.pskwiercz; import org.junit.Test; import org.omg.CORBA.PUBLIC_MEMBER; import static org.junit.Assert.*; /** * Created by pskwierc on 28/12/2016. */ public class MoneyTest { @Test public void testSimpleAddtion() { Bank bank = new Bank(); Money five = Money.dollar(5); Expression sum = five.plus(five); Money reduced = bank.reduce(sum, "USD"); assertEquals(Money.dollar(10), reduced); } @Test public void testPlusReturnsSum() { Money five = Money.dollar(5); Expression result = five.plus(five); Sum sum = (Sum) result; assertEquals(five, sum.augend); assertEquals(five, sum.addend); } @Test public void testReduceSum() { Expression sum = new Sum(Money.dollar(3), Money.dollar(4)); Bank bank = new Bank(); bank.addRate("CHF", "USD", 2); Money result = bank.reduce(sum, "USD"); assertEquals(Money.dollar(7), result); } @Test public void testReduceMoney() { Bank bank = new Bank(); Money result = bank.reduce(Money.dollar(1), "USD"); assertEquals(Money.dollar(1), result); } @Test public void testReduceMoneyDiffCurrency() { Bank bank = new Bank(); bank.addRate("CHF", "USD", 2); Money result = bank.reduce(Money.franc(2), "USD"); assertEquals(Money.dollar(1), result); } @Test public void testIdentityRate() { assertEquals(1, new Bank().rate("USD", "USD")); } @Test public void testMixedAddition() { Expression fiveBucks = Money.dollar(5); Expression tenFrancs = Money.franc(10); Bank bank = new Bank(); bank.addRate("CHF", "USD", 2); Money result = bank.reduce(fiveBucks.plus(tenFrancs), "USD"); assertEquals(Money.dollar(10), result); } @Test public void testSumPlusMoney() { Expression fiveBucks = Money.dollar(5); Expression tenFrancs = Money.franc(10); Bank bank = new Bank(); bank.addRate("CHF", "USD", 2); Expression sum = new Sum(fiveBucks, fiveBucks.plus(tenFrancs)); Money result = bank.reduce(sum, "USD"); assertEquals(Money.dollar(15), result); } @Test public void testSumTimes() { Expression fiveBucks = Money.dollar(5); Expression tenFrancs = Money.franc(10); Bank bank = new Bank(); bank.addRate("CHF", "USD", 2); Expression sum = new Sum(fiveBucks, tenFrancs).times(2); Money result = bank.reduce(sum, "USD"); assertEquals(Money.dollar(20), result); } }
package com.devweb.trans.model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.EqualsAndHashCode; import javax.persistence.*; import java.util.Date; @Entity @Table @Data @EqualsAndHashCode(exclude = "depot") public class Depot { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private Long montant; private Date date; @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) @JoinColumn private Compte compte; @JsonIgnore @ManyToOne(fetch = FetchType.LAZY) @JoinColumn private User caissier; public Compte getCompte() { return compte; } public void setCompte(Compte compte) { this.compte = compte; } public User getCaissier() { return caissier; } public void setCaissier(User caissier) { this.caissier = caissier; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Long getMontant() { return montant; } public void setMontant(Long montant) { this.montant = montant; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
package com.dave.project.wedjet.fresh.api; import android.content.Context; /** * 默认Header创建器 * Created by SCWANG on 2017/5/26. */ public interface DefaultRefreshHeaderCreater { RefreshHeader createRefreshHeader(Context context, RefreshLayout layout); }
package UI.panel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Event; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import com.sun.org.apache.bcel.internal.generic.NEW; import NetworkUtils.CollectionUtils; import NetworkUtils.Sniffer; import UI.AppMainWindow; import UI.ConstantsUI; import UI.MyLabel; import UI.MycomboBox; import UI.Chart.DeviceTable; import javafx.scene.control.ComboBox; import jpcap.JpcapCaptor; import jpcap.NetworkInterface; public class DevicesPanel extends JPanel{ private JPanel upPanel; private JPanel downPanel; private JLabel devicesMenu; private JComboBox<NetworkInterface> devicesCombox; private DeviceTable deviceDetail; private GridBagLayout layout; private NetworkInterface nowInterface; private NetworkInterface[] networkInters; public DevicesPanel() { super(); } public DevicesPanel(NetworkInterface[] networkInters) throws Exception { super(); this.networkInters = networkInters; initialize(); addComponent(networkInters[0]); addListener(); setVisible(true); } private void initialize() throws Exception { layout = new GridBagLayout(); setLayout(layout); upPanel = new JPanel(); downPanel = new JPanel(); devicesMenu = new JLabel("Interface:"); devicesCombox = new JComboBox<NetworkInterface>(); deviceDetail = new DeviceTable(); upPanel.setBackground(ConstantsUI.MAIN_BACK_COLOR); upPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK)); downPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK)); for (NetworkInterface p : networkInters) { devicesCombox.addItem(p); } } private void addComponent(NetworkInterface n) { addComponentInUpPanel(); addComponentInDownPanel(n); add(upPanel); add(downPanel); setComponentPosition(upPanel, 0, 1, 1, 0.05, layout); setComponentPosition(downPanel, 0, 1, 1, 1, layout); } private void setComponentPosition(JComponent component, int gridwidth, int gridheight, double weightx, double weighty, GridBagLayout layout) { GridBagConstraints s = new GridBagConstraints(); s.fill = GridBagConstraints.BOTH; s.gridwidth = gridwidth; s.weightx = weightx; s.weighty = weighty; layout.setConstraints(component, s); } private void addComponentInUpPanel() { GridBagLayout layout = new GridBagLayout(); upPanel.setLayout(layout); upPanel.add(devicesMenu); upPanel.add(devicesCombox); setComponentPosition(devicesMenu, 1, 0, 0, 0, layout); setComponentPosition(devicesCombox, 0, 0, 0, 0, layout); upPanel.setVisible(true); } private void addComponentInDownPanel(NetworkInterface n) { deviceDetail = new DeviceTable(n); downPanel.setLayout(new BorderLayout()); downPanel.add(deviceDetail, BorderLayout.CENTER); downPanel.setVisible(true); } private class itemListener implements ItemListener { public void itemStateChanged(ItemEvent e) { switch (e.getStateChange()) { case ItemEvent.SELECTED: System.out.println("c: " + e.getItem()); remove(); addComponent((NetworkInterface) e.getItem()); AppMainWindow.nowNetInter = (NetworkInterface) e.getItem(); AppMainWindow.comboB.reflesh(); AppMainWindow.devicesPanel.add(AppMainWindow.comboBox); validate(); break; case ItemEvent.DESELECTED: System.out.println("u: " + e.getItem()); break; } } } private void addListener() { devicesCombox.addItemListener(new itemListener()); } private void remove() { upPanel.removeAll(); downPanel.removeAll(); removeAll(); } }
/** * Classe com variáveis estáticas úteis, para fácil configuração. */ package client; public class Universal { public static String host = "localhost"; // endereço do servidor }