text
stringlengths
10
2.72M
/* * Copyright 2014 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.openrtb.snippet; import com.google.common.collect.ImmutableMap; /** * OpenRTB 4.6: Standard OpenRTB macros. * * <p>All {@code Bid} properties of type String can use macros. * Important notes about macro expansion: * * <ul><li>All properties can safely use macros that refer to values from the request: * {@code AUCTION_ID, AUCTION_CURRENCY, AUCTION_IMP_ID, AUCTION_SEAT_ID}.</li> * <li>All properties can also safely use macros that refer to properties that have * non-String type, so they cannot contain macros: {@code AUCTION_PRICE}. * <li>Properties are processed in two stages. The first stage resolves properties that can * contain macros AND feed other macros; {@code adid => AUCTION_AD_ID, id => AUCTION_BID_ID} * are currently the only items in this group. In the second stage, we process the * properties that support macros but don't provide values for any macro, which are: * {@code adm}, {@code cid}, {@code crid}, {@code dealid}, {@code iurl}, {@code nurl}.</li> * <li>Notice that {code impid} is expected to be set to {@code AUCTION_IMP_ID}; you can * use the macro or set the value manually but in the latter case they should match. * All other properties that use the macro {@code AUCTION_IMP_ID} will resolve that * to the bid's {code Imp.id}, not to the bid's own {code impid} property.</li> * </ul> */ public enum OpenRtbMacros implements SnippetMacroType { /** * ID of the ad markup the bid wishes to serve; from "adid" attribute. */ AUCTION_AD_ID("${AUCTION_AD_ID}"), /** * ID of the bid; from "bidid" attribute. */ AUCTION_BID_ID("${AUCTION_BID_ID}"), /** * The currency used in the bid (explicit or implied); for confirmation only. * <p>WARNING: May not be supported by all exchanges. */ AUCTION_CURRENCY("${AUCTION_CURRENCY}"), /** * ID of the bid request; from "id" attribute. */ AUCTION_ID("${AUCTION_ID}"), /** * ID of the impression just won; from "impid" attribute. * <p>WARNING: May not be supported by all exchanges. */ AUCTION_IMP_ID("${AUCTION_IMP_ID}"), /** * Settlement price using the same currency and units as the bid. * <p>WARNING: May not be supported by all exchanges. */ AUCTION_PRICE("${AUCTION_PRICE}"), /** * ID of the bidder's seat for whom the bid was made. */ AUCTION_SEAT_ID("${AUCTION_SEAT_ID}"), /** * Loss reason codes, for loss notices. * <p>WARNING: May not be supported by all exchanges. */ AUCTION_LOSS("${AUCTION_LOSS}"), /** * Market Bid Ratio, defined as: (clearance price / bid price). * <p>WARNING: May not be supported by all exchanges. */ AUCTION_MBR("${AUCTION_MBR}"), ; private static final ImmutableMap<String, OpenRtbMacros> LOOKUP_KEY; static { ImmutableMap.Builder<String, OpenRtbMacros> builder = ImmutableMap.builder(); for (OpenRtbMacros snippetMacro : values()) { builder.put(snippetMacro.key, snippetMacro); } LOOKUP_KEY = builder.build(); } private final String key; private OpenRtbMacros(String key) { this.key = key; } /** * Returns the key for this macro (string that will be substituted when the macro is processed). */ @Override public final String key() { return key; } /** * @return {@link OpenRtbMacros} instance by key name */ public static OpenRtbMacros valueOfKey(String key) { return LOOKUP_KEY.get(key); } }
package com.tencent.mm.plugin.appbrand.jsapi.audio; import com.tencent.mm.plugin.appbrand.e; import com.tencent.mm.plugin.appbrand.e$c; import com.tencent.mm.plugin.appbrand.e.b; import com.tencent.mm.plugin.appbrand.jsapi.audio.d.a; import com.tencent.mm.sdk.platformtools.x; class d$1 extends b { final /* synthetic */ String bAj; final /* synthetic */ d fHV; d$1(d dVar, String str) { this.fHV = dVar; this.bAj = str; } public final void onCreate() { d.fHU = true; } public final void onResume() { d.fHU = true; } public final void a(e$c e_c) { x.i("MicroMsg.Audio.JsApiCreateAudioInstance", "onPause, appId:%s", new Object[]{this.bAj}); d.fHU = false; a aVar = new a(); aVar.bWA = 1; aVar.appId = this.bAj; aVar.ahT(); } public final void onDestroy() { x.i("MicroMsg.Audio.JsApiCreateAudioInstance", "onDestroy, appId:%s", new Object[]{this.bAj}); d.fHU = false; a aVar = new a(); aVar.bWA = 2; aVar.appId = this.bAj; aVar.ahU(); e.b(this.bAj, this); d.ahX().remove(this.bAj); } }
/* * LumaQQ - Java QQ Client * * Copyright (C) 2004 luma <stubma@163.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package edu.tsinghua.lumaqq.ui.wizard.cluster; import java.util.ArrayList; import java.util.List; import edu.tsinghua.lumaqq.models.Cluster; import edu.tsinghua.lumaqq.models.User; import edu.tsinghua.lumaqq.qq.QQ; /** * 向导内数据的封装bean * * @author luma */ public class ClusterWizardModel { // 群类型 public static final int PERMANENT_CLUSTER = 0; public static final int DIALOG = 1; public static final int SUBJECT = 2; // 页名称 public static final String PAGE_CREATE_WHAT = "1"; public static final String PAGE_PERMANENT_CLUSTER_INFO = "2"; public static final String PAGE_TEMP_CLUSTER_INFO = "3"; public static final String PAGE_MEMBER_SELECT = "4"; public static final String PAGE_CREATE = "5"; private int clusterType; private String startingPage; private byte authType; private int category; private String name; private String description; private String notice; private Cluster parentCluster; private List<User> members; /** * 构造函数 */ public ClusterWizardModel() { clusterType = PERMANENT_CLUSTER; startingPage = PAGE_CREATE_WHAT; authType = QQ.QQ_AUTH_CLUSTER_NEED; category = 0; name = description = notice = ""; parentCluster = null; members = new ArrayList<User>(); } public List<Integer> getMemberQQArray() { List<Integer> temp = new ArrayList<Integer>(); for(User u : members) temp.add(u.qq); return temp; } public void removeAllMember() { members.clear(); } public void addMember(User member) { if(!members.contains(member)) members.add(member); } public void removeMember(User member) { members.remove(member); } public int getParentClusterId() { return (parentCluster == null) ? 0 : parentCluster.clusterId; } /** * @return Returns the clusterType. */ public int getClusterType() { return clusterType; } /** * @param clusterType The clusterType to set. */ public void setClusterType(int clusterType) { this.clusterType = clusterType; } /** * @return Returns the startingPage. */ public String getStartingPage() { return startingPage; } /** * @param startingPage The startingPage to set. */ public void setStartingPage(String startingPage) { this.startingPage = startingPage; } /** * @return Returns the authType. */ public byte getAuthType() { return authType; } /** * @param authType The authType to set. */ public void setAuthType(byte authType) { this.authType = authType; } /** * @return Returns the category. */ public int getCategory() { return category; } /** * @param category The category to set. */ public void setCategory(int category) { this.category = category; } /** * @return Returns the description. */ public String getDescription() { return description; } /** * @param description The description to set. */ public void setDescription(String description) { this.description = description; } /** * @return Returns the name. */ public String getName() { return name; } /** * @param name The name to set. */ public void setName(String name) { this.name = name; } /** * @return Returns the notice. */ public String getNotice() { return notice; } /** * @param notice The notice to set. */ public void setNotice(String notice) { this.notice = notice; } /** * @return Returns the parentCluster. */ public Cluster getParentCluster() { return parentCluster; } /** * @param parentCluster The parentCluster to set. */ public void setParentCluster(Cluster parentCluster) { this.parentCluster = parentCluster; } /** * @return Returns the members. */ public List<User> getMembers() { return members; } /** * @param members The members to set. */ public void setMembers(List<User> members) { this.members = members; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * PostPaymentHelper.java * * Created on Sep 7, 2009, 3:07:59 AM */ package legaltime.view; import java.awt.event.ActionEvent; import java.text.ParseException; import javax.swing.JOptionPane; import legaltime.AppPrefs; import legaltime.cache.ClientCache; import legaltime.controller.PaymentLogController; import legaltime.model.ClientBean; import legaltime.modelsafe.EasyLog; import legaltime.view.model.ClientComboBoxModel; import legaltime.view.renderer.ClientComboBoxRenderer; /** * * @author bmartin */ public class PostPaymentHelper extends javax.swing.JDialog implements java.awt.event.ActionListener { private boolean selectionConfirmed; ClientComboBoxModel clientComboBoxModel; ClientComboBoxRenderer clientComboBoxRenderer; EasyLog easyLog; AppPrefs appPrefs; public PostPaymentHelper(javax.swing.JFrame owner) { super(owner, true); appPrefs = AppPrefs.getInstance(); initComponents(); easyLog = EasyLog.getInstance(); selectionConfirmed = false; clientComboBoxModel = new ClientComboBoxModel(); clientComboBoxRenderer = new ClientComboBoxRenderer(); clientComboBoxModel.setList(ClientCache.getInstance().getCache()); cboClient.setModel(clientComboBoxModel); cboClient.setRenderer(clientComboBoxRenderer ); cboClient.setMaximumRowCount(Integer.parseInt(appPrefs.getValue(AppPrefs.CLIENTCBO_DISPLAY_ROWS))); cmdAddPayment.addActionListener(this); cmdCancel.addActionListener(this); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { cboClient = new javax.swing.JComboBox(); lblClient = new javax.swing.JLabel(); cmdAddPayment = new javax.swing.JButton(); dtcEffectiveDate = new com.toedter.calendar.JDateChooser(); lblEffectiveDate = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); txtPaymentAmount = new javax.swing.JTextField(); cmdCancel = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.HIDE_ON_CLOSE); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(legaltime.LegalTimeApp.class).getContext().getResourceMap(PostPaymentHelper.class); setTitle(resourceMap.getString("Form.title")); // NOI18N setName("Form"); // NOI18N cboClient.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); cboClient.setName("cboClient"); // NOI18N lblClient.setText(resourceMap.getString("lblClient.text")); // NOI18N lblClient.setName("lblClient"); // NOI18N cmdAddPayment.setText(resourceMap.getString("cmdAddPayment.text")); // NOI18N cmdAddPayment.setName("cmdAddPayment"); // NOI18N dtcEffectiveDate.setName("dtcEffectiveDate"); // NOI18N lblEffectiveDate.setText(resourceMap.getString("lblEffectiveDate.text")); // NOI18N lblEffectiveDate.setName("lblEffectiveDate"); // NOI18N jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N jLabel1.setName("jLabel1"); // NOI18N txtPaymentAmount.setHorizontalAlignment(javax.swing.JTextField.RIGHT); txtPaymentAmount.setText(resourceMap.getString("txtPaymentAmount.text")); // NOI18N txtPaymentAmount.setName("txtPaymentAmount"); // NOI18N cmdCancel.setText(resourceMap.getString("cmdCancel.text")); // NOI18N cmdCancel.setName("cmdCancel"); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lblClient) .addComponent(lblEffectiveDate)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(dtcEffectiveDate, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(txtPaymentAmount, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(cmdAddPayment) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(cmdCancel))) .addComponent(cboClient, 0, 245, Short.MAX_VALUE)) .addContainerGap()) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblClient) .addComponent(cboClient, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblEffectiveDate) .addComponent(dtcEffectiveDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel1) .addComponent(txtPaymentAmount, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(cmdAddPayment) .addComponent(cmdCancel)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JComboBox cboClient; private javax.swing.JButton cmdAddPayment; private javax.swing.JButton cmdCancel; private com.toedter.calendar.JDateChooser dtcEffectiveDate; private javax.swing.JLabel jLabel1; private javax.swing.JLabel lblClient; private javax.swing.JLabel lblEffectiveDate; private javax.swing.JTextField txtPaymentAmount; // End of variables declaration//GEN-END:variables /** * @return the cboClient */ public javax.swing.JComboBox getCboClient() { return cboClient; } /** * @return the dtcEffectiveDate */ public com.toedter.calendar.JDateChooser getDtcEffectiveDate() { return dtcEffectiveDate; } /** * @return the txtPaymentAmount */ public javax.swing.JTextField getTxtPaymentAmount() { return txtPaymentAmount; } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Post")){ if(validateForm()){ selectionConfirmed = true; setVisible(false); } }else if("Cancel".equals(e.getActionCommand())){ selectionConfirmed = true; setVisible(false); } } /** * @return the selectionConfirmed */ public boolean isSelectionConfirmed() { return selectionConfirmed; } /** * @param selectionConfirmed the selectionConfirmed to set */ public void setSelectionConfirmed(boolean selectionConfirmed_) { this.selectionConfirmed = selectionConfirmed_; } public boolean validateForm(){ boolean result = true; String message=""; if (getCboClientId() ==0){ message += "Please select a client. "; result = false; } if (getPaymentAmount() ==0){ message += "Please enter a non-zero payment. "; result = false; } if (dtcEffectiveDate.getDate() ==null){ message += "Please enter an effective date. "; result = false; } if(!result){ JOptionPane.showConfirmDialog( this , message , "Please correct payment posting issues..." , JOptionPane.DEFAULT_OPTION); } return result; } public int getCboClientId(){ int clientId; try{ clientId= ((ClientBean) cboClient.getSelectedItem()).getClientId(); }catch(NullPointerException ex){ clientId=0; easyLog.addEntry(EasyLog.INFO, "Client Line indeterminate" , getClass().getName(), ex); } return clientId; } public double getPaymentAmount(){ double result = 0; try{ result = Double.parseDouble(txtPaymentAmount.getText()); }catch(NumberFormatException e){ result =0; } return result; } public void showDialog(){ selectionConfirmed = false; dtcEffectiveDate.setDate(new java.util.Date()); txtPaymentAmount.setText("0.00"); setLocationRelativeTo(null); this.setVisible(true); } public void showDialog(ClientBean clientBean_){ clientComboBoxModel.setSelectedItem(clientBean_); showDialog(); } }
package com.appsquadz.hostelutility; class StudentComplaintsActivity { }
package jp.co.tau.web7.admin.supplier.services; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import javax.persistence.RollbackException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.modelmapper.Condition; import org.modelmapper.Converter; import org.modelmapper.ModelMapper; import org.modelmapper.spi.MappingContext; import jp.co.tau.web7.admin.supplier.common.CommonConstants; import jp.co.tau.web7.admin.supplier.common.MessageConstants; import jp.co.tau.web7.admin.supplier.dto.BaseDTO; import jp.co.tau.web7.admin.supplier.entity.BaseEntity; import jp.co.tau.web7.admin.supplier.exception.LogicException; import jp.co.tau.web7.admin.supplier.utils.CheckUtil; /** * <p>ファイル名 : BaseService</p> * <p>説明 : BaseService</p> * @author bp.truong.pq * @since 2017/11/25 */ public class BaseService { /** logger*/ protected final Logger logger = LogManager.getLogger(BaseService.class); /** modelMapper*/ protected ModelMapper modelMapper = new ModelMapper(); { modelMapper.getConfiguration().setAmbiguityIgnored(true); modelMapper.getConfiguration().setPropertyCondition(new Condition<Object, Object>() { public boolean applies(MappingContext<Object, Object> pContext) { if (null == pContext.getSource() || null == pContext.getDestinationType()) { return false; } if (pContext.getSourceType().equals(String.class)) { if (CommonConstants.BLANK.equals(pContext.getSource().toString())) { return false; } } // Convert String sang Integer, neu khong hop le thi khong map if (pContext.getSourceType().equals(String.class) && (Integer.class.equals(pContext.getDestinationType()) || int.class.equals(pContext.getDestinationType()))) { if (CheckUtil.isSignNumber(pContext.getSource().toString())) { return true; } return false; } return true; } }); // convert String -> LocalDate Converter<String, LocalDate> localDateConverter = new Converter<String, LocalDate>() { @Override public LocalDate convert(MappingContext<String, LocalDate> context) { String source = context.getSource(); if (CheckUtil.isEmpty(source) || !CheckUtil.isDateFormat(source, "yyyy/MM/dd")) return null; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd"); return LocalDate.parse(source, formatter); } }; modelMapper.addConverter(localDateConverter); // convert String -> LocalDateTime Converter<String, LocalDateTime> localDateTimeConverter = new Converter<String, LocalDateTime>() { @Override public LocalDateTime convert(MappingContext<String, LocalDateTime> context) { String source = context.getSource(); if (CheckUtil.isEmpty(source) || !CheckUtil.isDateFormat(source, "yyyy/MM/dd HH:mm")) return null; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm"); return LocalDateTime.parse(source, formatter); } }; modelMapper.addConverter(localDateTimeConverter); } /** * roll back * @param errMessage String */ protected void rollBack(String errMessage) { logger.info("rollBack {}", errMessage); RollbackException ex = new RollbackException(errMessage); throw ex; } /** * * <p>説明 : throw RuntimeException</p> * @param errMessage String */ protected void returnSystemException(String errMessage) { logger.info("RuntimeException {}", errMessage); throw new RuntimeException(MessageConstants.MSG_1296); } /** * roll back * @param errMessage String * @throws LogicException */ protected void returnLogicError(String errMessage) throws LogicException { logger.info("Logic error {}", errMessage); LogicException ex = new LogicException(errMessage); throw ex; } /** * * <p>説明 : copy create class info</p> * @author : minh.ls * @since : 2018/02/05 * @param dto BaseDTO */ protected void copyCreateInfo(BaseDTO dto) { dto.setCreateClass(this.getClass().toString()); dto.setCreateTime(LocalDateTime.now()); dto.setUpdateClass(this.getClass().toString()); dto.setUpdateTime(LocalDateTime.now()); dto.setDeleteFlg(CommonConstants.DB_AVAILABLE); } /** * * <p>説明 : copy update class info</p> * @author : duc.bv * @since : 2018/02/22 * @param dto BaseDTO */ protected void copyUpdateInfo(BaseDTO dto) { dto.setUpdateClass(this.getClass().toString()); dto.setUpdateTime(LocalDateTime.now()); } /** * * <p>説明 : Copy delete info</p> * @author : hung.nq * @since : 2018/02/26 * @param dto BaseDTO */ protected void copyDeleteInfo(BaseDTO dto) { dto.setUpdateClass(this.getClass().toString()); dto.setUpdateTime(LocalDateTime.now()); dto.setDeleteFlg(CommonConstants.DB_DELETED); dto.setDeleteTime(LocalDateTime.now()); } /** * * <p>説明 : copy create class info</p> * @author : minh.ls * @since : 2018/02/05 * @param entity BaseEntity */ protected void copyCreateInfo(BaseEntity entity) { entity.setCreateTime(LocalDateTime.now()); entity.setUpdateTime(LocalDateTime.now()); entity.setCreateClass(this.getClass().toString()); entity.setUpdateClass(this.getClass().toString()); entity.setDeleteFlg(CommonConstants.DB_AVAILABLE); } /** * * <p>説明 : copy update class info</p> * @author : duc.bv * @since : 2018/02/22 * @param entity BaseEntity */ protected void copyUpdateInfo(BaseEntity entity) { entity.setUpdateClass(this.getClass().toString()); entity.setUpdateTime(LocalDateTime.now()); entity.setDeleteFlg(CommonConstants.DB_AVAILABLE); } /** * * <p>説明 : copy update class info</p> * @author : duc.bv * @since : 2018/02/22 * @param entity BaseEntity */ protected void copyDeleteInfo(BaseEntity entity) { entity.setUpdateClass(this.getClass().toString()); entity.setUpdateTime(LocalDateTime.now()); entity.setDeleteTime(LocalDateTime.now()); entity.setDeleteFlg(CommonConstants.DB_DELETED); } }
package com.xampy.namboo.ui.manyRoomData.manyRoomData; import android.content.Context; import android.net.Uri; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.RequestManager; import com.xampy.namboo.R; import com.xampy.namboo.api.dataModel.PostNambooFirestore; import com.xampy.namboo.api.dataModel.UserNambooFirestore; import com.firebase.ui.firestore.FirestoreRecyclerAdapter; import com.firebase.ui.firestore.FirestoreRecyclerOptions; public class ManyRoomUsersServiceTypeFireStoreAdapter extends FirestoreRecyclerAdapter<UserNambooFirestore, ManyRoomUsersServiceTypeFireStoreAdapter.UserViewHolder> { private final Context mContext; private final RequestManager glide; private final UsersListener callback; private final String uid; LayoutInflater mLayoutInflater; public interface UsersListener { void onDataChanged(); } public interface ManyUsersByServiceInteractionListener { void onCallClicked(String call_number); void onVisitClicked(String coords); void onWhatsappMessagerClicked(String phoneNumber); } private ManyUsersByServiceInteractionListener mListener; public ManyRoomUsersServiceTypeFireStoreAdapter( @NonNull FirestoreRecyclerOptions<UserNambooFirestore> options, RequestManager glide, UsersListener callback, ManyUsersByServiceInteractionListener listener, String uid, Context context) { super(options); this.glide = glide; this.callback = callback; this.uid = uid; this.mContext = context; this.mListener = listener; } @Override protected void onBindViewHolder( @NonNull final ManyRoomUsersServiceTypeFireStoreAdapter.UserViewHolder holder, int position, @NonNull UserNambooFirestore user) { holder.mUserItem = user; Log.i("Got service", user.getUsername()); holder.mUserName.setText(user.getUsername()); holder.mUserService.setText(user.getServiceType()); //holder.mUserCall.setText(user.getPhoneNumber()); holder.mUserLocation.setText(user.getCity() + "-" + user.getDistrict()); String image = user.getUrlPicture(); if (image.startsWith("http")) { glide.load(Uri.parse(image)).into(holder.mImage); } holder.mUserCall.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Ask opening the onRoom fragment if(mListener != null) mListener.onCallClicked(holder.mUserItem.getPhoneNumber()); } }); //Check that the poster has allowed his position if(holder.mUserItem.getPosition().length() < 3){ //Sure that it contains maps coords holder.mUserVisit.setVisibility(View.INVISIBLE); } holder.mUserVisit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Open the google map intent here if(mListener != null){ mListener.onVisitClicked(holder.mUserItem.getPosition()); } } }); holder.mUserWhatsapp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mListener != null) mListener.onWhatsappMessagerClicked(holder.mUserItem.getPhoneNumber()); } }); } @NonNull @Override public ManyRoomUsersServiceTypeFireStoreAdapter.UserViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { return new ManyRoomUsersServiceTypeFireStoreAdapter.UserViewHolder( LayoutInflater.from(parent.getContext()) .inflate( R.layout.fragment_many_room_user_services_item, parent, false)); } @Override public void onDataChanged() { super.onDataChanged(); this.callback.onDataChanged(); } public class UserViewHolder extends RecyclerView.ViewHolder { public View mView; public ImageView mImage; public TextView mUserName; public ImageView mUserWhatsapp; public ImageView mUserCall; public ImageView mUserVisit; public TextView mUserLocation; public TextView mUserService; public UserNambooFirestore mUserItem; public UserViewHolder(View view) { super(view); mView = view; mImage = (ImageView) view.findViewById(R.id.services_user_item_image_view); mUserName = (TextView) view.findViewById(R.id.services_user_item_name_text_view); mUserWhatsapp = (ImageView) view.findViewById(R.id.services_user_item_whatsapp_image_view); mUserCall = (ImageView) view.findViewById(R.id.services_user_item_call_image_view); mUserVisit = (ImageView) view.findViewById(R.id.services_user_item_go_image_view); mUserLocation = (TextView) view.findViewById(R.id.services_user_item_location_text_view); mUserService = (TextView) view.findViewById(R.id.services_user_item_service_text_view); } @Override public String toString() { return super.toString() + " '" + mUserName.getText() + "'"; } } }
package pl.michalgorski.medinfo.models.services; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import pl.michalgorski.medinfo.models.CommentEntity; import pl.michalgorski.medinfo.models.DoctorEntity; import pl.michalgorski.medinfo.models.forms.CommentForm; import pl.michalgorski.medinfo.models.repositories.CommentRepository; import java.util.Optional; @Service public class CommentService { final SessionService sessionService; final CommentRepository commentRepository; final DoctorService doctorService; @Autowired public CommentService(SessionService sessionService, CommentRepository commentRepository, DoctorService doctorService) { this.sessionService = sessionService; this.commentRepository = commentRepository; this.doctorService = doctorService; } public void addComment(CommentForm commentForm, int doctorId) { CommentEntity commentEntity = createCommentEntity(commentForm, doctorId); commentRepository.save(commentEntity); doctorService.increaseQuantityOfComments(doctorId); } private CommentEntity createCommentEntity(CommentForm commentForm, int doctorId) { CommentEntity commentEntity = new CommentEntity(); DoctorEntity doctorEntity = new DoctorEntity(); doctorEntity.setId(doctorId); commentEntity.setContext(commentForm.getContext()); commentEntity.setRating(commentForm.getRating()); commentEntity.setDoctor(doctorEntity); commentEntity.setUser(sessionService.getUserEntity()); return commentEntity; } public void deleteCommentById(int doctorId, int commentId) { doctorService.decreaseQuantityOfComments(doctorId); commentRepository.deleteById(commentId); } public Optional<CommentEntity> getCommentById(int commentId) { return commentRepository.findById(commentId); } }
import java.io.FileReader; import java.io.FileWriter; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Scanner; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; public class WelcomeMenuController implements Serializable { private static Scanner input= new Scanner(System.in); //private Booking booking; public Table headTable=null; private int tableNum=0; private Booking firstBooking=null; private int bookingNum=0; private FoodDrinkMenu firstFdItem=null; private int fdMenuNum=0; private Purchase firstPurchase = null; //private int number=1; //private Purchase firstPurchase = null; //NO.... private int purchase=0; private FoodDrinkMenu fdm; /* implements Serializable File FileOutputStream / FileInputStream ObjectOutputStream / ObjectInputStream writeObject() / readObject() */ public static void main(String[] args) { //WelcomeMenuController app; WelcomeMenuController app = new WelcomeMenuController(); app.runMenu(); try { app = WelcomeMenuController.load(); app.runMenu(); } catch (Exception e) { app = new WelcomeMenuController(); app.runMenu(); } //app.initForTesting(); //for testing only /* ObjectOutputStream / ObjectInputStream writeObject() / readObject(); */ } /*public void initForTesting() { addNewFoodAndDrinkItem("Pizza",4.99); addNewFoodAndDrinkItem("Salad",2.49); addNewFoodAndDrinkItem("EggDish",3.99); }*/ /** * mainMenu() - This method displays the menu for the application, reads the * menu option that the user entered and returns it. * * @return the users menu choice */ private int mainMenu() { System.out.println("Table Menu"); System.out.println("---------"); System.out.println(" 1) Add a Table"); System.out.println(" 2) View Table"); //System.out.println(" 3) Delete Table"); System.out.println("---------"); System.out.println("Booking Menu"); System.out.println("---------"); System.out.println(" 4) Add a Booking"); System.out.println(" 5) View Booking"); System.out.println(" 6) Delete Booking"); System.out.println("---------"); System.out.println(" 7) Add New Food/Drink Order"); System.out.println(" 8) View Food/Drink ordered"); System.out.println(" 9) Delete Food/Drink ordered"); System.out.println("---------"); System.out.println("Purchase Menu"); System.out.println("---------"); System.out.println(" 10) Add a Purchase"); System.out.println(" 11) View All Purchases"); System.out.println(" 12) Delete Purchase"); System.out.println(" 13) View All Tables & Bookings"); System.out.println(" 14) Save to XML"); System.out.println(" 15) Reset"); System.out.println(" 16) Check Out!"); System.out.println("-----------"); System.out.println("-----------"); System.out.println(" 0) Exit"); System.out.print("==>> "); int option = input.nextInt(); return option; } /** * This is the method that controls the loop of the Menu. */ private void runMenu() { int option = mainMenu(); while (option != 0) { switch (option) { case 1: addTable(); break; case 2: viewTables(); break; /*case 3: input.nextLine(); deleteTable(promptForInt("Enter Table Number to delete")); break;*/ case 4 : addBooking(); break; case 5: viewBookings(); break; case 6: input.nextLine(); deleteBookings(promptForString("Enter Customer Name to delete")); break; case 7: addNewFoodAndDrinkItem(); break; case 8: viewFoodItems(); break; case 9: input.nextLine(); deleteFoodItems(promptForString("Enter item to delete")); break; case 10: addPurchase(); break; case 11: viewAllPurchases(); break; case 12: input.nextLine(); deletePurchases(promptForString("Enter Item Purchased to delete"), firstBooking); break; case 13: viewAllTablesAndBookings(); break; case 14: try { save(this); } catch (Exception e) { System.out.println("Error writing to file: " + e); } break; case 15: reset(); break; // case 16: // input.nextLine(); // checkOut(); // break; case 17: try { load(); } catch (Exception e) { System.out.print("Error reading from file: " + e); } break; default: System.out.println("Invalid option entered: " + option); break; } // pause the program so that the user can read what we just printed to the // terminal window System.out.println("\nPress any key to continue..."); input.nextLine(); input.nextLine(); // this second read is required - bug in Scanner class; a String read is ignored // straight after reading an int. // display the main menu again option = mainMenu(); } // the user chose option 0, so exit the program System.out.println("Exiting... bye"); System.exit(0); } //Prompts the user to enter String in order to call the method relevant to delete based on the String entered public String promptForString(String prompt) { System.out.print(prompt+": "); return input.nextLine(); } /* * SAVE METHOD FOR THE ENTIRE SYSTEM */ public static void save(WelcomeMenuController app) throws Exception { try { XStream xstream = new XStream(new DomDriver()); ObjectOutputStream out = xstream.createObjectOutputStream(new FileWriter("WelcomeMenuBookings.xml")); out.writeObject(app); out.close(); }catch(Exception e) { System.out.println("Save error "+e.getMessage()); } } /* * SAVE METHOD FOR THE ENTIRE SYSTEM */ @SuppressWarnings("unchecked") public static WelcomeMenuController load() throws Exception { XStream xstream = new XStream(new DomDriver()); ObjectInputStream is = xstream.createObjectInputStream(new FileReader("WelcomeMenuBookings.xml")); WelcomeMenuController app=(WelcomeMenuController)is.readObject(); is.close(); return app; } /* * METHOD TO ADD TABLES */ public void addTable() { System.out.print("Please Enter the number of seats: "); int numberOfSeats = input.nextInt(); tableNum++; Table nt=new Table(tableNum,numberOfSeats); nt.next=headTable; headTable=nt; } /* * METHOD TO VIEW TABLES ADDED */ public void viewTables() { Table temp=headTable; System.out.print("Table Details"+" \n "); while(temp!=null){ System.out.print("\t"+"Table No. "+temp.getTableNumber()+", Seats "+temp.getNumberOfSeats()+ " \n "); temp=temp.next; } } /* * METHOD TO DELETE A TABLE */ /* public void deleteTable(int number) { Table temp3=headTable,temp4=null; while(temp3!=null && !temp3. .equals(number)) { temp4=temp3; temp3 = temp3.next; } if(temp3!=null) { //found it if(temp4!=null) temp4.next=temp3.next; //not at the head else headTable=headTable.next; //delete the head System.out.println("Table Number "+number+" deleted."); } else {//not found System.out.println("Table Number "+number+" not found."); } } */ /* * METHOD TO ADD BOOKINGS */ public void addBooking() { System.out.print("Please Enter your Name: "); String customerName = input.nextLine(); customerName = input.nextLine(); System.out.print("Number of People booking: "); int numberOfPplBooking= input.nextInt(); System.out.print("Table Number being booked: "); int tableNumberBooked = input.nextInt(); System.out.print("Time of Booking: "); int bookingTime = input.nextInt(); System.out.print("The Amount of time (in hours) the booking is for: "); int amountOfTimeBooking = input.nextInt(); bookingNum++; Booking nb=new Booking(bookingNum,customerName,numberOfPplBooking,tableNumberBooked,bookingTime,amountOfTimeBooking); nb.next=firstBooking; firstBooking=nb; } public void viewBookings() { Booking temp2=firstBooking; System.out.println("Booking Details:"+" \n "); while(temp2!=null){ //process Booking here.... System.out.println("Booking Details: "+" \n " + "\t"+"Booking No.: "+temp2.getbookingNumber() +" \n " + "\t" + "Customer Name: "+temp2.getCustomerName()+" \n " + "\t" + "Number of People Booking: "+temp2.getNumberOfPplBooking()+" \n " + "\t" + "Table Number Booked: "+temp2.getTableNumberBooked()+" \n " + "\t" + "Booking Time: "+temp2.getBookingTime()+" \n " + "\t" + "The Amount of time (in hours) the booking is for: "+temp2.getAmountOfTimeBooking()); temp2=temp2.next; } } /* * METHOD TO DELETE BOOKING */ public void deleteBookings(String name) { Booking temp3=firstBooking,temp4=null; while(temp3!=null && !temp3.customerName.equals(name)) { temp4=temp3; temp3 = temp3.next; } if(temp3!=null) { //found it if(temp4!=null) temp4.next=temp3.next; //not at the head else firstBooking=firstBooking.next; //delete the head System.out.println("Item "+name+" deleted."); } else {//not found System.out.println("Item "+name+" not found."); } } /* * !!! HERE I WILL CREATE MY SEARCH ALGORITHM!!! * * * /* public void SEARCH(int index) { if (!(index > (numberOfMembers() - 1) || index < 0)) members.remove(index); } */ /* * METHOD TO ADD FOOD/DRINK ADDED */ public void addNewFoodAndDrinkItem() { System.out.print("Please Enter Food/Drink Item: "+ " \n "); String fdMenuItem = input.nextLine(); fdMenuItem = input.nextLine(); System.out.print("Please Enter Price: "+ " \n "); double itemPrice= input.nextInt(); addNewFoodAndDrinkItem(fdMenuItem,itemPrice); } //Method for number iterating through the foodMenu when a food has been added! public void addNewFoodAndDrinkItem(String fdMenuItem, double itemPrice) { fdMenuNum++; FoodDrinkMenu nf=new FoodDrinkMenu(fdMenuNum,fdMenuItem,itemPrice); //head insertion //nf.next=firstFdItem; //firstFdItem=nf; //tail insertion if(firstFdItem!=null) { fdm = firstFdItem; while(fdm.next!=null) fdm=fdm.next; fdm.next=nf; } else firstFdItem=nf; } /* * METHOD TO VIEW FOOD/DRINK ADDED */ public void viewFoodItems() { // int number=1; fdm = firstFdItem; System.out.println("FoodDrink Item Details: \n========================\n"); while(fdm!=null){ System.out.println("Number: "+ fdm.getFoodMenuNumber() +""+" \n " + "\t" + "Item Name: "+fdm.getFdMenuItem()+" \n " + "\t" + "Item Cost Cost.: "+fdm.getItemPrice()); fdm=fdm.next; //number++; } } /* * METHOD TO DELETE A FOOD/DRINK */ public void deleteFoodItems(String item) { FoodDrinkMenu temp1=firstFdItem,temp2=null; while(temp1!=null && !temp1.getFdMenuItem().equals(item)) { temp2=temp1; temp1 = temp1.next; } if(temp1!=null) { //found it if(temp2!=null) temp2.next=temp1.next; //not at the head else firstFdItem=firstFdItem.next; //delete the head System.out.println("Item "+item+" deleted."); } else {//not found System.out.println("Item "+item+" not found."); } } /* * METHOD TO ADD PURCHASE */ public void addPurchase() { //System.out.print("Please Enter your Name: "); System.out.print("Enter Booking Id for Purchase: "); int bid = input.nextInt(); //Find booking to add purchase to Booking thebooking=firstBooking; if(thebooking==null){ System.out.println("No Bookings Found!"); //no booking found.... return; } else{ while(thebooking.getbookingNumber()!=bid) thebooking=thebooking.next; } System.out.print("Menu Item being purchased: "); String itemPurchased = input.nextLine(); itemPurchased = input.nextLine(); System.out.print("Quantities of Purchase: "); int quantity= input.nextInt(); purchase++; Purchase np=new Purchase(purchase,itemPurchased,quantity); //head insertion np.next=thebooking.firstPurchase; thebooking.firstPurchase=np; } /** * METHOD TO VIEW ADD VIEW PURCHASE */ public void viewAllPurchases() { //Purchase pMenu=firstPurchase; Booking thebooking=firstBooking; while(thebooking!=null) { Purchase pMenu=thebooking.firstPurchase; System.out.println("Booking Details: "+"===================\n " + "\t" + "Booking No.: "+thebooking.bookingNumber +" \n " + "\t" + "Table: "+thebooking.getTableNumberBooked()+" \n " + "\t" + "Customer Name: "+thebooking.getCustomerName()); while(pMenu!=null){ //process Booking here.... System.out.println("Purchase Details: "+" \n " + "\t" + "Purchase No.: "+pMenu.getPurchaseNumber() +" \n " + "\t" + "FoodItem being Purchased: "+pMenu.getItemPurchased()+" \n " + "\t" + "Quantity: "+pMenu.getQuantity()); pMenu=pMenu.next; } thebooking=thebooking.next; } } /** * METHOD TO DELETE A PURCHASE */ public void deletePurchases(String itemP, Booking booking) { // !!!! *ASK LECTURER IF THE PROBLEM IS THAT IT HAS TO POINT TO AN ID TO DELETE I.E. PROMPT 'ENTER BOOKING ID TO DELETE FOOD ITEM PURCHASED' !!! Purchase temp5=booking.firstPurchase,temp6=null; while(temp5!=null && !temp5.itemPurchased.equals(itemP)) { temp6=temp5; temp5 = temp5.next; } if(temp5!=null) { //found it if(temp6!=null) temp6.next=temp5.next; //not at the head else firstFdItem=firstFdItem.next; //delete the head System.out.println("Item "+itemP+" deleted."); } else {//not found System.out.println("Item "+itemP+" not found."); } } /* public void deletePurchases(String itemP) { //ASK LECTURER IF THE PROBLEM IS THAT IT HAS TO POINT TO AN ID TO DELETE I.E. PROMPT 'ENTER BOOKING ID TO DELETE FOOD ITEM PURCHASED' //Find booking to add purchase to Booking thebooking=firstBooking; int bid = input.nextInt(); Purchase temp5=firstPurchase,temp6=null; while(thebooking.getbookingNumber()!=bid && temp5!=null && !temp5.itemPurchased.equals(itemP)) { temp6=temp5; temp5 = temp5.next; } if(temp5!=null) { //found it if(temp6!=null) temp6.next=temp5.next; //not at the head else firstFdItem=firstFdItem.next; //delete the head System.out.println("Item "+itemP+" deleted."); } else {//not found System.out.println("Item "+itemP+" not found."); } }*/ /* ==================================================================================== System.out.print("Enter Booking Id for Purchase: "); int bid = input.nextInt(); //Find booking to add purchase to Booking thebooking=firstBooking; if(thebooking==null){ System.out.println("No Bookings Found!"); //no booking found.... return; } else{ while(thebooking.getbookingNumber()!=bid) thebooking=thebooking.next; } ========================================================================================== public void deleteFoodItems(String item) { FoodDrinkMenu temp1=firstFdItem,temp2=null; while(temp1!=null && !temp1.getFdMenuItem().equals(item)) { temp2=temp1; temp1 = temp1.next; } if(temp1!=null) { //found it if(temp2!=null) temp2.next=temp1.next; //not at the head else firstFdItem=firstFdItem.next; //delete the head System.out.println("Item "+item+" deleted."); } else {//not found System.out.println("Item "+item+" not found."); } } */ /** * !!! HERE I CREATE THE METHOD TO LIST ALL TABLES AND ALL BOOKINGS !!!! */ //Method to view Tables added public void viewAllTablesAndBookings() { Table temp=headTable; Booking temp2=firstBooking; while(temp!=null && temp2!=null){ System.out.print("Table Details: "+" \n " + "\t" + "Table No. "+temp.getTableNumber() +" \n " + "\t" + "No. of Seats "+temp.getNumberOfSeats()+ " \n "); System.out.println("Booking Details:"+" \n " + "\t" + "Booking No.: "+temp2.getbookingNumber() +" \n " + "\t" + "Customer Name: "+temp2.getCustomerName()+" \n " + "\t" + "Number of People Booking: "+temp2.getNumberOfPplBooking()+" \n " + "\t" + "Table Number Booked: "+temp2.getTableNumberBooked()+" \n " + "\t" + "Booking Time: "+temp2.getBookingTime()+" \n " + "\t" + "The Amount of time (in hours) the booking is for: "+temp2.getAmountOfTimeBooking()); temp=temp.next; temp2=temp2.next; } } /** * METHOD TO RESET THE SYSTEM */ public void reset() { headTable=null; System.out.println("Reset Successful"); } }
package com.tencent.tencentmap.mapsdk.a; import java.util.ArrayList; class tg$2 implements Runnable { private /* synthetic */ ArrayList a; private /* synthetic */ tg b; tg$2(tg tgVar, ArrayList arrayList) { this.b = tgVar; this.a = arrayList; } public final void run() { tg.a(this.b).clear(); synchronized (tg.b(this.b)) { tg.b(this.b).clear(); tg.b(this.b).putAll(tg.c(this.b)); } for (int i = 0; i < this.a.size(); i++) { for (td tdVar : ((tc) this.a.get(i)).b()) { tf a; try { a = te.a().a(tdVar); } catch (Throwable th) { if (tz.n() != null) { tz.n().a("TileEngineManager getTiles Runnable call CacheManager Get occured Exception,tileInfo:x=" + tdVar.b() + ",y=" + tdVar.c() + ",z=" + tdVar.d() + "Exception Info:" + th.toString()); } a = null; } if (a.b() != null && a.d() == tdVar.l()) { tdVar.a(a.b()); if (tdVar.m() == tc$a.TENCENT && !tg.d(this.b).r()) { sl.a++; } if (tdVar.m() == tc$a.WORLD) { sl.b++; } } else if (a.b() != null && a.d() != tdVar.l() && tdVar.m() == tc$a.TENCENT) { new StringBuilder("Have got cache,but version is not ok,tileBitmap.getVersion:").append(a.d()).append(",tileData.getVersion:").append(tdVar.l()); tg.a(this.b, tdVar, true, a); } else if (a.b() == null) { tg.a(this.b, tdVar, false, null); if (tdVar.m() == tc$a.TENCENT && !tg.d(this.b).r()) { tg.d(this.b); sl.c++; } if (tdVar.m() == tc$a.WORLD) { tg.d(this.b); sl.d++; } } } tg.d(this.b).c().postInvalidate(); } } }
import java.util.*; abstract public class Graph { abstract public boolean hasEdge(int p, int q); abstract public Set<Integer> neighboursOf(int p); abstract public void addEdge(int p, int q); public List<Integer> depthFirstTraversal(int root) { List<Integer> visited = new LinkedList<>(); LinkedList<Integer> notVisited = new LinkedList<>(); notVisited.add(root); while (!notVisited.isEmpty()) { int p = notVisited.pop(); visited.add(p); Set<Integer> neighbours = neighboursOf(p); for (int q : neighbours) if (!visited.contains(q) && !notVisited.contains(q)) notVisited.push(q); } return visited; } }
package it.unical.asd.group6.computerSparePartsCompany.data.entities; import com.fasterxml.jackson.annotation.JsonManagedReference; import javax.persistence.*; import java.util.Objects; @Entity @Table(name="PRODUCT") public class Product { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="PRICE") private Double price; @Column(name="BRAND") private String brand; @Column(name="MODEL") private String model; //@Lob @Column(name="DESCRIPTION", length = 1024) private String description; @Column(name = "IMAGE_URL") private String imageUrl; @ManyToOne @JoinColumn(name = "PURCHASE_ID", referencedColumnName = "ID" , nullable = true) @JsonManagedReference private Purchase purchase; @ManyToOne @JoinColumn(name = "ORDER_ID", referencedColumnName = "ID", nullable = true) @JsonManagedReference private OrderRequest orderRequest; @ManyToOne @JoinColumn(name = "WAREHOUSE_ID", referencedColumnName = "ID") private Warehouse warehouse; @ManyToOne @JoinColumn(name = "CATEGORY_ID", referencedColumnName = "ID") private Category category; public Product() {} public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Purchase getPurchaseId() { return purchase; } public void setPurchaseId(Purchase purchaseId) { this.purchase = purchaseId; } public OrderRequest getOrder() { return orderRequest; } public void setOrder(OrderRequest order) { this.orderRequest = order; } public Warehouse getWarehouse() { return warehouse; } public void setWarehouse(Warehouse warehouse) { this.warehouse = warehouse; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public Purchase getPurchase() { return purchase; } public void setPurchase(Purchase purchase) { this.purchase = purchase; } public OrderRequest getOrderRequest() { return orderRequest; } public void setOrderRequest(OrderRequest orderRequest) { this.orderRequest = orderRequest; } @Override public boolean equals(Object o) { //(MANUEL) HO ELIMINATO L'ID POICHE' CHIAVE PRIMARE SEMPRE DIVERSA---> L'EQUALS DAVA SEMPRE FALSO if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Product product = (Product) o; return Objects.equals(price, product.price) && Objects.equals(brand, product.brand) && Objects.equals(model, product.model)/* && Objects.equals(description, product.description) && Objects.equals(purchase, product.purchase) && Objects.equals(orderRequest, product.orderRequest) && Objects.equals(warehouse, product.warehouse) && Objects.equals(category, product.category) && Objects.equals(imageUrl, product.imageUrl)*/; } @Override //(MANUEL) HO FATTO LA STESSA COSA QUI NELL'HASHCODE POICHE' NON SI PUO' VIOLARE IL CONTRATTO TRA EQUALS E HASHCODE public int hashCode() { return Objects.hash(price, brand, model/*, description, purchase, orderRequest, warehouse, category, imageUrl*/); } }
package cn.omsfuk.library.web.service; import cn.omsfuk.library.web.model.Book; import cn.omsfuk.library.web.model.Borrow; import java.util.List; import java.util.Map; public interface BorrowService { List<Book> listBorrow(int page); Integer returnBook(List<Integer> id); Integer borrowBook(List<Integer> id); Boolean renewBorrow(Integer id); /** * 获得借阅信息概览。包括当前借阅数量,即将超期数量 * @return */ Map<String, Object> getBorrowAbstract(); List<Borrow> history(int page); }
/* * Copyright (c) 2012-2019 Snowflake Computing Inc. All rights reserved. */ package net.snowflake.client.jdbc; import java.sql.SQLException; import net.snowflake.client.core.SFException; import net.snowflake.client.log.SFLogger; import net.snowflake.client.log.SFLoggerFactory; import net.snowflake.common.core.ResourceBundleManager; /** @author jhuang */ public class SnowflakeSQLException extends SQLException { static final SFLogger logger = SFLoggerFactory.getLogger(SnowflakeSQLException.class); private static final long serialVersionUID = 1L; static final ResourceBundleManager errorResourceBundleManager = ResourceBundleManager.getSingleton(ErrorCode.errorMessageResource); private String queryId = "unknown"; /** * This constructor should only be used for error from Global service. Since Global service has * already built the error message, we use it as is. For any errors local to JDBC driver, we * should use one of the constructors below to build the error message. * * @param queryId query id * @param reason reason for which exception is created * @param sqlState sql state * @param vendorCode vendor code */ public SnowflakeSQLException(String queryId, String reason, String sqlState, int vendorCode) { super(reason, sqlState, vendorCode); this.queryId = queryId; // log user error from GS at fine level logger.debug( "Snowflake exception: {}, sqlState:{}, vendorCode:{}, queryId:{}", reason, sqlState, vendorCode, queryId); } public SnowflakeSQLException(String reason, String SQLState) { super(reason, SQLState); // log user error from GS at fine level logger.debug("Snowflake exception: {}, sqlState:{}", reason, SQLState); } public SnowflakeSQLException(String sqlState, int vendorCode) { super( errorResourceBundleManager.getLocalizedMessage(String.valueOf(vendorCode)), sqlState, vendorCode); logger.debug( "Snowflake exception: {}, sqlState:{}, vendorCode:{}", errorResourceBundleManager.getLocalizedMessage(String.valueOf(vendorCode)), sqlState, vendorCode); } public SnowflakeSQLException(String sqlState, int vendorCode, Object... params) { super( errorResourceBundleManager.getLocalizedMessage(String.valueOf(vendorCode), params), sqlState, vendorCode); logger.debug( "Snowflake exception: {}, sqlState:{}, vendorCode:{}", errorResourceBundleManager.getLocalizedMessage(String.valueOf(vendorCode), params), sqlState, vendorCode); } public SnowflakeSQLException(Throwable ex, String sqlState, int vendorCode) { super( errorResourceBundleManager.getLocalizedMessage(String.valueOf(vendorCode)), sqlState, vendorCode, ex); logger.debug( "Snowflake exception: {}" + errorResourceBundleManager.getLocalizedMessage(String.valueOf(vendorCode)), ex); } public SnowflakeSQLException(Throwable ex, ErrorCode errorCode, Object... params) { this(ex, errorCode.getSqlState(), errorCode.getMessageCode(), params); } public SnowflakeSQLException(Throwable ex, String sqlState, int vendorCode, Object... params) { super( errorResourceBundleManager.getLocalizedMessage(String.valueOf(vendorCode), params), sqlState, vendorCode, ex); logger.debug( "Snowflake exception: " + errorResourceBundleManager.getLocalizedMessage(String.valueOf(vendorCode), params), ex); } public SnowflakeSQLException(ErrorCode errorCode, Object... params) { super( errorResourceBundleManager.getLocalizedMessage( String.valueOf(errorCode.getMessageCode()), params), errorCode.getSqlState(), errorCode.getMessageCode()); } public SnowflakeSQLException(SFException e) { this(e.getQueryId(), e.getMessage(), e.getSqlState(), e.getVendorCode()); } public SnowflakeSQLException(String reason) { super(reason); } public String getQueryId() { return queryId; } }
package com.tencent.mm.g.a; import com.tencent.mm.sdk.b.b; public final class gc extends b { public a bPk; public static final class a { public boolean bPl = false; public long bPm = 0; } public gc() { this((byte) 0); } private gc(byte b) { this.bPk = new a(); this.sFm = false; this.bJX = null; } }
import java.util.*; /** * */ /** * @author Nanda * */ public class ArrayListTypesOfInit { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub /* Using Arrays.asList() */ ArrayList<String> obj = new ArrayList<String>( Arrays.asList("Pratap", "Peter", "Harsh")); System.out.println("Elements are:"+obj); /* Anonymous Inner class method */ ArrayList<String> cities = new ArrayList<String>(){ { add("Delhi"); add("Agra"); add("Chennai"); } }; System.out.println("Content of Array list cities:"+cities); /* Using Collections.ncopis() */ ArrayList<Integer> intlist = new ArrayList<Integer>(Collections.nCopies(10, 5)); System.out.println("ArrayList items: "+intlist); } }
package webmail.managers.userManagers; import webmail.entities.Contacts; import webmail.managers.Manager; import webmail.managers.otherManagers.SQLManager; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Created by JOKER on 12/2/14. */ public class AddContactManager extends Manager { public AddContactManager(HttpServletRequest request, HttpServletResponse response) { super(request, response); } @Override public void run(){ //create user try { HttpSession session = request.getSession(); String account = (String)session.getAttribute("account"); String name = request.getParameter("name"); String email = request.getParameter("email"); String phone = request.getParameter("phone"); Contacts contact = new Contacts(0,account,name,email,phone); SQLManager.addContactSQL(contact); response.sendRedirect("/contacts?infolder=inbox"); } catch (Exception e){ e.printStackTrace(); } } }
package com.chengfu.android.fuplayer.ui; import android.content.Context; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.exoplayer2.Player; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; public class SampleBufferingView extends BaseStateView { @Documented @Retention(RetentionPolicy.SOURCE) @IntDef({SHOW_MODE_ALWAYS, SHOW_MODE_PLAYING, SHOW_MODE_NEVER}) @interface ShowMode { } /** * The buffering view is always shown when the player is in the {@link Player#STATE_BUFFERING * buffering} state. */ public static final int SHOW_MODE_ALWAYS = 0; /** * The buffering view is shown when the player is in the {@link Player#STATE_BUFFERING buffering} * state and {@link Player#getPlayWhenReady() playWhenReady} is {@code true}. */ public static final int SHOW_MODE_PLAYING = 1; /** * The buffering view is never shown. */ public static final int SHOW_MODE_NEVER = 2; protected final ComponentListener componentListener; private int showMode; private boolean showInDetachPlayer; public SampleBufferingView(@NonNull Context context) { this(context, null); } public SampleBufferingView(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public SampleBufferingView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); View view = onCreateView(LayoutInflater.from(context), this); if (view != null) { addView(view); } componentListener = new ComponentListener(); updateVisibility(); } @Override protected void onFullScreenChanged(boolean fullScreen) { } protected View onCreateView(LayoutInflater inflater, ViewGroup parent) { return inflater.inflate(R.layout.sample_buffering_view, parent, false); } protected void updateVisibility() { if (isInShowState()) { show(); } else { hide(); } } protected boolean isInShowState() { if (player == null) { return showInDetachPlayer; } else { if (player.getPlaybackState() == Player.STATE_BUFFERING) { if (showMode == SHOW_MODE_ALWAYS) { return true; } else return showMode == SHOW_MODE_PLAYING && player.getPlayWhenReady(); } } return false; } @Override protected void onAttachedToPlayer(@NonNull Player player) { player.addListener(componentListener); updateVisibility(); } @Override protected void onDetachedFromPlayer(@NonNull Player player) { player.removeListener(componentListener); updateVisibility(); } @ShowMode public int getShowMode() { return showMode; } public void setShowMode(@ShowMode int showMode) { this.showMode = showMode; updateVisibility(); } public boolean isShowInDetachPlayer() { return showInDetachPlayer; } public void setShowInDetachPlayer(boolean showInDetachPlayer) { this.showInDetachPlayer = showInDetachPlayer; updateVisibility(); } private final class ComponentListener implements Player.Listener { @Override public void onPlaybackStateChanged(int playbackState) { updateVisibility(); } @Override public void onPlayWhenReadyChanged(boolean playWhenReady, int reason) { updateVisibility(); } } }
package day04_variables_intro; public class VariableNamingRules { public static void main (String [] args ){ // System.out.println("Break"); int static2 = 22; int _static = 22; int $static = 44; int staticVar = 234; int $ = 55; int _ = 3000; System.out.println($); System.out.println(_); } }
package animatronics.client.render.tile; import java.nio.FloatBuffer; import java.util.Random; import org.lwjgl.opengl.GL11; import animatronics.utils.handler.ClientTickHandler; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.ActiveRenderInfo; import net.minecraft.client.renderer.GLAllocation; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; public class RenderTileEntityNothing extends TileEntitySpecialRenderer { FloatBuffer fBuffer; private boolean inrange; private ResourceLocation t1; private ResourceLocation t2; private ResourceLocation t3; public RenderTileEntityNothing() { t1 = new ResourceLocation("animatronics:textures/misc/end_sky.png"); t2 = new ResourceLocation("animatronics:textures/misc/particlefield.png"); t3 = new ResourceLocation("animatronics:textures/misc/particlefield32.png"); fBuffer = GLAllocation.createDirectFloatBuffer(16); } public void renderTileEntityAt(final TileEntity te, final double x, final double y, final double z, final float f) { this.inrange = (Minecraft.getMinecraft().renderViewEntity.getDistanceSq(te.xCoord + 0.5, te.yCoord + 0.5, te.zCoord + 0.5) < 512.0); GL11.glDisable(2912); if (!te.getWorldObj().getBlock(te.xCoord, te.yCoord + 1, te.zCoord).isOpaqueCube()) { this.drawPlaneYNeg(x, y, z, f); } if (!te.getWorldObj().getBlock(te.xCoord, te.yCoord - 1, te.zCoord).isOpaqueCube()) { this.drawPlaneYPos(x, y, z, f); } if (!te.getWorldObj().getBlock(te.xCoord, te.yCoord, te.zCoord - 1).isOpaqueCube()) { this.drawPlaneZPos(x, y, z, f); } if (!te.getWorldObj().getBlock(te.xCoord, te.yCoord, te.zCoord + 1).isOpaqueCube()) { this.drawPlaneZNeg(x, y, z, f); } if (!te.getWorldObj().getBlock(te.xCoord - 1, te.yCoord, te.zCoord).isOpaqueCube()) { this.drawPlaneXPos(x, y, z, f); } if (!te.getWorldObj().getBlock(te.xCoord + 1, te.yCoord, te.zCoord).isOpaqueCube()) { this.drawPlaneXNeg(x, y, z, f); } GL11.glEnable(2912); } public void drawPlaneYPos(final double x, final double y, final double z, final float f) { final float px = (float)TileEntityRendererDispatcher.staticPlayerX; final float py = (float)TileEntityRendererDispatcher.staticPlayerY; final float pz = (float)TileEntityRendererDispatcher.staticPlayerZ; GL11.glDisable(2896); final Random random = new Random(31100L); final float offset = 0.0f; if (this.inrange) { for (int i = 0; i < 16; ++i) { GL11.glPushMatrix(); float f2 = 16 - i; float f3 = 0.0625f; float f4 = 1.0f / (f2 + 1.0f); if (i == 0) { bindTexture(this.t1); f4 = 0.1f; f2 = 65.0f; f3 = 0.125f; GL11.glEnable(3042); GL11.glBlendFunc(770, 771); } if (i == 1) { bindTexture(this.t2); GL11.glEnable(3042); GL11.glBlendFunc(1, 1); f3 = 0.5f; } final float f5 = (float)(y + offset); final float f6 = f5 - ActiveRenderInfo.objectY; final float f7 = f5 + f2 - ActiveRenderInfo.objectY; float f8 = f6 / f7; f8 += (float)(y + offset); GL11.glTranslatef(px, f8, pz); GL11.glTexGeni(8192, 9472, 9217); GL11.glTexGeni(8193, 9472, 9217); GL11.glTexGeni(8194, 9472, 9217); GL11.glTexGeni(8195, 9472, 9216); GL11.glTexGen(8192, 9473, this.calcFloatBuffer(1.0f, 0.0f, 0.0f, 0.0f)); GL11.glTexGen(8193, 9473, this.calcFloatBuffer(0.0f, 0.0f, 1.0f, 0.0f)); GL11.glTexGen(8194, 9473, this.calcFloatBuffer(0.0f, 0.0f, 0.0f, 1.0f)); GL11.glTexGen(8195, 9474, this.calcFloatBuffer(0.0f, 1.0f, 0.0f, 0.0f)); GL11.glEnable(3168); GL11.glEnable(3169); GL11.glEnable(3170); GL11.glEnable(3171); GL11.glPopMatrix(); GL11.glMatrixMode(5890); GL11.glPushMatrix(); GL11.glLoadIdentity(); GL11.glTranslatef(0.0f, System.currentTimeMillis() % 700000L / 250000.0f, 0.0f); GL11.glScalef(f3, f3, f3); GL11.glTranslatef(0.5f, 0.5f, 0.0f); GL11.glRotatef((i * i * 4321 + i * 9) * 2.0f, 0.0f, 0.0f, 1.0f); GL11.glTranslatef(-0.5f, -0.5f, 0.0f); GL11.glTranslatef(-px, -pz, -py); GL11.glTranslatef(ActiveRenderInfo.objectX * f2 / f6, ActiveRenderInfo.objectZ * f2 / f6, -py); final Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); f8 = random.nextFloat() * 0.5f + 0.1f; float f9 = random.nextFloat() * 0.5f + 0.4f; float f10 = random.nextFloat() * 0.5f + 0.5f; if (i == 0) { f9 = (f8 = (f10 = 1.0f)); } tessellator.setBrightness(180); tessellator.setColorRGBA_F(f8 * f4, f9 * f4, f10 * f4, 1.0f); tessellator.addVertex(x, y + offset, z + 1.0); tessellator.addVertex(x, y + offset, z); tessellator.addVertex(x + 1.0, y + offset, z); tessellator.addVertex(x + 1.0, y + offset, z + 1.0); tessellator.draw(); GL11.glPopMatrix(); GL11.glMatrixMode(5888); } } else { GL11.glPushMatrix(); bindTexture(this.t3); final Tessellator tessellator2 = Tessellator.instance; tessellator2.startDrawingQuads(); tessellator2.setBrightness(180); tessellator2.addVertexWithUV(x, y + offset, z + 1.0, 1.0, 1.0); tessellator2.addVertexWithUV(x, y + offset, z, 1.0, 0.0); tessellator2.addVertexWithUV(x + 1.0, y + offset, z, 0.0, 0.0); tessellator2.addVertexWithUV(x + 1.0, y + offset, z + 1.0, 0.0, 1.0); tessellator2.draw(); GL11.glPopMatrix(); } GL11.glDisable(3042); GL11.glDisable(3168); GL11.glDisable(3169); GL11.glDisable(3170); GL11.glDisable(3171); GL11.glEnable(2896); } public void drawPlaneYNeg(final double x, final double y, final double z, final float f) { final float f2 = (float)TileEntityRendererDispatcher.staticPlayerX; final float f3 = (float)TileEntityRendererDispatcher.staticPlayerY; final float f4 = (float)TileEntityRendererDispatcher.staticPlayerZ; GL11.glDisable(2896); final Random random = new Random(31100L); final float offset = 1.0f; if (this.inrange) { for (int i = 0; i < 16; ++i) { GL11.glPushMatrix(); float f5 = 16 - i; float f6 = 0.0625f; float f7 = 1.0f / (f5 + 1.0f); if (i == 0) { bindTexture(this.t1); f7 = 0.1f; f5 = 65.0f; f6 = 0.125f; GL11.glEnable(3042); GL11.glBlendFunc(770, 771); } if (i == 1) { bindTexture(this.t2); GL11.glEnable(3042); GL11.glBlendFunc(1, 1); f6 = 0.5f; } final float f8 = (float)(-(y + offset)); final float f9 = f8 + ActiveRenderInfo.objectY; final float f10 = f8 + f5 + ActiveRenderInfo.objectY; float f11 = f9 / f10; f11 += (float)(y + offset); GL11.glTranslatef(f2, f11, f4); GL11.glTexGeni(8192, 9472, 9217); GL11.glTexGeni(8193, 9472, 9217); GL11.glTexGeni(8194, 9472, 9217); GL11.glTexGeni(8195, 9472, 9216); GL11.glTexGen(8192, 9473, this.calcFloatBuffer(1.0f, 0.0f, 0.0f, 0.0f)); GL11.glTexGen(8193, 9473, this.calcFloatBuffer(0.0f, 0.0f, 1.0f, 0.0f)); GL11.glTexGen(8194, 9473, this.calcFloatBuffer(0.0f, 0.0f, 0.0f, 1.0f)); GL11.glTexGen(8195, 9474, this.calcFloatBuffer(0.0f, 1.0f, 0.0f, 0.0f)); GL11.glEnable(3168); GL11.glEnable(3169); GL11.glEnable(3170); GL11.glEnable(3171); GL11.glPopMatrix(); GL11.glMatrixMode(5890); GL11.glPushMatrix(); GL11.glLoadIdentity(); GL11.glTranslatef(0.0f, System.currentTimeMillis() % 700000L / 250000.0f, 0.0f); GL11.glScalef(f6, f6, f6); GL11.glTranslatef(0.5f, 0.5f, 0.0f); GL11.glRotatef((i * i * 4321 + i * 9) * 2.0f, 0.0f, 0.0f, 1.0f); GL11.glTranslatef(-0.5f, -0.5f, 0.0f); GL11.glTranslatef(-f2, -f4, -f3); GL11.glTranslatef(ActiveRenderInfo.objectX * f5 / f9, ActiveRenderInfo.objectZ * f5 / f9, -f3); final Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); f11 = random.nextFloat() * 0.5f + 0.1f; float f12 = random.nextFloat() * 0.5f + 0.4f; float f13 = random.nextFloat() * 0.5f + 0.5f; if (i == 0) { f12 = (f11 = (f13 = 1.0f)); } tessellator.setBrightness(180); tessellator.setColorRGBA_F(f11 * f7, f12 * f7, f13 * f7, 1.0f); tessellator.addVertex(x, y + offset, z); tessellator.addVertex(x, y + offset, z + 1.0); tessellator.addVertex(x + 1.0, y + offset, z + 1.0); tessellator.addVertex(x + 1.0, y + offset, z); tessellator.draw(); GL11.glPopMatrix(); GL11.glMatrixMode(5888); } } else { GL11.glPushMatrix(); bindTexture(this.t3); final Tessellator tessellator2 = Tessellator.instance; tessellator2.startDrawingQuads(); tessellator2.setBrightness(180); tessellator2.addVertexWithUV(x, y + offset, z, 1.0, 1.0); tessellator2.addVertexWithUV(x, y + offset, z + 1.0, 1.0, 0.0); tessellator2.addVertexWithUV(x + 1.0, y + offset, z + 1.0, 0.0, 0.0); tessellator2.addVertexWithUV(x + 1.0, y + offset, z, 0.0, 1.0); tessellator2.draw(); GL11.glPopMatrix(); } GL11.glDisable(3042); GL11.glDisable(3168); GL11.glDisable(3169); GL11.glDisable(3170); GL11.glDisable(3171); GL11.glEnable(2896); } public void drawPlaneZNeg(final double x, final double y, final double z, final float f) { final float px = (float)TileEntityRendererDispatcher.staticPlayerX; final float py = (float)TileEntityRendererDispatcher.staticPlayerY; final float pz = (float)TileEntityRendererDispatcher.staticPlayerZ; GL11.glDisable(2896); final Random random = new Random(31100L); final float offset = 1.0f; if (this.inrange) { for (int i = 0; i < 16; ++i) { GL11.glPushMatrix(); float f2 = 16 - i; float f3 = 0.0625f; float f4 = 1.0f / (f2 + 1.0f); if (i == 0) { bindTexture(this.t1); f4 = 0.1f; f2 = 65.0f; f3 = 0.125f; GL11.glEnable(3042); GL11.glBlendFunc(770, 771); } if (i == 1) { bindTexture(this.t2); GL11.glEnable(3042); GL11.glBlendFunc(1, 1); f3 = 0.5f; } final float f5 = (float)(-(z + offset)); final float f6 = f5 + ActiveRenderInfo.objectZ; final float f7 = f5 + f2 + ActiveRenderInfo.objectZ; float f8 = f6 / f7; f8 += (float)(z + offset); GL11.glTranslatef(px, py, f8); GL11.glTexGeni(8192, 9472, 9217); GL11.glTexGeni(8193, 9472, 9217); GL11.glTexGeni(8194, 9472, 9217); GL11.glTexGeni(8195, 9472, 9216); GL11.glTexGen(8192, 9473, this.calcFloatBuffer(1.0f, 0.0f, 0.0f, 0.0f)); GL11.glTexGen(8193, 9473, this.calcFloatBuffer(0.0f, 1.0f, 0.0f, 0.0f)); GL11.glTexGen(8194, 9473, this.calcFloatBuffer(0.0f, 0.0f, 0.0f, 1.0f)); GL11.glTexGen(8195, 9474, this.calcFloatBuffer(0.0f, 0.0f, 1.0f, 0.0f)); GL11.glEnable(3168); GL11.glEnable(3169); GL11.glEnable(3170); GL11.glEnable(3171); GL11.glPopMatrix(); GL11.glMatrixMode(5890); GL11.glPushMatrix(); GL11.glLoadIdentity(); GL11.glTranslatef(0.0f, System.currentTimeMillis() % 700000L / 250000.0f, 0.0f); GL11.glScalef(f3, f3, f3); GL11.glTranslatef(0.5f, 0.5f, 0.0f); GL11.glRotatef((i * i * 4321 + i * 9) * 2.0f, 0.0f, 0.0f, 1.0f); GL11.glTranslatef(-0.5f, -0.5f, 0.0f); GL11.glTranslatef(-px, -py, -pz); GL11.glTranslatef(ActiveRenderInfo.objectX * f2 / f6, ActiveRenderInfo.objectY * f2 / f6, -pz); final Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); f8 = random.nextFloat() * 0.5f + 0.1f; float f9 = random.nextFloat() * 0.5f + 0.4f; float f10 = random.nextFloat() * 0.5f + 0.5f; if (i == 0) { f9 = (f8 = (f10 = 1.0f)); } tessellator.setBrightness(180); tessellator.setColorRGBA_F(f8 * f4, f9 * f4, f10 * f4, 1.0f); tessellator.addVertex(x, y + 1.0, z + offset); tessellator.addVertex(x, y, z + offset); tessellator.addVertex(x + 1.0, y, z + offset); tessellator.addVertex(x + 1.0, y + 1.0, z + offset); tessellator.draw(); GL11.glPopMatrix(); GL11.glMatrixMode(5888); } } else { GL11.glPushMatrix(); bindTexture(this.t3); final Tessellator tessellator2 = Tessellator.instance; tessellator2.startDrawingQuads(); tessellator2.setBrightness(180); tessellator2.addVertexWithUV(x, y + 1.0, z + offset, 1.0, 1.0); tessellator2.addVertexWithUV(x, y, z + offset, 1.0, 0.0); tessellator2.addVertexWithUV(x + 1.0, y, z + offset, 0.0, 0.0); tessellator2.addVertexWithUV(x + 1.0, y + 1.0, z + offset, 0.0, 1.0); tessellator2.draw(); GL11.glPopMatrix(); } GL11.glDisable(3042); GL11.glDisable(3168); GL11.glDisable(3169); GL11.glDisable(3170); GL11.glDisable(3171); GL11.glEnable(2896); } public void drawPlaneZPos(final double x, final double y, final double z, final float f) { final float px = (float)TileEntityRendererDispatcher.staticPlayerX; final float py = (float)TileEntityRendererDispatcher.staticPlayerY; final float pz = (float)TileEntityRendererDispatcher.staticPlayerZ; GL11.glDisable(2896); final Random random = new Random(31100L); final float offset = 0.0f; if (this.inrange) { for (int i = 0; i < 16; ++i) { GL11.glPushMatrix(); float f2 = 16 - i; float f3 = 0.0625f; float f4 = 1.0f / (f2 + 1.0f); if (i == 0) { bindTexture(this.t1); f4 = 0.1f; f2 = 65.0f; f3 = 0.125f; GL11.glEnable(3042); GL11.glBlendFunc(770, 771); } if (i == 1) { bindTexture(this.t2); GL11.glEnable(3042); GL11.glBlendFunc(1, 1); f3 = 0.5f; } final float f5 = (float)(z + offset); final float f6 = f5 - ActiveRenderInfo.objectZ; final float f7 = f5 + f2 - ActiveRenderInfo.objectZ; float f8 = f6 / f7; f8 += (float)(z + offset); GL11.glTranslatef(px, py, f8); GL11.glTexGeni(8192, 9472, 9217); GL11.glTexGeni(8193, 9472, 9217); GL11.glTexGeni(8194, 9472, 9217); GL11.glTexGeni(8195, 9472, 9216); GL11.glTexGen(8192, 9473, this.calcFloatBuffer(1.0f, 0.0f, 0.0f, 0.0f)); GL11.glTexGen(8193, 9473, this.calcFloatBuffer(0.0f, 1.0f, 0.0f, 0.0f)); GL11.glTexGen(8194, 9473, this.calcFloatBuffer(0.0f, 0.0f, 0.0f, 1.0f)); GL11.glTexGen(8195, 9474, this.calcFloatBuffer(0.0f, 0.0f, 1.0f, 0.0f)); GL11.glEnable(3168); GL11.glEnable(3169); GL11.glEnable(3170); GL11.glEnable(3171); GL11.glPopMatrix(); GL11.glMatrixMode(5890); GL11.glPushMatrix(); GL11.glLoadIdentity(); GL11.glTranslatef(0.0f, System.currentTimeMillis() % 700000L / 250000.0f, 0.0f); GL11.glScalef(f3, f3, f3); GL11.glTranslatef(0.5f, 0.5f, 0.0f); GL11.glRotatef((i * i * 4321 + i * 9) * 2.0f, 0.0f, 0.0f, 1.0f); GL11.glTranslatef(-0.5f, -0.5f, 0.0f); GL11.glTranslatef(-px, -py, -pz); GL11.glTranslatef(ActiveRenderInfo.objectX * f2 / f6, ActiveRenderInfo.objectY * f2 / f6, -pz); final Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); f8 = random.nextFloat() * 0.5f + 0.1f; float f9 = random.nextFloat() * 0.5f + 0.4f; float f10 = random.nextFloat() * 0.5f + 0.5f; if (i == 0) { f9 = (f8 = (f10 = 1.0f)); } tessellator.setBrightness(180); tessellator.setColorRGBA_F(f8 * f4, f9 * f4, f10 * f4, 1.0f); tessellator.addVertex(x, y, z + offset); tessellator.addVertex(x, y + 1.0, z + offset); tessellator.addVertex(x + 1.0, y + 1.0, z + offset); tessellator.addVertex(x + 1.0, y, z + offset); tessellator.draw(); GL11.glPopMatrix(); GL11.glMatrixMode(5888); } } else { GL11.glPushMatrix(); bindTexture(this.t3); final Tessellator tessellator2 = Tessellator.instance; tessellator2.startDrawingQuads(); tessellator2.setBrightness(180); tessellator2.addVertexWithUV(x, y, z + offset, 1.0, 1.0); tessellator2.addVertexWithUV(x, y + 1.0, z + offset, 1.0, 0.0); tessellator2.addVertexWithUV(x + 1.0, y + 1.0, z + offset, 0.0, 0.0); tessellator2.addVertexWithUV(x + 1.0, y, z + offset, 0.0, 1.0); tessellator2.draw(); GL11.glPopMatrix(); } GL11.glDisable(3042); GL11.glDisable(3168); GL11.glDisable(3169); GL11.glDisable(3170); GL11.glDisable(3171); GL11.glEnable(2896); } public void drawPlaneXNeg(final double x, final double y, final double z, final float f) { final float px = (float)TileEntityRendererDispatcher.staticPlayerX; final float py = (float)TileEntityRendererDispatcher.staticPlayerY; final float pz = (float)TileEntityRendererDispatcher.staticPlayerZ; GL11.glDisable(2896); final Random random = new Random(31100L); final float offset = 1.0f; if (this.inrange) { for (int i = 0; i < 16; ++i) { GL11.glPushMatrix(); float f2 = 16 - i; float f3 = 0.0625f; float f4 = 1.0f / (f2 + 1.0f); if (i == 0) { bindTexture(this.t1); f4 = 0.1f; f2 = 65.0f; f3 = 0.125f; GL11.glEnable(3042); GL11.glBlendFunc(770, 771); } if (i == 1) { bindTexture(this.t2); GL11.glEnable(3042); GL11.glBlendFunc(1, 1); f3 = 0.5f; } final float f5 = (float)(-(x + offset)); final float f6 = f5 + ActiveRenderInfo.objectX; final float f7 = f5 + f2 + ActiveRenderInfo.objectX; float f8 = f6 / f7; f8 += (float)(x + offset); GL11.glTranslatef(f8, py, pz); GL11.glTexGeni(8192, 9472, 9217); GL11.glTexGeni(8193, 9472, 9217); GL11.glTexGeni(8194, 9472, 9217); GL11.glTexGeni(8195, 9472, 9216); GL11.glTexGen(8193, 9473, this.calcFloatBuffer(0.0f, 1.0f, 0.0f, 0.0f)); GL11.glTexGen(8192, 9473, this.calcFloatBuffer(0.0f, 0.0f, 1.0f, 0.0f)); GL11.glTexGen(8194, 9473, this.calcFloatBuffer(0.0f, 0.0f, 0.0f, 1.0f)); GL11.glTexGen(8195, 9474, this.calcFloatBuffer(1.0f, 0.0f, 0.0f, 0.0f)); GL11.glEnable(3168); GL11.glEnable(3169); GL11.glEnable(3170); GL11.glEnable(3171); GL11.glPopMatrix(); GL11.glMatrixMode(5890); GL11.glPushMatrix(); GL11.glLoadIdentity(); GL11.glTranslatef(0.0f, System.currentTimeMillis() % 700000L / 250000.0f, 0.0f); GL11.glScalef(f3, f3, f3); GL11.glTranslatef(0.5f, 0.5f, 0.0f); GL11.glRotatef((i * i * 4321 + i * 9) * 2.0f, 0.0f, 0.0f, 1.0f); GL11.glTranslatef(-0.5f, -0.5f, 0.0f); GL11.glTranslatef(-pz, -py, -px); GL11.glTranslatef(ActiveRenderInfo.objectZ * f2 / f6, ActiveRenderInfo.objectY * f2 / f6, -px); final Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); f8 = random.nextFloat() * 0.5f + 0.1f; float f9 = random.nextFloat() * 0.5f + 0.4f; float f10 = random.nextFloat() * 0.5f + 0.5f; if (i == 0) { f9 = (f8 = (f10 = 1.0f)); } tessellator.setBrightness(180); tessellator.setColorRGBA_F(f8 * f4, f9 * f4, f10 * f4, 1.0f); tessellator.addVertex(x + offset, y + 1.0, z); tessellator.addVertex(x + offset, y + 1.0, z + 1.0); tessellator.addVertex(x + offset, y, z + 1.0); tessellator.addVertex(x + offset, y, z); tessellator.draw(); GL11.glPopMatrix(); GL11.glMatrixMode(5888); } } else { GL11.glPushMatrix(); bindTexture(this.t3); final Tessellator tessellator2 = Tessellator.instance; tessellator2.startDrawingQuads(); tessellator2.setBrightness(180); tessellator2.addVertexWithUV(x + offset, y + 1.0, z, 1.0, 1.0); tessellator2.addVertexWithUV(x + offset, y + 1.0, z + 1.0, 1.0, 0.0); tessellator2.addVertexWithUV(x + offset, y, z + 1.0, 0.0, 0.0); tessellator2.addVertexWithUV(x + offset, y, z, 0.0, 1.0); tessellator2.draw(); GL11.glPopMatrix(); } GL11.glDisable(3042); GL11.glDisable(3168); GL11.glDisable(3169); GL11.glDisable(3170); GL11.glDisable(3171); GL11.glEnable(2896); } public void drawPlaneXPos(final double x, final double y, final double z, final float f) { final float px = (float)TileEntityRendererDispatcher.staticPlayerX; final float py = (float)TileEntityRendererDispatcher.staticPlayerY; final float pz = (float)TileEntityRendererDispatcher.staticPlayerZ; GL11.glDisable(2896); final Random random = new Random(31100L); final float offset = 0.0f; if (this.inrange) { for (int i = 0; i < 16; ++i) { GL11.glPushMatrix(); float f2 = 16 - i; float f3 = 0.0625f; float f4 = 1.0f / (f2 + 1.0f); if (i == 0) { bindTexture(this.t1); f4 = 0.1f; f2 = 65.0f; f3 = 0.125f; GL11.glEnable(3042); GL11.glBlendFunc(770, 771); } if (i == 1) { bindTexture(this.t2); GL11.glEnable(3042); GL11.glBlendFunc(1, 1); f3 = 0.5f; } final float f5 = (float)(x + offset); final float f6 = f5 - ActiveRenderInfo.objectX; final float f7 = f5 + f2 - ActiveRenderInfo.objectX; float f8 = f6 / f7; f8 += (float)(x + offset); GL11.glTranslatef(f8, py, pz); GL11.glTexGeni(8192, 9472, 9217); GL11.glTexGeni(8193, 9472, 9217); GL11.glTexGeni(8194, 9472, 9217); GL11.glTexGeni(8195, 9472, 9216); GL11.glTexGen(8193, 9473, this.calcFloatBuffer(0.0f, 1.0f, 0.0f, 0.0f)); GL11.glTexGen(8192, 9473, this.calcFloatBuffer(0.0f, 0.0f, 1.0f, 0.0f)); GL11.glTexGen(8194, 9473, this.calcFloatBuffer(0.0f, 0.0f, 0.0f, 1.0f)); GL11.glTexGen(8195, 9474, this.calcFloatBuffer(1.0f, 0.0f, 0.0f, 0.0f)); GL11.glEnable(3168); GL11.glEnable(3169); GL11.glEnable(3170); GL11.glEnable(3171); GL11.glPopMatrix(); GL11.glMatrixMode(5890); GL11.glPushMatrix(); GL11.glLoadIdentity(); GL11.glTranslatef(0.0f, System.currentTimeMillis() % 700000L / 250000.0f, 0.0f); GL11.glScalef(f3, f3, f3); GL11.glTranslatef(0.5f, 0.5f, 0.0f); GL11.glRotatef((i * i * 4321 + i * 9) * 2.0f, 0.0f, 0.0f, 1.0f); GL11.glTranslatef(-0.5f, -0.5f, 0.0f); GL11.glTranslatef(-pz, -py, -px); GL11.glTranslatef(ActiveRenderInfo.objectZ * f2 / f6, ActiveRenderInfo.objectY * f2 / f6, -px); final Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); f8 = random.nextFloat() * 0.5f + 0.1f; float f9 = random.nextFloat() * 0.5f + 0.4f; float f10 = random.nextFloat() * 0.5f + 0.5f; if (i == 0) { f9 = (f8 = (f10 = 1.0f)); } tessellator.setBrightness(180); tessellator.setColorRGBA_F(f8 * f4, f9 * f4, f10 * f4, 1.0f); tessellator.addVertex(x + offset, y, z); tessellator.addVertex(x + offset, y, z + 1.0); tessellator.addVertex(x + offset, y + 1.0, z + 1.0); tessellator.addVertex(x + offset, y + 1.0, z); tessellator.draw(); GL11.glPopMatrix(); GL11.glMatrixMode(5888); } } else { GL11.glPushMatrix(); bindTexture(this.t3); final Tessellator tessellator2 = Tessellator.instance; tessellator2.startDrawingQuads(); tessellator2.setBrightness(180); tessellator2.addVertexWithUV(x + offset, y, z, 1.0, 1.0); tessellator2.addVertexWithUV(x + offset, y, z + 1.0, 1.0, 0.0); tessellator2.addVertexWithUV(x + offset, y + 1.0, z + 1.0, 0.0, 0.0); tessellator2.addVertexWithUV(x + offset, y + 1.0, z, 0.0, 1.0); tessellator2.draw(); GL11.glPopMatrix(); } GL11.glDisable(3042); GL11.glDisable(3168); GL11.glDisable(3169); GL11.glDisable(3170); GL11.glDisable(3171); GL11.glEnable(2896); } private FloatBuffer calcFloatBuffer(final float f, final float f1, final float f2, final float f3) { this.fBuffer.clear(); this.fBuffer.put(f).put(f1).put(f2).put(f3); this.fBuffer.flip(); return this.fBuffer; } }
package com.mythosapps.time15.util; import com.mythosapps.time15.storage.CsvFileLineWrongException; import com.mythosapps.time15.types.BeginEndTask; import com.mythosapps.time15.types.DaysDataNew; import com.mythosapps.time15.types.KindOfDay; import com.mythosapps.time15.types.Time15; /** * Utility class to work with csv files or rather, csv input streams. */ public final class CsvUtils { public static final String[] CSV_TASK_COLUMNS = {"Task", "Begin", "End", "Break", "Total", "Note"}; private static final String CSV_ID_COLUMN = "Date"; public static int CSV_LINE_LENGTH_A; public static int CSV_LINE_LENGTH_B; static { CSV_LINE_LENGTH_A = 2 + CSV_TASK_COLUMNS.length; CSV_LINE_LENGTH_B = 2 + 2 * CSV_TASK_COLUMNS.length; } public static String toCsvLine(DaysDataNew data) { if (data.getNumberOfTasks() == 0) { return null; } StringBuilder s = new StringBuilder(data.getId() + ","); for (int i = 0; i < data.getNumberOfTasks(); i++) { BeginEndTask taskB = data.getTask(i); s.append(taskB.getKindOfDay()).append(","); if (taskB.getBegin() == null || taskB.getBegin15() == null) { s.append(","); } else { s.append(new Time15(taskB.getBegin(), taskB.getBegin15()).toDisplayString()).append(","); } if (taskB.getEnd() == null || taskB.getEnd15() == null) { s.append(","); } else { s.append(new Time15(taskB.getEnd(), taskB.getEnd15()).toDisplayString()).append(","); } if (taskB.getPause() == null) { s.append(","); } else { s.append(Time15.fromMinutes(taskB.getPause()).toDisplayString()).append(","); } s.append(taskB.getTotal().toDecimalFormat()).append(","); s.append(taskB.getNote() == null ? "" : taskB.getNote()).append(","); } return s.toString(); } public static DaysDataNew fromCsvLine(String csvString) throws CsvFileLineWrongException { String id = "unknown"; String errMsg = "no error"; DaysDataNew data = new DaysDataNew(id); try { errMsg = "Datum wird in der ersten Spalte erwartet!"; String[] line = csvString.split(",", -1); if (line.length > 0) { id = line[0]; } data.setId(id); errMsg = "Spalten B bis G sollten die Werte für den ersten Task enthalten!"; if (line.length < CSV_LINE_LENGTH_A) { errMsg = "Spalten B bis G müssen vorhanden sein!"; } BeginEndTask task0 = toBeginEndTask(id, line[1], line[2], line[3], line[4], line[5], line[6]); data.addTask(task0); if (line.length >= CSV_LINE_LENGTH_B) { errMsg = "Spalten H bis M sollten die Werte für den zweiten Task enthalten, falls vorhanden!"; BeginEndTask task1 = toBeginEndTask(id, line[7], line[8], line[9], line[10], line[11], line[12]); data.addTask(task1); } } catch (Throwable t) { // error while reading task from String, might result in Task.isComplete == false } // ignore rest of csvString return data; } private static BeginEndTask toBeginEndTask(String id, String kindOfTask, String begin, String end, String breakString, String total, String note) throws CsvFileLineWrongException { BeginEndTask task = new BeginEndTask(); try { // can: simplify String displayString = safeGetNextToken(kindOfTask, id, "Task"); task.setKindOfDay(KindOfDay.fromString(displayString)); String s = safeGetNextTokenOptional(begin, id, "Begin"); Time15 beginTime = toTime15(s); if (beginTime != null) { task.setBegin(beginTime.getHours()); task.setBegin15(beginTime.getMinutes()); } s = safeGetNextTokenOptional(end, id, "End"); Time15 endTime = toTime15(s); if (endTime != null) { task.setEnd(endTime.getHours()); task.setEnd15(endTime.getMinutes()); } s = safeGetNextTokenOptional(breakString, id, "Pause"); Time15 pauseTime = toTime15(s); if (pauseTime != null) { task.setPause(pauseTime.toMinutes()); } s = safeGetNextTokenOptional(total, id, "Total"); Time15 totalTime = toTime15FromDecimal(s); if (totalTime != null) { task.setTotal(totalTime); } s = safeGetNextTokenOptional(note, id, "Note"); task.setNote(s); if (task.getKindOfDay() == null) { task.setKindOfDay(KindOfDay.convert(displayString, task.getBegin(), task.getEnd())); } } catch (Throwable t) { // error while reading task from String, might result in Task.isComplete == false } return task; } private static Time15 toTime15(String s) { Time15 time15 = null; try { time15 = Time15.fromDisplayString(s); } catch (Throwable t) { // ignore } return time15; } private static Time15 toTime15FromDecimal(String s) { Time15 time15 = null; try { time15 = Time15.fromDecimalFormat(s); } catch (Throwable t) { // ignore } return time15; } private static String safeGetNextTokenOptional(String s, String id, String expected) throws CsvFileLineWrongException { if (s == null || s.trim().isEmpty()) { return null; } return s.trim(); } private static String safeGetNextToken(String s, String id, String expected) throws CsvFileLineWrongException { if (s == null || s.isEmpty()) { String msg = "load csv " + id + " missing: " + expected; throw new CsvFileLineWrongException(id, msg); } return s.trim(); } public static String getHeadline() { return CSV_ID_COLUMN + "," + "Task,Begin,End,Break,Total,Note" + "," + "Task,Begin,End,Break,Total,Note"; } }
package com.tencent.mm.plugin.wallet.bind.a; import com.tencent.mm.ab.e; import com.tencent.mm.network.q; import com.tencent.mm.plugin.wallet.a.p; import com.tencent.mm.plugin.wallet_core.model.ag; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.wallet_core.c.m; public final class b extends m { private com.tencent.mm.ab.b diG; private e diJ; private String pct; public final void e(int i, int i2, String str, q qVar) { x.d("MicroMsg.NetSceneSetMainBankCard", "errType:" + i + ",errCode:" + i2 + ",errMsg" + str); if (i == 0 && i2 == 0) { p.bNp(); p.bNq(); ag.Pc(this.pct); } this.diJ.a(i, i2, str, this); } public final int getType() { return 621; } public final int a(com.tencent.mm.network.e eVar, e eVar2) { this.diJ = eVar2; return a(eVar, this.diG, this); } }
package org.sbbs.base.pager; /** * * */ public interface IPagerParameters { String getSortNameKey(); String getPageNumberKey(); String getSortDirectionKey(); String getPageSizeKey(); }
package src; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import model.R; import org.junit.Test; public class PublishPaneTest { PublishPane publishPane = new PublishPane(); /** * . */ @Test public void testGetCheckType_() { publishPane.getCheckType(); publishPane.chckbxSelectParent.setSelected(false); publishPane.chckbxSelectChildren.setSelected(false); assertThat(publishPane.getCheckType(), is("")); } /** * . */ @Test public void testGetCheckType_p() { publishPane.getCheckType(); publishPane.chckbxSelectParent.setSelected(true); publishPane.chckbxSelectChildren.setSelected(false); assertThat(publishPane.getCheckType(), is(R.PARENT)); } /** * . */ @Test public void testGetCheckType_c() { publishPane.getCheckType(); publishPane.chckbxSelectParent.setSelected(false); publishPane.chckbxSelectChildren.setSelected(true); assertThat(publishPane.getCheckType(), is(R.SUBNODES)); } /** * . */ @Test public void testGetCheckType_pc() { publishPane.getCheckType(); publishPane.chckbxSelectParent.setSelected(true); publishPane.chckbxSelectChildren.setSelected(true); assertThat(publishPane.getCheckType(), is(R.SUBNODES_AND_PARENT)); } }
package com.minipg.fanster.armoury.object; /** * Created by Knot on 8/17/2017. */ public class TopicForm { String title; String link; String description; String category; public TopicForm(){ } public TopicForm(String title, String link, String description, String category) { this.title = title; this.link = link; this.description = description; this.category = category; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getLink() { return link; } public void setLink(String link) { this.link = link; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getForm(){ return "{ "+title+" "+link+" "+description+" "+category+" }"; } }
package great_class28; import java.util.ArrayList; import java.util.List; /** * Created by likz on 2023/4/21 * * @author likz */ public class Problem_0017_LetterCombinationsOfAPhoneNumber { public static char[][] phone = new char[][]{ {'a', 'b', 'c'}, {'d', 'e', 'f'}, {'g', 'h', 'i'}, {'j', 'k', 'l'}, {'m', 'n', 'o'}, {'p', 'q', 'r', 's'}, {'t', 'u', 'v'}, {'w', 'x', 'y', 'z'}, }; public List<String> letterCombinations(String digits) { if (digits == null || digits.length() == 0){ return new ArrayList<>(); } List<String> ans = new ArrayList<>(); char[] str = digits.toCharArray(); // 保存结果字符串 char[] path = new char[str.length]; // dfs dfs(str, 0, path, ans); return ans; } public static void dfs(char[] str, int index, char[] path, List<String> ans) { if (str.length == index){ ans.add(String.valueOf(path)); } else { char[] phoneStr = phone[str[index] - '2']; for (char e : phoneStr){ path[index] = e; dfs(str, index + 1, path, ans); } } } }
/* * MetricComparator - Does the actual fusion of the analysis * components. Part of the UBC CPSC 410 yardwand project. * * Author: Eric Furugori */ package fusion; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import models.Activity; import models.Repository; import models.Stat; import models.CollaboratorsActivities; import analysis.CodeDuplicationDetector; import analysis.NewCollaboratorDetector; public class MetricComparator { private Repository repo1; private Repository repo2; private List<Stat> repo1StatList; private List<Stat> repo2StatList; /** * Generate velocities and weights (bloat) given two repositories. * MetricComparator sends requests to the analysis Detectors and * fuses them into two <code>Stat</code> lists. * @param repo1 * A <code>Repository</code> to be compared against repo2. * @param repo2 * A <code>Repository</code> to be compared against repo1. */ public MetricComparator(Repository repo1, Repository repo2) { this.repo1 = repo1; this.repo2 = repo2; generateStats(); } /** * Reads from the <code>CodeDuplicationDetector</code>s and the <code> * NewCollaboratorDetector</code>s to populate two lists of <code>Stat</code> * to be used in the Play Framework. * * This routine is called upon the creation of the object. */ private void generateStats() { NewCollaboratorDetector ncd1 = new NewCollaboratorDetector(repo1.getContributorURL()); NewCollaboratorDetector ncd2 = new NewCollaboratorDetector(repo2.getContributorURL()); CollaboratorsActivities analysis1 = ncd1.getAnalysis(); CollaboratorsActivities analysis2 = ncd2.getAnalysis(); HashMap<Double, Activity> map1 = analysis1.getActivities(); HashMap<Double, Activity> map2 = analysis2.getActivities(); Iterator<Entry<Double, Activity>> it1 = map1.entrySet().iterator(); Iterator<Entry<Double, Activity>> it2 = map2.entrySet().iterator(); List<Integer> weeklyCommits1 = new ArrayList<Integer>(); List<Integer> weeklyCommits2 = new ArrayList<Integer>(); List<Double> commitWeeks1 = new ArrayList<Double>(); List<Double> commitWeeks2 = new ArrayList<Double>(); while (it1.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry pairs = (Map.Entry) it1.next(); Activity a = (Activity) pairs.getValue(); weeklyCommits1.add(a.getCommits()); } while (it2.hasNext()) { @SuppressWarnings("rawtypes") Map.Entry pairs = (Map.Entry) it2.next(); Activity a = (Activity) pairs.getValue(); weeklyCommits2.add(a.getCommits()); } commitWeeks1.addAll(map1.keySet()); commitWeeks2.addAll(map2.keySet()); CodeDuplicationDetector cdd = new CodeDuplicationDetector(); HashMap<Double, String> duplicationMap1 = cdd.getRepo1DuplicationAnalysis(); HashMap<Double, String> duplicationMap2 = cdd.getRepo2DuplicationAnalysis(); List<String> duplicationStrings1 = buildDuplicationList(duplicationMap1, commitWeeks1); List<String> duplicationStrings2 = buildDuplicationList(duplicationMap2, commitWeeks2); StatListBuilder slb1 = new StatListBuilder(duplicationStrings1, weeklyCommits1); StatListBuilder slb2 = new StatListBuilder(duplicationStrings2, weeklyCommits2); repo1StatList = slb1.getStats(); repo2StatList = slb2.getStats(); } public List<String> buildDuplicationList( HashMap<Double, String> duplicationMap, List<Double> commitWeeks) { List<String> duplicationStrings = new ArrayList<String>(); double key; for (double w : commitWeeks) { if (duplicationMap.keySet().iterator().hasNext()) { if ((key = duplicationMap.keySet().iterator().next()) < w) { duplicationStrings.add(duplicationMap.get(key)); duplicationMap.remove(key); } else { duplicationStrings.add(""); } } } return duplicationStrings; } /** * Get the list of <code>Stat</code> objects containing weights and * step sizes in weekly intervals corresponding to repository 1. * @return */ public List<Stat> getRepo1StatList() { return repo1StatList; } /** * Get the list of <code>Stat</code> objects containing weights and * step sizes in weekly intervals corresponding to repository 2. * @return */ public List<Stat> getRepo2StatList() { return repo2StatList; } }
package com.tencent.mm.plugin.fav.ui.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import com.tencent.mm.plugin.fav.ui.m.b; import com.tencent.mm.plugin.fav.ui.m.e; import com.tencent.mm.plugin.fav.ui.m.i; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.sdk.platformtools.bi; import java.util.LinkedList; import java.util.List; public class FavSearchActionView extends LinearLayout { public FavTagPanel jat; public List<Integer> jbK = new LinkedList(); public a jfA; private ImageButton jfw; private ImageView jfx; public List<String> jfy = new LinkedList(); public List<String> jfz = new LinkedList(); public FavSearchActionView(Context context, AttributeSet attributeSet) { super(context, attributeSet); } protected void onFinishInflate() { super.onFinishInflate(); this.jfw = (ImageButton) findViewById(e.search_clear_button); this.jat = (FavTagPanel) findViewById(e.fav_tag_input_panel); this.jfx = (ImageView) findViewById(e.ab_back_btn); if (this.jat != null) { this.jat.setEditTextColor(getResources().getColor(b.black_text_color)); this.jat.setTagTipsDrawable(0); this.jat.setTagHighlineBG(0); this.jat.setTagSelectedBG(0); this.jat.setTagSelectedTextColorRes(b.green_text_color); this.jat.setTagNormalBG(0); this.jat.setTagNormalTextColorRes(b.white); this.jat.setEditHint(getResources().getString(i.app_search)); this.jat.lL(true); this.jat.txD = false; this.jat.txE = true; this.jat.setCallBack(new 1(this)); } if (this.jfw != null) { this.jfw.setOnClickListener(new 2(this)); } } /* renamed from: BG */ public final void a(String str) { this.jfz.clear(); for (String str2 : bi.aG(str, "").split(" ")) { if (!bi.oW(str2)) { this.jfz.add(str2); } } } public void setOnSearchChangedListener(a aVar) { this.jfA = aVar; } public List<String> getSearchKeys() { if (this.jat != null) { a(this.jat.getEditText()); } return this.jfz; } public List<String> getSearchTags() { return this.jfy; } private void aMT() { if (this.jbK.isEmpty() && this.jfy.isEmpty()) { this.jat.setEditHint(getResources().getString(i.app_search)); } else { this.jat.setEditHint(""); } } public void setType(int i) { this.jbK.clear(); this.jbK.add(Integer.valueOf(i)); if (this.jat != null) { String string; aMT(); FavTagPanel favTagPanel = this.jat; Context context = getContext(); if (context != null) { switch (i) { case 1: string = context.getString(i.favorite_sub_title_chat); break; case 2: string = context.getString(i.favorite_sub_title_image); break; case 3: string = context.getString(i.favorite_sub_title_voice); break; case 4: string = context.getString(i.favorite_sub_title_video); break; case 5: string = context.getString(i.favorite_sub_title_url); break; case 6: string = context.getString(i.favorite_sub_title_location); break; case 7: string = context.getString(i.favorite_sub_title_music); break; case 8: string = context.getString(i.favorite_sub_title_file); break; } } string = ""; favTagPanel.setType(string); if (this.jfA != null) { a(this.jat.getEditText()); this.jfA.a(this.jbK, this.jfz, this.jfy, false); h.mEJ.h(11126, new Object[]{Integer.valueOf(1)}); } } } public static Integer af(Context context, String str) { if (context == null) { return Integer.valueOf(-1); } if (context.getString(i.favorite_sub_title_image).equals(str)) { return Integer.valueOf(2); } if (context.getString(i.favorite_sub_title_music).equals(str)) { return Integer.valueOf(7); } if (context.getString(i.favorite_sub_title_location).equals(str)) { return Integer.valueOf(6); } if (context.getString(i.favorite_sub_title_chat).equals(str)) { return Integer.valueOf(1); } if (context.getString(i.favorite_sub_title_video).equals(str)) { return Integer.valueOf(4); } if (context.getString(i.favorite_sub_title_url).equals(str)) { return Integer.valueOf(5); } if (context.getString(i.favorite_sub_title_voice).equals(str)) { return Integer.valueOf(3); } if (context.getString(i.favorite_sub_title_file).equals(str)) { return Integer.valueOf(8); } return Integer.valueOf(-1); } }
package com.smelending.kotak; import java.io.PrintWriter; import java.io.StringWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Date; import org.apache.log4j.Logger; public class initiateSettlement extends saveSettlement { private static Logger logger = Logger.getLogger(initiateSettlement.class); /*`id` bigint(20) NOT NULL auto_increment, `time` datetime NOT NULL, `basis` char(2) collate latin1_bin NOT NULL COMMENT '1:bank basis,2 : time basis,3 : merchant basis ,4 : others', `reason` char(2) collate latin1_bin NOT NULL COMMENT '1: cash limit ,2:transaction limit ,3:EOD 4:others', `type` char(2) collate latin1_bin NOT NULL COMMENT '1:Automatic 2:manual', `user_id` bigint(20) default NULL COMMENT 'If type = 2,not null', `bankterminalid` varchar(20) collate latin1_bin default NULL, `batchno` varchar(6) collate latin1_bin NOT NULL, `settledamount` varchar(15) collate latin1_bin default NULL, `transactioncount` varchar(6) collate latin1_bin default NULL,*/ public String doSettlementIntiation(Connection con,Date setDate){ logger.info("inside :doSettlementIntiation() method"); String query="insert into settlement (time,basis,reason,type,batchno) values(?,?,?,?,?)"; PreparedStatement pstmt; String date =new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(setDate); try { pstmt = con.prepareStatement(query); if(pstmt!=null){ pstmt.setString(1,date); pstmt.setString(2, "02"); pstmt.setString(3, "03"); pstmt.setString(4, "01"); pstmt.setString(5, dbQueires.getCurrentBatchno(con)); int rows = pstmt.executeUpdate(); logger.info("Response after temp_transaction database update : "+rows); if(rows>=1){ return getSettlementId(con, date); } } }catch(Exception e){ } return null; } public String getSettlementId(Connection con,String settlementDate){ logger.info("calling getSettlementId ............."+settlementDate); String query="select id as id from settlement where time='"+settlementDate+"'"; ResultSet rs= null; try { rs=con.createStatement().executeQuery(query); if(rs.next()){ return rs.getString("id"); } } catch (SQLException e) { // TODO Auto-generated catch block StringWriter stack = new StringWriter(); e.printStackTrace(new PrintWriter(stack)); logger.info("Caught exception; during action : " + stack.toString()); } return null; } public static void main(String[] args) { // TODO Auto-generated method stub } }
package com.rc.portal.alipay.config; import com.rc.commons.util.InfoUtil; /* * *类名:AlipayConfig *功能:基础配置类 *详细:设置帐户有关信息及返回路径 *版本:3.3 *日期:2012-08-10 *说明: *以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。 *该代码仅供学习和研究支付宝接口使用,只是提供一个参考。 *提示:如何获取安全校验码和合作身份者ID *1.用您的签约支付宝账号登录支付宝网站(www.alipay.com) *2.点击“商家服务”(https://b.alipay.com/order/myOrder.htm) *3.点击“查询合作者身份(PID)”、“查询安全校验码(Key)” *安全校验码查看时,输入支付密码后,页面呈灰色的现象,怎么办? *解决方法: *1、检查浏览器配置,不让浏览器做弹框屏蔽设置 *2、更换浏览器或电脑,重新登录查询。 */ public class AlipayConfig { //↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ // 合作身份者ID,以2088开头由16位纯数字组成的字符串 public static String partner= InfoUtil.getInstance().getInfo("alipay","alipay.partner"); // 商户的私钥 public static String key = InfoUtil.getInstance().getInfo("alipay","alipay.key"); public static String return_url="http://www.111yao.com/login/alipayreturnlogin!alipayAction.action"; //↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ // 调试用,创建TXT日志文件夹路径 public static String log_path = "D:\\"; // 签名方式 不需修改 public static String paygateway=""; public static String email= InfoUtil.getInstance().getInfo("alipay","alipay.seller.email"); public static String paymenttype="1"; public static String input_charset= InfoUtil.getInstance().getInfo("alipay","alipay.CharSet"); public static String sign_type= "MD5";//InfoUtil.getInstance().getInfo("alipay","alipay.sign_type"); public static String returnurl= InfoUtil.getInstance().getInfo("config","pay_return_url"); public static String notifyurl= InfoUtil.getInstance().getInfo("config","pay.payServiceUri")+InfoUtil.getInstance().getInfo("config","alipayNotifyUri");//回掉方法; }
package com.khaale.bigdatarampup.mapreduce.hw3.part2; import com.khaale.bigdatarampup.mapreduce.hw3.part2.parsing.BrowserDetector; import com.khaale.bigdatarampup.mapreduce.hw3.part2.parsing.IpDataParser; import com.khaale.bigdatarampup.mapreduce.hw3.part2.writables.IpStatsWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import java.io.IOException; public class IpStatsMapper extends Mapper<LongWritable, Text, Text, IpStatsWritable> { private IpDataParser parser = new IpDataParser(); private BrowserDetector browserDetector = new BrowserDetector(); private Text outKey = new Text(); private IpStatsWritable outValue = new IpStatsWritable(); @Override public void map(LongWritable inputKey, Text inputValue, Context output) throws IOException, InterruptedException { parser.set(inputValue); outKey.set(parser.getIp()); outValue.set(1L, parser.getBiddingPrice()); populateUserAgentCounters(parser.getUserAgent(), output); output.write(outKey, outValue); } private void populateUserAgentCounters(String userAgent, Context output) { Browsers browser = browserDetector.getBrowserByUserAgent(userAgent); output.getCounter(browser).increment(1); } }
/* * 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 Entidades; import java.util.Date; import java.util.List; /** * * @author rosemary */ public class entBrotacion { private int id_brotacion; private entCampaniaLote objCampaniaLote; private entEvaluador objEvaluador; private Date fecha_registro; private Boolean estado; private String usuario_responsable; private Date fecha_modificacion; private List<entCabeceraBrotacion> list; public entBrotacion() { this.list = null; } public int getId_brotacion() { return id_brotacion; } public void setId_brotacion(int id_brotacion) { this.id_brotacion = id_brotacion; } public entCampaniaLote getObjCampaniaLote() { return objCampaniaLote; } public void setObjCampaniaLote(entCampaniaLote objCampaniaLote) { this.objCampaniaLote = objCampaniaLote; } public entEvaluador getObjEvaluador() { return objEvaluador; } public void setObjEvaluador(entEvaluador objEvaluador) { this.objEvaluador = objEvaluador; } public Boolean isEstado() { return estado; } public void setEstado(Boolean estado) { this.estado = estado; } public String getUsuario_responsable() { return usuario_responsable; } public void setUsuario_responsable(String usuario_responsable) { this.usuario_responsable = usuario_responsable; } public Date getFecha_modificacion() { return fecha_modificacion; } public void setFecha_modificacion(Date fecha_modificacion) { this.fecha_modificacion = fecha_modificacion; } public List<entCabeceraBrotacion> getList() { return list; } public void setList(List<entCabeceraBrotacion> list) { this.list = list; } public Date getFecha_registro() { return fecha_registro; } public void setFecha_registro(Date fecha_registro) { this.fecha_registro = fecha_registro; } }
/* * Copyright ApeHat.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.apehat.newyear.event.annotation; import com.apehat.newyear.event.Event; import com.apehat.newyear.event.EventSubscriber; import com.apehat.newyear.validation.annotation.NonNull; import java.lang.annotation.*; /** * Subscribe events by defined {@code EventSubscriber}s. The subscriber must * have an no-parameter constructor. * * @author hanpengfei * @since 1.0 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Subscribe { /** * Subscribe a specified event. * * @return be subscribed event. */ @NonNull Class<? extends Event> evenType(); /** * The subscribers to subscribe specified event. * * @return the subscribes to subscriber */ @NonNull Class<? extends EventSubscriber>[] by(); }
package com.xxx; import java.io.IOException; import org.apache.http.HttpHost; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.unit.TimeValue; /** * @author xujunming * Created on 2020-03-22 */ public class Main01 { public static void main(String[] args) throws IOException { RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( // 指定 ElasticSearch 集群各个节点的地址和端口号 new HttpHost("localhost", 9200, "http"))); // 创建 CreateIndexRequest请求,该请求会创建一个名为"skywalking"的 Index, // 注意,Index 的名称必须是小写 CreateIndexRequest request = new CreateIndexRequest("skywalking"); // 在 CreateIndexRequest请求中设置 Index的 setting信息 request.settings(Settings.builder() .put("index.number_of_shards", 3) // 设置分片数量 .put("index.number_of_replicas", 2) // 设置副本数量 ); // 在 CreateIndexRequest请求中设置 Index的 Mapping信息,新建的 Index里有 // 个user和message两个字段,都为text类型,还有一个 age字段,为 integer类型 request.mapping("type", "user", "type=text", "age", "type=integer", "message", "type=text"); // 设置请求的超时时间 request.timeout(TimeValue.timeValueSeconds(5)); // 发送 CreateIndex请求 CreateIndexResponse response = client.indices().create(request); // 这里关心 CreateIndexResponse响应的 isAcknowledged字段值 // 该字段为 true则表示 ElasticSearch已处理该请求 boolean acknowledged = response.isAcknowledged(); System.out.println(acknowledged); } }
package ru.Makivay.sandbox.utils; import java.util.stream.IntStream; public class SomeUselessStuff { public static void infinityCpuHeat() { IntStream.range(0, Runtime.getRuntime().availableProcessors()*2).parallel().forEach(i -> { while (true) { for (int index = 1; index < Integer.MAX_VALUE; index++) { final int result = Integer.MAX_VALUE % index; } } }); } }
import java.util.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JPanel; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.util.Vector; import java.awt.*; public class Lienzo2 extends JPanel implements MouseListener { private Vector<Nodo> vectorNodos; private Vector<Enlace> vectorEnlaces; private Point p1, p2; public Lienzo2() { this.vectorNodos = new Vector<Nodo>(); this.vectorEnlaces = new Vector<Enlace>(); this.addMouseListener(this); } public void paint(Graphics g) { for(Nodo nodos: vectorNodos) { if(nodos.seleccionado) g.setColor(Color.GREEN); else g.setColor(Color.RED); nodos.pintar(g); } g.setColor(Color.BLACK); for (Enlace enlace : vectorEnlaces) enlace.pintar(g); } public int estanSobrespuestos(int x1, int y1, int x2, int y2, int r1, int r2){ int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0; } public void mouseClicked(MouseEvent e) { if(e.getButton() == MouseEvent.BUTTON1) { this.vectorNodos.add(new Nodo(e.getX(), e.getY(), 80)); repaint(); } if(vectorNodos.size() > 1) { Nodo nodoActual = vectorNodos.lastElement(); p1 = new Point(nodoActual.getX(), nodoActual.getY()); for(int i = 0 ; i < vectorNodos.size() - 1 ; i++){ int val = estanSobrespuestos(nodoActual.getX(), nodoActual.getY(), vectorNodos.get(i).getX(), vectorNodos.get(i).getY(),nodoActual.getD()/2, vectorNodos.get(i).getD()/2); if(val == 0){ p2 = new Point(vectorNodos.get(i).getX(), vectorNodos.get(i).getY()); this.vectorEnlaces.add(new Enlace(p1.x,p1.y,p2.x,p2.y)); repaint(); } } p1 = null; p2 = null; } } }
package com.projects.houronearth.activities.fragments.profile; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.design.widget.BottomSheetDialogFragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.projects.houronearth.R; import com.projects.houronearth.activities.helpers.GenericFileProvider; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import static android.app.Activity.RESULT_OK; public class PictureSelectBottomSheetFragment extends BottomSheetDialogFragment { // TODO: Customize parameter argument names private static final String ARG_ITEM_COUNT = "item_count"; public static final int PickImageFromGallery = 26; public static final int PickImageFromCamera = 27; public static Uri fileUri = null; public static String mCurrentPhotoPath = ""; // TODO: Customize parameters public static PictureSelectBottomSheetFragment newInstance(int itemCount) { final PictureSelectBottomSheetFragment fragment = new PictureSelectBottomSheetFragment(); final Bundle args = new Bundle(); args.putInt(ARG_ITEM_COUNT, itemCount); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_picture_selection, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.list); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setAdapter(new ItemAdapter(imagePickOptions,drawables)); } String[] imagePickOptions = {"Gallery", "Camera"}; Integer[] drawables = {R.drawable.ic_photos_24dp,R.drawable.ic_camera_24dp}; private class ViewHolder extends RecyclerView.ViewHolder { final TextView text; ViewHolder(LayoutInflater inflater, ViewGroup parent) { // TODO: Customize the item layout super(inflater.inflate(R.layout.picture_select_row_layout, parent, false)); text = (TextView) itemView.findViewById(R.id.selectFrom); } } private class ItemAdapter extends RecyclerView.Adapter<ViewHolder> { String[] imagePickOptions; Integer[] drawables; public ItemAdapter(String[] imagePickOptions, Integer[] drawables) { this.imagePickOptions = imagePickOptions; this.drawables = drawables; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()), parent); } @Override public void onBindViewHolder(ViewHolder holder, final int position) { holder.text.setText(imagePickOptions[position]); holder.text.setCompoundDrawablesWithIntrinsicBounds(drawables[position], 0, 0, 0); holder.text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { switch (position) { case 0: Intent in = new Intent(Intent.ACTION_PICK); in.setType("image/*"); ((AppCompatActivity)getContext()).setResult(RESULT_OK, in); ((AppCompatActivity)getContext()).startActivityForResult(in, PickImageFromGallery);// start break; case 1: captureImage(); break; } dismiss(); } }); } @Override public int getItemCount() { return imagePickOptions.length; } } private void captureImage() { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); Log.e("Image file", mCurrentPhotoPath); fileUri = GenericFileProvider.getUriForFile(getContext(), getContext().getPackageName()+ ".provider", createImageFile()); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { intent.putExtra(MediaStore.EXTRA_OUTPUT, getPhotoFileUri()); } else { Uri photoUri = GenericFileProvider.getUriForFile(getContext(), getContext().getPackageName() , createImageFile()); intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); } intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); ((AppCompatActivity)getContext()).setResult(RESULT_OK, intent); ((AppCompatActivity)getContext()).startActivityForResult(intent, PickImageFromCamera); } private File createImageFile() { try { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File storageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM), "Camera"); File image = null; image = File.createTempFile( imageFileName, /* prefix */ ".jpg", /* suffix */ storageDir /* directory */ ); // Save a file: path for use with ACTION_VIEW intents mCurrentPhotoPath = image.getAbsolutePath(); return image; } catch (IOException e) { e.printStackTrace(); return null; } } String TAG = PictureSelectBottomSheetFragment.class.getSimpleName(); // Returns the Uri for a photo stored on disk given the fileName public Uri getPhotoFileUri() { // Create an image file name String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String imageFileName = "JPEG_" + timeStamp + "_"; File fileName = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM), "Camera"); // Get safe storage directory for photos File mediaStorageDir = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Camera"); // Create the storage directory if it does not exist if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){ Log.d(TAG, "failed to create directory"); } // Return the file target for the photo based on filename return Uri.fromFile(new File(mediaStorageDir.getPath() + File.separator + fileName)); } }
package variaveisTipos; public class Variaveis { public static void main(String[] args) { byte pequeno = 10; int numero = 100; short curto = 12; long grande = 120215641L; System.out.println(numero); System.out.println(curto); System.out.println(pequeno); System.out.println(grande); } }
package com.mostlymagic.guava.string.processing; import static java.util.Arrays.asList; import static org.apache.commons.lang3.StringUtils.isEmpty; import static org.apache.commons.lang3.StringUtils.strip; import static org.apache.commons.lang3.StringUtils.stripToEmpty; import static org.apache.commons.lang3.StringUtils.stripToNull; import static org.junit.Assert.assertEquals; import static com.google.common.base.CharMatcher.WHITESPACE; import static com.google.common.base.Strings.commonPrefix; import static com.google.common.base.Strings.commonSuffix; import static com.google.common.base.Strings.emptyToNull; import static com.google.common.base.Strings.isNullOrEmpty; import static com.google.common.base.Strings.nullToEmpty; import static com.google.common.base.Strings.padEnd; import static com.google.common.base.Strings.padStart; import org.junit.Test; import com.google.common.base.Strings; /** * Strings is Guava's own StringUtil variation, thankfully reduced to the minimum. */ public class E_StringsTest { @Test public void testCommonPrefixSuffix() throws Exception { // find the longest common prefix for two CharSequences assertEquals("pter", commonPrefix("pteranodon", "pterodactylus")); assertEquals("ophon", commonSuffix("grammophon", "xylophon")); } @Test public void testIsNullOrEmpty() throws Exception { // ok, so you still miss StringUtils.isEmpty()? Ok, then take this instead: // test to see whether a String is either null or "" for (String s : asList(null, "", " ", "abc")) { assertEquals(s, isNullOrEmpty(s), isEmpty(s)); } } @Test public void testNullToEmptyToNull() throws Exception { // are you missing StringUtils.stripTo*()? // well you can build your own version using nullToEmpty and emptyToNull for (String s : asList(null, "", " \t ", "abc", "d f")) { assertEquals(s, stripToEmpty(s), WHITESPACE.trimFrom(nullToEmpty(s))); assertEquals(s, stripToNull(s), emptyToNull(WHITESPACE.trimFrom(nullToEmpty(s)))); assertEquals(s, strip(s), isNullOrEmpty(s) ? s : WHITESPACE.trimFrom(nullToEmpty(s))); } } @Test public void testPad() throws Exception { // these are roughly equivalent to StringUtils.leftPad() / rightPad() assertEquals("yabba-dabba-dooooooooooooooooo", padEnd("yabba-dabba-doo", 30, 'o')); assertEquals("aaaaaardvark", padStart("aardvark", 12, 'a')); assertEquals("*************************", Strings.repeat("*", 25)); } }
/* * [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.acceleratorfacades.cart.action.exceptions; import de.hybris.platform.acceleratorfacades.cart.action.CartEntryActionHandler; /** * A general exception used by {@link CartEntryActionHandler#handleAction(long)} when an error occurs. */ public class CartEntryActionException extends Exception { public CartEntryActionException(final String message, final Throwable cause) { super(message, cause); } public CartEntryActionException(final String message) { super(message); } }
package studio.baka.originiumcraft.client.gui; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.util.ResourceLocation; public class GuiTransparentButton extends GuiButton { public GuiTransparentButton(GuiScreen parent, int startX, int startY, int width, int height) { super(parent, startX, startY, width, height); init(null,0,0,0,0); } @Override public void draw(int mouthX, int mouthY) { } public void drawPureColor(int mouthX, int mouthY){ GlStateManager.pushMatrix(); { GlStateManager.color(1, 1, 1, 1); if (mouthX >= startX && mouthX <= startX + width && mouthY >= startY && mouthY <= startY + height) Minecraft.getMinecraft().renderEngine.bindTexture(OCGuiResources.GUI_PURE_GREY); else Minecraft.getMinecraft().renderEngine.bindTexture(OCGuiResources.GUI_PURE_BLACK); parent.drawTexturedModalRect(startX, startY, 0, 0, width, height); } GlStateManager.popMatrix(); } }
package jp.co.logacy.dto.search; /** * BD検索用の検索条件保持DTO * * @author y_someya * */ public class ItemsDto { public ItemDto Item; }
package SvgPac; import java.awt.BasicStroke; import java.awt.Graphics; import java.awt.Graphics2D; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; public class SvgEllipse extends SvgShape { public static final long serialVersionUID = 8646427093351643039L; private float cx = 0.0f; private float cy = 0.0f; private float rx = 0.0f; private float ry = 0.0f; public SvgEllipse() { super(); } public void read() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("\tid="); setId(br.readLine()); System.out.print("\tcx="); setCX(Float.parseFloat(br.readLine())); System.out.print("\tcy="); setCY(Float.parseFloat(br.readLine())); System.out.print("\trx="); setRX(Float.parseFloat(br.readLine())); System.out.print("\try="); setRY(Float.parseFloat(br.readLine())); style.read(br); } @Override public void save(PrintStream stream) { stream.printf("\t<ellipse id=\"%s\" cx=\"%s\" cy=\"%s\" ", id, SvgHelper.floatToString(cx), SvgHelper.floatToString(cy)); stream.printf("rx=\"%s\" ry=\"%s\"\n", SvgHelper.floatToString(rx), SvgHelper.floatToString(ry)); stream.printf("\t%s />\n", style.toString()); } @Override public void save(DataOutputStream stream) throws IOException { stream.writeLong(SvgEllipse.serialVersionUID); stream.writeUTF(id); stream.writeFloat(cx); stream.writeFloat(cy); stream.writeFloat(rx); stream.writeFloat(ry); style.save(stream); } @Override public void load(DataInputStream stream) throws IOException { id = stream.readUTF(); cx = stream.readFloat(); cy = stream.readFloat(); rx = stream.readFloat(); ry = stream.readFloat(); style.load(stream); } @Override public void draw(Graphics g) { final float rx1 = rx / 2.0f, ry1 = ry / 2.0f; final int rx2 = Math.round(rx * 2.0f), ry2 = Math.round(ry * 2.0f); if (style.fill) { g.setColor(style.fillWithAlpha()); g.fillArc(Math.round(cx - rx1), Math.round(cy - ry1), rx2, ry2, 0, 360); } if (style.stroke) { Graphics2D g2 = (Graphics2D)g; g2.setStroke(new BasicStroke(style.stroke_width)); g.setColor(style.strokeWithAlpha()); g.drawArc(Math.round(cx - rx1), Math.round(cy - ry1), rx2, ry2, 0, 360); } } public final float getCX() { return cx; } public final void setCX(final float cx) { this.cx = cx; } public final float getCY() { return cy; } public final void setCY(final float cy) { this.cy = cy; } public final float getRX() { return rx; } public final void setRX(final float rx) { this.rx = rx; } public final float getRY() { return ry; } public final void setRY(final float ry) { this.ry = ry; } }
package com.hackerrank.github.model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Data @Entity @NoArgsConstructor public class Repo { @Id @Column(unique = true, nullable = false) @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String url; @OneToOne(mappedBy = "repo") @JsonIgnore private Event event; }
package bandeau; import java.awt.Color; public class ChangerCouleurFond extends Effet { private Color newColor; public ChangerCouleurFond(Bandeau monBandeau, Color myColor) { super(monBandeau); newColor=myColor; } public Color getNewColor() { return newColor; } public void jouerEffet() { this.monBandeau.setBackground(getNewColor()); this.monBandeau.sleep(50); } }
package com.example.user.myapplication.main.activity.adapter; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.user.myapplication.R; /** * Created by Junho on 2016-03-13. */ public class Tab3BaseAdapter extends ArrayAdapter<Integer> { private Context mContext; public Tab3BaseAdapter(Context context, int resource, int textViewResourceId, Integer[] objects) { super(context, resource, textViewResourceId, objects); this.mContext = context; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; // inflate layout from xml LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); // If holder not exist then locate all view from UI file. if (convertView == null) { // inflate UI from XML file convertView = inflater.inflate(R.layout.tab3_list_view_item_layout, parent, false); // get all UI view holder = new ViewHolder(convertView); holder.image = (ImageView)convertView.findViewById(R.id.consumeitem); holder.text =(TextView)convertView.findViewById(R.id.consumetext); // set tag for holder convertView.setTag(holder); } else { // if holder created, get tag from view holder = (ViewHolder) convertView.getTag(); } //holder.image.setImageResource(getItem(position)); //getItem은 Integer[] 로 들어오는건데 이걸 Consume으로 대체해서 //holder에서 ImageView를 Text와 같이 꾸밀 수 있지않을까합니다. holder.image.setImageResource(getItem(position)); holder.text.setText("TEMP"+position); holder.image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(mContext,"ToastTest : "+position,Toast.LENGTH_SHORT).show(); } }); return convertView; } private class ViewHolder { private ImageView image; private TextView text; public ViewHolder(View v) { image = (ImageView)v.findViewById(R.id.image); text = (TextView)v.findViewById(R.id.consumetext); } } }
package com.tencent.mm.plugin.webview.ui.tools.widget; import android.app.Activity; import com.tencent.mm.ui.MMActivity; class WebViewSearchContentInputFooter$7 implements Runnable { final /* synthetic */ WebViewSearchContentInputFooter qlx; WebViewSearchContentInputFooter$7(WebViewSearchContentInputFooter webViewSearchContentInputFooter) { this.qlx = webViewSearchContentInputFooter; } public final void run() { MMActivity.showVKB((Activity) this.qlx.getContext()); } }
package br.com.projeto.kafka.java; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProjetoKafkaJavaApplication { public static void main(String[] args) { SpringApplication.run(ProjetoKafkaJavaApplication.class, args); } }
/** * Exception levée lorsqu'un cycle est détecté parmi les traitements */ public class CycleException extends Exception { private static final long serialVersionUID = 1L; public CycleException(String message) { super(message); } }
package botenanna.behaviortree.guards; import botenanna.behaviortree.ArgumentTranslator; import botenanna.behaviortree.Leaf; import botenanna.behaviortree.MissingNodeException; import botenanna.behaviortree.NodeStatus; import botenanna.game.Situation; import botenanna.math.Vector3; import java.util.function.Function; public class GuardIsPointBehind extends Leaf { private Function<Situation, Object> point; /** * The guard GuardIsPointBehind takes a Vector3 point and checks if the given point is behind the current car. * If the point is behind it will return SUCCESS and if not, it will return FAILURE. * * Its signature is: {@code GuardIsPointBehind <givenPoint:Vector3>} */ public GuardIsPointBehind(String[] arguments) throws IllegalArgumentException { super(arguments); if (arguments.length != 1) throw new IllegalArgumentException(); point = ArgumentTranslator.get(arguments[0]); } @Override public void reset() { // Irrelevant } @Override public NodeStatus run(Situation input) throws MissingNodeException { // Convert given input to a Vector Vector3 givenPoint = (Vector3) point.apply(input); return input.isPointBehindCar(input.myPlayerIndex, givenPoint) ? NodeStatus.DEFAULT_SUCCESS : NodeStatus.DEFAULT_FAILURE; } }
package com.baohua.databingdemo.activity; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.Toast; import com.baohua.databingdemo.R; import com.baohua.databingdemo.adapter.WorkerAdapter; import com.baohua.databingdemo.databinding.ActivityListBinding; import com.baohua.databingdemo.model.Worker; import java.util.ArrayList; import java.util.List; /** * @Author yaobaohua * @CreatedTime 2016/10/19 23:07 * @DESC : */ public class RecyclerViewActivity extends AppCompatActivity { ActivityListBinding mBinding; WorkerAdapter adapter; private List<Worker> workers; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding= DataBindingUtil.setContentView(this,R.layout.activity_list); mBinding.recycleView.setLayoutManager(new LinearLayoutManager(this)); mBinding.setPresenter(new Presenter()); workers=new ArrayList<>(); workers.add(new Worker("lisi","22",true)); workers.add(new Worker("wangwu","233",false)); workers.add(new Worker("yao","2452",false)); workers.add(new Worker("bao","322",true)); adapter=new WorkerAdapter(this); mBinding.recycleView.setAdapter(adapter); adapter.setOnRecycleItemClickListener(new WorkerAdapter.OnRecycleItemClickListener() { @Override public void onRecycleItemClick(Worker worker) { Toast.makeText(RecyclerViewActivity.this,worker.getName(),Toast.LENGTH_LONG).show(); } }); adapter.addAllItem(workers); } public class Presenter{ public void onClickAddItem(View view){ adapter.addOneItem(new Worker("zhao","2323",true)); } public void onClickRemoveItem(View view){ adapter.removewItem(); } } }
package com.zzlz13.zmusic.fragment; import com.zzlz13.zlibrary.base.BaseInitFragment; /** * Created by hjr on 2016/5/10. */ public abstract class BaseFragment extends BaseInitFragment { }
package edu.weber; import javax.swing.*; import java.awt.*; import java.util.ArrayList; public class TransferFrame extends JFrame{ public TransferFrame(AccountHolder accountHolder, ArrayList<AccountHolder> listOfAccounts) { super("Transfer from account: " + accountHolder.getAccountNumber()); TransferPanel transferPanel = new TransferPanel(accountHolder, listOfAccounts); add(transferPanel, BorderLayout.WEST); setSize(600, 500); setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); setVisible(true); } }
/* * [y] hybris Platform * * Copyright (c) 2000-2016 SAP SE * All rights reserved. * * This software is the confidential and proprietary information of SAP * Hybris ("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 Hybris. */ package com.cnk.travelogix.sapintegrations.converters.populator; import de.hybris.platform.converters.Populator; import de.hybris.platform.servicelayer.dto.converter.ConversionException; import java.util.List; import org.apache.log4j.Logger; import com.cnk.travelogix.custom.zifws.account.clear.TableOfZifstAccount; import com.cnk.travelogix.custom.zifws.account.clear.ZIffmAccountClear; import com.cnk.travelogix.custom.zifws.account.clear.ZifstAccount; import com.cnk.travelogix.custom.zifws.account.clear.ZifstDocheadClear; import com.cnk.travelogix.custom.zifws.account.clear.data.TableOfZifstAccountData; import com.cnk.travelogix.custom.zifws.account.clear.data.ZIffmAccountClearDataRequest; import com.cnk.travelogix.custom.zifws.account.clear.data.ZifstAccountData; import com.cnk.travelogix.custom.zifws.account.clear.data.ZifstDocheadClearData; /** * */ public class DefaultAccountClearRequestDataPopulator implements Populator<ZIffmAccountClearDataRequest, ZIffmAccountClear> { private final Logger LOG = Logger.getLogger(getClass()); @Override public void populate(final ZIffmAccountClearDataRequest source, final ZIffmAccountClear target) throws ConversionException { try { final ZifstDocheadClear zifstDocheadClear = new ZifstDocheadClear(); final TableOfZifstAccount tableOfZifstAccount = new TableOfZifstAccount(); if (source.getIDocheader() != null) { final ZifstDocheadClearData zifstDocheadClearDataSrc = source.getIDocheader(); zifstDocheadClear.setAccount(zifstDocheadClearDataSrc.getAccount()); zifstDocheadClear.setAgums(zifstDocheadClearDataSrc.getAgums()); zifstDocheadClear.setBktxt(zifstDocheadClearDataSrc.getBktxt()); zifstDocheadClear.setBlart(zifstDocheadClearDataSrc.getBlart()); zifstDocheadClear.setBudat(zifstDocheadClearDataSrc.getBudat()); zifstDocheadClear.setBukrs(zifstDocheadClearDataSrc.getBukrs()); zifstDocheadClear.setUniqid(zifstDocheadClearDataSrc.getUniqid()); zifstDocheadClear.setWaers(zifstDocheadClearDataSrc.getWaers()); zifstDocheadClear.setXblnr(zifstDocheadClearDataSrc.getXblnr()); } if (source.getItAccount() != null) { final List<ZifstAccount> zifstAccounts = tableOfZifstAccount.getItem(); final TableOfZifstAccountData tableOfZifstAccountData = source.getItAccount(); final List<ZifstAccountData> accountDatas = tableOfZifstAccountData.getItem(); for (final ZifstAccountData zifstAccountData : accountDatas) { final ZifstAccount zifstAccount = new ZifstAccount(); zifstAccount.setAccount(zifstAccountData.getAccount()); zifstAccount.setBelnr(zifstAccountData.getBelnr()); zifstAccount.setBudat(zifstAccountData.getBudat()); zifstAccount.setWrbtr(zifstAccountData.getWrbtr()); zifstAccount.setXblnr(zifstAccountData.getXblnr()); zifstAccount.setZuonr(zifstAccountData.getZuonr()); zifstAccounts.add(zifstAccount); } } target.setIDocheader(zifstDocheadClear); target.setItAccount(tableOfZifstAccount); } catch (final Exception e) { LOG.error(e.getMessage(), e); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package main.game.action.creature; import com.jme3.cinematic.Cinematic; import com.jme3.cinematic.MotionPath; import com.jme3.cinematic.MotionPathListener; import com.jme3.cinematic.events.CinematicEvent; import com.jme3.cinematic.events.CinematicEventListener; import com.jme3.cinematic.events.MotionEvent; import com.jme3.math.Vector3f; import com.jme3.scene.Node; import java.util.logging.Level; import java.util.logging.Logger; import main.exception.ActionNotEnabledException; import main.exception.NoReachablePathException; import main.game.Game; import main.game.Player; import main.game.algorithm.PathFinding; import main.game.model.FoodSource; import main.game.model.control.AirborneCreatureControl; import main.game.model.control.FoodSourceControl; import main.game.model.control.LandCreatureControl; import main.game.model.creature.AirborneCreature; import main.game.model.creature.Creature; import main.game.model.creature.LandCreature; import main.game.model.creature.SeaCreature; /** * * @author s116861 */ public class PickupFoodAction extends CreatureAction { /** * Properties */ private transient FoodSource foodSource; private int foodSourceId; /** * Constructor */ public PickupFoodAction(Player player, Creature subject, FoodSource foodSource) { this.player = player; this.subject = subject; this.foodSource = foodSource; this.foodSourceId = foodSource.getId(); } /** * Business logic */ @Override public void deserialize(Game game) { super.deserialize(game); this.foodSource = game.getWorld().findFoodSourceById(this.foodSourceId); } @Override public boolean isEnabled(Game game) { if (this.foodSource.getLocation().creatureAllowed(subject) && !this.subject.isInFight() && this.foodSource.hasFood() && this.subject.getLocation().distance(this.foodSource.getLocation()) <= this.subject.getActionRadius()) { return true; } else { return false; } } @Override public void performAction(Game game) throws ActionNotEnabledException { if (!this.isEnabled(game)) { throw new ActionNotEnabledException(); } else { try { final MotionPath path = PathFinding.createMotionPath(game.getTerrain(), game.getWorld().getCells(), this.subject.getLocation(), this.foodSource.getLocation(), this.subject); final Cinematic cinematic = new Cinematic(game.getWorld().getWorldNode(), 20); MotionEvent track = new MotionEvent(this.subject.getModel(), path); if(subject instanceof LandCreature) { LandCreatureControl c= (LandCreatureControl)this.subject.getController(); Node s = (Node) c.getSpatial(); s.detachChild(c.getStand()); s.attachChild(c.getMove()); c.setSpatial(null); c.setSpatial(s); track.setDirectionType(MotionEvent.Direction.Path); } else if (subject instanceof SeaCreature){ track.setDirectionType(MotionEvent.Direction.LookAt); track.setLookAt(this.foodSource.getLocation().getWorldCoordinates(), Vector3f.UNIT_Y); } else if (subject instanceof AirborneCreature) { AirborneCreatureControl c = (AirborneCreatureControl) subject.getController(); Node s = (Node) c.getSpatial(); s.detachChild(c.getStand()); s.attachChild(c.getMove()); c.setSpatial(null); c.setSpatial(s); track.setDirectionType(MotionEvent.Direction.None); } cinematic.addCinematicEvent(0, track); cinematic.fitDuration(); game.getStateManager().attach(cinematic); path.addListener(new MotionPathListener() { public void onWayPointReach(MotionEvent control, int wayPointIndex) { if (path.getNbWayPoints() == wayPointIndex + 1) { //control.getSpatial().setLocalTranslation(destination.getWorldCoordinates().subtract(control.getSpatial().getWorldTranslation())); cinematic.stop(); } } }); //final Vector3f airDestination = foodSource.getLocation().getWorldCoordinates();//new Vector3f(foodSource.getLocation().getWorldCoordinates().x, PathFinding.airCreatureHeight, foodSource.getLocation().getWorldCoordinates().z); cinematic.addListener(new CinematicEventListener() { public void onPlay(CinematicEvent cinematic) { //throw new UnsupportedOperationException("Not supported yet."); } public void onPause(CinematicEvent cinematic) { //throw new UnsupportedOperationException("Not supported yet."); } public void onStop(CinematicEvent cinematic) { if(subject instanceof LandCreature) { LandCreatureControl c= (LandCreatureControl)subject.getController(); Node s = (Node) c.getSpatial(); s.detachChild(c.getMove()); s.attachChild(c.getStand()); c.setSpatial(null); c.setSpatial(s); } if(subject instanceof AirborneCreature) { AirborneCreatureControl c = (AirborneCreatureControl)subject.getController(); Node s = (Node) c.getSpatial(); s.detachChild(c.getMove()); s.attachChild(c.getStand()); c.setSpatial(null); c.setSpatial(s); } FoodSourceControl c= (FoodSourceControl)foodSource.getController(); Node s = (Node) c.getSpatial(); s.detachChild(c.getFull()); c.setSpatial(null); c.setSpatial(s); subject.getModel().setLocalTranslation(foodSource.getLocation().getWorldCoordinates()); //subject.setLocation(foodSource.getLocation()); } }); cinematic.play(); } catch (NoReachablePathException ex) { Logger.getLogger(MoveAction.class.getName()).log(Level.SEVERE, null, ex); } // When succeeded, perform some action this.foodSource.eat(); this.player.increaseFood(1); /** * Update locations */ // Update old location if (this.subject instanceof AirborneCreature) { this.subject.getLocation().removeCreature(this.subject, ((AirborneCreature) this.subject).isAirborne()); ((AirborneCreature) this.subject).land(); } else { this.subject.getLocation().removeCreature(this.subject, false); } // Update new location this.foodSource.getLocation().addCreature(this.subject, false); this.subject.setLocation(this.foodSource.getLocation()); /** * Set in fight if necessary after moving */ boolean mixedTeamsInCell = false; for (Creature creature : this.foodSource.getLocation().getOccupants()) { if (!creature.getPlayer().equals(this.player)) { mixedTeamsInCell = true; break; } } for (Creature creature : this.foodSource.getLocation().getAirborneOccupants()) { if (!creature.getPlayer().equals(this.player)) { mixedTeamsInCell = true; break; } } if (mixedTeamsInCell) { for (Creature creature : this.foodSource.getLocation().getOccupants()) { creature.setInFight(true); } for (Creature creature : this.foodSource.getLocation().getAirborneOccupants()) { creature.setInFight(true); } } } } /** * Getters & Setters */ }
package com.example.android.roomwithmoreentitiesapp.database; import android.arch.persistence.room.Dao; import android.arch.persistence.room.Delete; import android.arch.persistence.room.Insert; import android.arch.persistence.room.Update; @Dao public interface BaseDao<T> { @Insert void insert(T object); @Update void update(T object); @Delete void delete(T object); }
package escriturauno; import java.util.Scanner; public class PruebaCrearArchivoTexto { public static void main(String args[]) { Scanner entrada = new Scanner(System.in); String cadenaFinal = ""; System.out.println("Ingrese su nombre"); String nombre = entrada.nextLine(); System.out.println("Ingrese su apellido"); String apellido = entrada.nextLine(); System.out.println("Ingrese su edad"); int edad = entrada.nextInt(); cadenaFinal = String.format("%s%s %s %d\n", cadenaFinal, nombre, apellido, edad); CrearArchivoTexto.agregarRegistros(cadenaFinal); } // fin de main } // fin de la clase PruebaCrearArchivoTexto /************************************************************************** * (C) Copyright 1992-2007 por Deitel & Associates, Inc. y * * Pearson Education, Inc. Todos los derechos reservados. * *************************************************************************/
package com.kakaopay.payments.api.dto; import lombok.Builder; import lombok.Getter; import lombok.Setter; import org.springframework.http.HttpStatus; import java.io.Serializable; import java.util.Map; @Getter @Setter public class ResponseDto implements Serializable { private String manageId; // 관리번호 private CardInfo cardInfo; // 카드정보 private AmountInfo amountInfo; // 금액정보 private String payStatement; // 결제 명세 private String payType; // 결제 / 취소 구분 private Map<String, Object> optionalData; // 추가 데이터 @Builder public ResponseDto(String manageId, CardInfo cardInfo, AmountInfo amountInfo, String payStatement, String payType, Map<String, Object> optionalData){ this.manageId = manageId; this.cardInfo = cardInfo; this.amountInfo = amountInfo; this.payStatement = payStatement; this.payType = payType; this.optionalData = optionalData; } }
package com.application.view; import com.application.controller.CartController; import java.util.Objects; public class CartView implements IView { private static final String VIEW_FORMAT = "|%3s|%12s|%13s|"; private final CartController cartController; public CartView(final CartController cartController) { this.cartController = Objects.requireNonNull(cartController, "cartController is NULL!!"); } @Override public void render() { System.out.println(String.format(VIEW_FORMAT, "ID", "PRODUCT_NAME", "PRODUCT_COUNT")); cartController.fetchCartItems() .forEach((key, value) -> System.out.println(String.format(VIEW_FORMAT, key.getId(), key.getName(), value.intValue()))); } }
package uptc.softMin.logic.scalability; public class Cl_Singh { }
package plattern.BridgePattern; public class Test { public static void main(String args []) { Pen pencil = new Pencil(new Blue()); Pen crayon = new Crayon(new Red()); Pen ballPointPen = new BallPointPen(new Yellow()); System.out.println(pencil.description()); System.out.println(crayon.description()); System.out.println(ballPointPen.description()); } }
package kr.or.kosta.chat.entity; import java.net.Socket; import kr.or.kosta.chat.server.ClientThread; public class User { private String nickName; public User() {} public User(String nickName) { this.nickName = nickName; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } @Override public String toString() { return "User [nickName=" + nickName + "]"; } }
/* TODO: Create a Server . */ import java.io.*; import java.net.*; public class Networking { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(6666); Socket s = ss.accept();//establishes connection and waits for the client DataInputStream dis = new DataInputStream(s.getInputStream()); String str = (String)dis.readUTF(); System.out.println("message= "+str); ss.close(); } }
package be.thomaswinters.goofer.generators.string; import be.thomaswinters.datamuse.connection.DatamuseCaller; import be.thomaswinters.datamuse.data.DatamuseWord; import be.thomaswinters.datamuse.query.DatamuseQuery; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; public class DatamuseRelatedAdjectiveGenerator implements IRelatedStringGenerator { protected final DatamuseCaller caller; private final DatamuseQuery basicQuery = new DatamuseQuery().maximumAnswers(1000); public DatamuseRelatedAdjectiveGenerator(DatamuseCaller caller) { this.caller = caller; } protected List<DatamuseWord> getRelatedDatamuseWords(String noun) throws IOException { DatamuseQuery query = basicQuery.relatedAdjectiveFor(noun); List<DatamuseWord> result = caller.call(query); return result; } @Override public List<String> generate(String relatedWord) throws Exception { return getRelatedDatamuseWords(relatedWord).stream().map(e -> e.getWord()).collect(Collectors.toList()); } }
package de.zarncke.lib.io.store.ext; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.regex.Pattern; import org.junit.Test; import de.zarncke.lib.coll.L; import de.zarncke.lib.coll.Pair; import de.zarncke.lib.err.GuardedTest; import de.zarncke.lib.io.store.MapStore; import de.zarncke.lib.io.store.MemStore; import de.zarncke.lib.io.store.Store; import de.zarncke.lib.io.store.StoreUtil; import de.zarncke.lib.io.store.ext.StoreGroup.Controller; import de.zarncke.lib.io.store.ext.StoreGroup.Grouper; import de.zarncke.lib.region.RegionUtil; import de.zarncke.lib.util.Chars; public class StoreGroupTest extends GuardedTest { @Test public void testStoreGroup() throws IOException { testStoreGroup(false); testStoreGroup(true); } private void testStoreGroup(final boolean fail) throws IOException { Store a = make("a"); Store b = make("b"); Store c = make("c"); Store d = make("d"); Store e = make("e"); MapStore mapStore = new MapStore(); mapStore.setCreateMode(MapStore.CreateMode.ALLOW_AUTOMATIC); mapStore.add("a.1", a); if (fail) { // add an element that is designed to cause the two different groups with the same name "a" to be created mapStore.add("collision", a); } mapStore.add("b.1", b); mapStore.add("c.2", c); mapStore.add("d.2", d); mapStore.add("e", e); Store group = null; try { group = StoreGroup.group(mapStore, new Grouper() { @Override public Pair<Controller, ? extends Iterable<Store>> getMatchingsFor(final Store container, final Store selectedElement) { String name = selectedElement.getName(); if (name.contains(".")) { String suffix = Chars.rightAfter(name, "."); return Pair.pair((Controller) new StoreGroup.SimpleController(suffix), (Iterable<Store>) StoreGroup.filterByName(container, ".*\\." + Pattern.quote(suffix))); } if (name.equals("collision")) { return Pair.pair((Controller) new StoreGroup.SimpleController("1"), L.s(selectedElement)); } return null; } }); if (fail) { fail("we expected failure"); } } catch (IllegalArgumentException e1) { if (!fail) { throw e1; } // no further tests needed return; } assertSameContent(a, StoreUtil.resolvePath(group, "1/a.1", "/")); assertSameContent(b, StoreUtil.resolvePath(group, "1/b.1", "/")); assertSameContent(c, StoreUtil.resolvePath(group, "2/c.2", "/")); assertSameContent(d, StoreUtil.resolvePath(group, "2/d.2", "/")); assertEquals(2, L.copy(group.iterator()).size()); // TODO add test that no two matchings get the name name (from controller) } public void testStoreGrouper2() throws IOException { Store a = make("1"); Store ab = make("2"); Store abc = make("3"); Store abd = make("4"); Store b = make("5"); Store bcd = make("6"); Store bcde = make("7"); MapStore mapStore = new MapStore(); mapStore.setCreateMode(MapStore.CreateMode.ALLOW_AUTOMATIC); mapStore.add("a", a); mapStore.add("ab", ab); mapStore.add("abc", abc); mapStore.add("abd", abd); mapStore.add("b", b); mapStore.add("bcd", bcd); mapStore.add("bcde", bcde); Store group = null; group = StoreGroup.group(mapStore, StoreGroup.makePrefixLengthGrouper(2)); assertEquals("" + group, 2 + 2, L.copy(group.iterator()).size()); assertSameContent(a, StoreUtil.resolvePath(group, "a/a", "/")); assertSameContent(ab, StoreUtil.resolvePath(group, "ab/ab", "/")); assertSameContent(abc, StoreUtil.resolvePath(group, "ab/abc", "/")); assertSameContent(abd, StoreUtil.resolvePath(group, "ab/abd", "/")); assertSameContent(b, StoreUtil.resolvePath(group, "b/b", "/")); assertSameContent(bcd, StoreUtil.resolvePath(group, "bc/bcd", "/")); assertSameContent(bcde, StoreUtil.resolvePath(group, "bc/bcde", "/")); } public Store make(final String content) throws UnsupportedEncodingException { Store onlyData = new MemStore(RegionUtil.asRegion(content.getBytes("ASCII"))); return onlyData; } protected void assertSameContent(final Store a, final Store b) throws IOException { assertEquals(0, RegionUtil.compare(a.asRegion(), b.asRegion())); } }
package Association.Aggregaion.Composition; public class Driver { private Vehicle availableVehicle; public void rentVehicle(Vehicle v){ this.availableVehicle = v; System.out.println("driver has now a vehicle to drive"); } public void driveVehicle(double miles){ if(this.availableVehicle != null){ this.availableVehicle.goToDestination(miles); System.out.println("driver drives the vehicle safely"); } } public void returnVehicle(){ this.availableVehicle = null; System.out.println("driver returns the vehicle"); } }
package com.example.demo; import java.util.Objects; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class Order { private @Id @GeneratedValue Long id; private Integer day; @ManyToOne @JoinColumn(name = "CITY_ID", referencedColumnName = "ID") private City city; @ManyToOne @JoinColumn(name = "ACTION_ID", referencedColumnName = "ID") private Action action; @SuppressWarnings("unused") private Order() {} public Order(Integer day, City city, Action action) { this.day = day; this.city = city; this.action = action; } @Override public boolean equals(Object o) { if(this==o) return true; if(o == null || getClass() != o.getClass()) return false; Order orders = (Order)o; return Objects.equals(day, orders.day) && Objects.equals(city, orders.city) && Objects.equals(action, orders.action); } @Override public int hashCode() { return Objects.hash(id, day, city, action); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Integer getDay() { return day; } public void setDay(Integer day) { this.day = day; } public City getCity() { return city; } public void setCity(City city) { this.city = city; } public Action getAction() { return action; } public void setAction(Action action) { this.action = action; } @Override public String toString() { return "Order{" + "id=" + id + ", day='" + day + "'" + ", city='" + city.getId() + "'" + ", action='" + action.getId() + "'}"; } }
package com.ricex.cartracker.androidrequester.request.type; import org.springframework.core.ParameterizedTypeReference; public class BooleanResponseType extends ParameterizedTypeReference<Boolean> { }
package com.wds.spring.batch.ch03; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.batch.core.ChunkListener; import org.springframework.batch.core.scope.context.ChunkContext; /** * Created by wds on 2015/10/1. */ public class FirstChunkListener implements ChunkListener { private static final Logger LOGGER = LoggerFactory.getLogger(FirstChunkListener.class); @Override public void beforeChunk(ChunkContext context) { LOGGER.info("FirstChunkListener before Chunk"); } @Override public void afterChunk(ChunkContext context) { LOGGER.info("FirstChunkListener after Chunk"); } @Override public void afterChunkError(ChunkContext context) { LOGGER.error(context.getStepContext().getStepName()); } }
package com.example.expensetracker2020.Database.Repositories; import android.app.Application; import android.os.AsyncTask; import androidx.lifecycle.LiveData; import com.example.expensetracker2020.Database.AppDatabase; import com.example.expensetracker2020.Database.DAOs.AccountDao; import com.example.expensetracker2020.Database.DAOs.IntervalDao; import com.example.expensetracker2020.Database.Entities.Account; import com.example.expensetracker2020.Database.Entities.Interval; import com.example.expensetracker2020.Database.Entities.TransactionAndTag; import java.util.List; public class IntervalRepository { private IntervalDao intervalDao; private LiveData<List<Interval>> intervals; public IntervalRepository(Application application) { AppDatabase database = AppDatabase.getDatabase(application); intervalDao = database.intervalDao(); intervals = intervalDao.getAll(); } public LiveData<List<Interval>> getAll() { return intervals; } public void insert(Interval interval) { new IntervalRepository.InsertIntervalAsyncTask(intervalDao).execute(interval); } private static class InsertIntervalAsyncTask extends AsyncTask<Interval, Void, Void> { private IntervalDao intervalDao; private InsertIntervalAsyncTask(IntervalDao intervalDao) { this.intervalDao = intervalDao; } @Override protected Void doInBackground(Interval... intervals) { intervalDao.insert(intervals[0]); return null; } } }
package com.jiuzhe.app.hotel.entity; import com.jiuzhe.app.hotel.constants.OrderStatusEnum; /** * @Description:自动将支付状态变成入住状态的类 */ public class PaidToLived { private String orderId; private String merchantId; private String userId; private Integer paid = OrderStatusEnum.PAID.getIndex(); private Integer lived = OrderStatusEnum.LIVED.getIndex(); public Integer getLived() { return lived; } public void setLived(Integer lived) { this.lived = lived; } public Integer getPaid() { return paid; } public void setPaid(Integer paid) { this.paid = paid; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getMerchantId() { return merchantId; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } }
package com.jiejing.repo.utils; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; /** * @author baihe * Created on 2020-07-16 23:33 */ public class PageUtil { /** * Convert to Pageable * @param pageNo the page index * @param pageSize the page size * @param sort the sort object * @param oneBasedPage whether the page start from 1 * @return the converted Pageable object */ public static final Pageable toPageable(int pageNo, int pageSize, Sort sort, boolean oneBasedPage) { return PageRequest.of(Math.max(pageNo - (oneBasedPage ? 1 : 0), 0), pageSize, sort); } }
package com.javano1.StudentJobMS.api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.javano1.StudentJobMS.service.RoleService; @RestController @RequestMapping(value = { "/admin" }) public class RoleController { @Autowired private RoleService roleService; @RequestMapping(value = { "/roleList" }, method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public String getRoleList() { return roleService.getRoleList(); } @RequestMapping(value = { "/addRole" }, method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public String addRole(String roleName) { return roleService.addRole(roleName); } @RequestMapping(value = { "/updateRole" }, method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public String updateRole(String roleId,String roleName) { return roleService.updateRole(roleId, roleName); } @RequestMapping(value = { "/delRole" }, method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public String delRole(String roleId) { return roleService.delRole(roleId); } @RequestMapping(value = { "/searchRole" }, method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public String searchRole(String keyWord) { return roleService.searchRole(keyWord); } @RequestMapping(value = { "/hasRoleName" }, method = {RequestMethod.GET, RequestMethod.POST}) @ResponseBody public String hasRoleName(String roleName) { return roleService.hasRoleName(roleName); } }
package android.support.v4.app; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnDismissListener; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; public class i extends Fragment implements OnCancelListener, OnDismissListener { int no = 0; int np = 0; boolean nq = true; public boolean nr = true; int ns = -1; Dialog nt; boolean nu; boolean nv; boolean nw; public void a(m mVar, String str) { this.nv = false; this.nw = true; q bk = mVar.bk(); bk.a((Fragment) this, str); bk.commit(); } public void onAttach(Activity activity) { super.onAttach(activity); if (!this.nw) { this.nv = false; } } public void onDetach() { super.onDetach(); if (!this.nw && !this.nv) { this.nv = true; } } public void onCreate(Bundle bundle) { super.onCreate(bundle); this.nr = this.mContainerId == 0; if (bundle != null) { this.no = bundle.getInt("android:style", 0); this.np = bundle.getInt("android:theme", 0); this.nq = bundle.getBoolean("android:cancelable", true); this.nr = bundle.getBoolean("android:showsDialog", this.nr); this.ns = bundle.getInt("android:backStackId", -1); } } public LayoutInflater getLayoutInflater(Bundle bundle) { if (!this.nr) { return super.getLayoutInflater(bundle); } this.nt = bg(); if (this.nt == null) { return (LayoutInflater) this.mHost.mContext.getSystemService("layout_inflater"); } Dialog dialog = this.nt; switch (this.no) { case 1: case 2: break; case 3: dialog.getWindow().addFlags(24); break; } dialog.requestWindowFeature(1); return (LayoutInflater) this.nt.getContext().getSystemService("layout_inflater"); } public Dialog bg() { return new Dialog(getActivity(), this.np); } public void onCancel(DialogInterface dialogInterface) { } public void onDismiss(DialogInterface dialogInterface) { if (!this.nu && !this.nv) { this.nv = true; this.nw = false; if (this.nt != null) { this.nt.dismiss(); this.nt = null; } this.nu = true; if (this.ns >= 0) { getFragmentManager().S(this.ns); this.ns = -1; return; } q bk = getFragmentManager().bk(); bk.a(this); bk.commitAllowingStateLoss(); } } public void onActivityCreated(Bundle bundle) { super.onActivityCreated(bundle); if (this.nr) { View view = getView(); if (view != null) { if (view.getParent() != null) { throw new IllegalStateException("DialogFragment can not be attached to a container view"); } this.nt.setContentView(view); } this.nt.setOwnerActivity(getActivity()); this.nt.setCancelable(this.nq); this.nt.setOnCancelListener(this); this.nt.setOnDismissListener(this); if (bundle != null) { Bundle bundle2 = bundle.getBundle("android:savedDialogState"); if (bundle2 != null) { this.nt.onRestoreInstanceState(bundle2); } } } } public void onStart() { super.onStart(); if (this.nt != null) { this.nu = false; this.nt.show(); } } public void onSaveInstanceState(Bundle bundle) { super.onSaveInstanceState(bundle); if (this.nt != null) { Bundle onSaveInstanceState = this.nt.onSaveInstanceState(); if (onSaveInstanceState != null) { bundle.putBundle("android:savedDialogState", onSaveInstanceState); } } if (this.no != 0) { bundle.putInt("android:style", this.no); } if (this.np != 0) { bundle.putInt("android:theme", this.np); } if (!this.nq) { bundle.putBoolean("android:cancelable", this.nq); } if (!this.nr) { bundle.putBoolean("android:showsDialog", this.nr); } if (this.ns != -1) { bundle.putInt("android:backStackId", this.ns); } } public void onStop() { super.onStop(); if (this.nt != null) { this.nt.hide(); } } public void onDestroyView() { super.onDestroyView(); if (this.nt != null) { this.nu = true; this.nt.dismiss(); this.nt = null; } } }
package org.firstinspires.ftc.teamcode; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; /** * Created by Steve on 10/22/2017. */ @TeleOp(name="DriveTrainTest", group="Linear Opmode") public class DrivevTrainTest extends LinearOpMode { double powerLeft; double powerRight; double strafePower = 0.5; DcMotor fl = null; DcMotor fr = null; DcMotor bl = null; DcMotor br = null; public void runOpMode() { fl = hardwareMap.get(DcMotor.class, "fl"); fl.setDirection(DcMotorSimple.Direction.FORWARD); fr = hardwareMap.get(DcMotor.class, "fr"); fr.setDirection(DcMotorSimple.Direction.REVERSE); bl = hardwareMap.get(DcMotor.class, "bl"); bl.setDirection(DcMotorSimple.Direction.FORWARD); br = hardwareMap.get(DcMotor.class, "br"); br.setDirection(DcMotorSimple.Direction.REVERSE); waitForStart(); while (opModeIsActive()) { powerLeft = gamepad1.left_stick_y; powerRight = gamepad1.right_stick_y; fl.setPower(powerLeft); bl.setPower(powerLeft); fr.setPower(powerRight); br.setPower(powerRight); while(gamepad1.left_bumper==true) { fl.setPower(strafePower); bl.setPower(-strafePower); fr.setPower(-strafePower); br.setPower(strafePower); } while(gamepad1.right_bumper==true) { fl.setPower(-strafePower); bl.setPower(strafePower); fr.setPower(strafePower); br.setPower(-strafePower); } } } }
/* * Copyright 2017 University of Michigan * * 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 edu.umich.verdict.query; import edu.umich.verdict.VerdictContext; import edu.umich.verdict.exceptions.VerdictException; import edu.umich.verdict.parser.VerdictSQLParser; import edu.umich.verdict.relation.ExactRelation; import edu.umich.verdict.relation.Relation; import edu.umich.verdict.util.StringManipulations; import edu.umich.verdict.util.VerdictLogger; public class CreateViewAsSelectQuery extends Query { public CreateViewAsSelectQuery(VerdictContext vc, String q) { super(vc, q); } @Override public void compute() throws VerdictException { VerdictSQLParser p = StringManipulations.parserOf(queryString); Relation r = ExactRelation.from(vc, p.create_view().select_statement()); p.reset(); String viewName = p.create_view().view_name().getText(); p.reset(); boolean exact = p.create_view().select_statement().EXACT() != null; if (!exact) { r = ((ExactRelation) r).approx(); } // compose a query. StringBuilder sql = new StringBuilder(); sql.append("CREATE VIEW "); sql.append(viewName); sql.append(" AS "); String selectSql = r.toSql(); VerdictLogger.debug(this, String.format("Creates a view (%s) with the following query:", viewName)); VerdictLogger.debugPretty(this, Relation.prettyfySql(vc, selectSql), " "); sql.append(selectSql); vc.getDbms().executeUpdate(sql.toString()); } }
/* 类的成员之四:初始化快 分类 静态代码块 非静态代码块(没有static修饰 相同 可以有输出语句 可以对类的属性+类的声明进行初始化操作 可以按照从上到下的顺序依次执行 不同 静态代码块 不可以对非静态的属性(属性+方法)初始化 静态代码块的执行要先于非静态代码块 静态代码块只执行一次 非静态代码块(没有static修饰) 每一创建对象的时候都会执行一次,且先于构造器执行 程序自己创建类中的属性方法 左击“Source” 创建接口 生成getter和setter方法 生成toString()方法 生成hashCode()+equals()方法 生成构造函数方法 练习:TestOrder.java */ package day3; public class TestOrder { public static void main(String[] args) { // TODO Auto-generated method stub Order o1= new Order(); System.out.println(o1); Order o2= new Order(); System.out.println(o2); } } class Order { private int orderId; private String orderName; private static String orderDesc; // 非静态初始化块(没有限制) { orderId = 1002; // 非静态属性初始化 orderName = "a"; System.out.println("非静态初始化块!!"); // 输出语句 orderDesc = "orderDesc"; // 静态属性初始化 show1(); // 非静态方法调用 show2(); } // 静态初始化(只能输出花静态属性+静态方法+输出语句) { System.out.println("静态初始化块!!"); // 输出语句 orderDesc = "orderDesc"; // 静态属性初始化 show2(); // 静态方法初始化 } public Order(int orderId, String orderName) { super(); this.orderId = orderId; this.orderName = orderName; } public Order() { super(); } public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public String getOrderName() { return orderName; } public void setOrderName(String orderName) { this.orderName = orderName; } @Override public String toString() { // TODO Auto-generated method stub return super.toString(); } public void show1(){ } public static void show2(){ } }
package com.tencent.mm.plugin.qqmail.ui; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import com.tencent.mm.plugin.qqmail.b.i; class MailAddrsViewControl$5 implements OnKeyListener { final /* synthetic */ MailAddrsViewControl mhb; MailAddrsViewControl$5(MailAddrsViewControl mailAddrsViewControl) { this.mhb = mailAddrsViewControl; } public final boolean onKey(View view, int i, KeyEvent keyEvent) { String obj; if (i == 67 && keyEvent.getAction() == 0) { obj = this.mhb.mgU.getEditableText().toString(); if (obj.length() == 0 && MailAddrsViewControl.c(this.mhb) != null && MailAddrsViewControl.c(this.mhb).isSelected()) { this.mhb.f((i) MailAddrsViewControl.c(this.mhb).getTag()); MailAddrsViewControl.a(this.mhb, null); this.mhb.bpb(); } else if (obj.length() == 0 && MailAddrsViewControl.f(this.mhb).size() > 0) { int size = MailAddrsViewControl.f(this.mhb).size() - 1; View childAt = this.mhb.getChildAt(size); if (childAt.isSelected()) { this.mhb.f((i) MailAddrsViewControl.f(this.mhb).get(size)); this.mhb.bpb(); } else { childAt.setSelected(true); } } } else if (i == 66 && keyEvent.getAction() == 0) { obj = this.mhb.mgU.getEditableText().toString(); if (obj != null && obj.length() > 0) { MailAddrsViewControl.a(this.mhb, obj, true); this.mhb.bpb(); } } return false; } }
package com.finddreams.androidnewstack.dagger; import com.finddreams.androidnewstack.service.LivingService; import com.finddreams.androidnewstack.service.RestApiAdapter; import com.finddreams.androidnewstack.service.StockService; import dagger.Module; import dagger.Provides; import retrofit2.Retrofit; /** * Created by lx on 17-11-13. */ @Module public class AppModule { @Provides public Retrofit provideStockAdapter() { return RestApiAdapter.getInstance("http://v.juhe.cn/"); } @Provides public StockService provideStockApi(Retrofit restAdapter) { return restAdapter.create(StockService.class); } @Provides public LivingService provideLivingApi(Retrofit restAdapter) { return restAdapter.create(LivingService.class); } }
package dynks.cache; import dynks.URIMatcher; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.junit.Test; import javax.servlet.http.HttpServletRequest; import java.util.concurrent.TimeUnit; import static dynks.cache.test.DynksAssertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Created by jszczepankiewicz on 2015-03-26. */ public class ResponseCacheByURIBuilderTest { @Test public void shouldLoadConfigurationFromFileOnClasspath() { // given Config conf = ConfigFactory.load("dynks-test"); KeyStrategy keyStrategy = new NamespacedURIKeyStrategy("tst"); // when ResponseCacheByURIPolicy policy = ResponseCacheByURIBuilder.build(conf); // then assertThat(policy.getRegions()).isNotEmpty().hasSize(3); assertThat(policy.getRegions().get(new URIMatcher("/api/v1/bestsellers/{D}"))).isEqualTo(new CacheRegion(1800000, TimeUnit.MILLISECONDS,keyStrategy)); assertThat(policy.getRegions().get(new URIMatcher("/api/v1/users/{S}"))).isEqualTo(new CacheRegion(129000, TimeUnit.MILLISECONDS,keyStrategy)); assertThat(policy.getRegions().get(new URIMatcher("/api/v1/events/{D}"))).isEqualTo(new CacheRegion(4, TimeUnit.MILLISECONDS,keyStrategy)); } private HttpServletRequest forURI(final String uri) { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getRequestURI()).thenReturn(uri); return request; } }
package com.boraji.tutorial.springboot.model; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "pro_supplier") public class Suppliers { @Id @Column(name = "supplier_id") private Integer supplierid; @Column(name = "supplier_name") private String suppliername; @Column(name = "supplier_location") private String supplierlocation; public Integer getSupplierid() { return supplierid; } public void setSupplierid(Integer supplierid) { this.supplierid = supplierid; } public String getSuppliername() { return suppliername; } public void setSuppliername(String suppliername) { this.suppliername = suppliername; } public String getSupplierlocation() { return supplierlocation; } public void setSupplierlocation(String supplierlocation) { this.supplierlocation = supplierlocation; } @Override public String toString() { return "Suppliers [supplierid=" + supplierid + ", suppliername=" + suppliername + ", supplierlocation=" + supplierlocation + "]"; } }
package pm.server.persistence.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import pm.server.persistence.entity.PortfolioEntry; public interface PortfolioEntryRepository extends JpaRepository<PortfolioEntry, Long> { @Query(value = "from PortfolioEntry pe where pe.portfolio.id = ?") List<PortfolioEntry> findByPortfolioId(Long portfolioId); }
package ru.otus.homework.services; import org.junit.jupiter.api.*; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import ru.otus.homework.models.Author; import ru.otus.homework.models.Book; import ru.otus.homework.services.dao.JdbcBookDao; import javax.sql.DataSource; import java.sql.SQLException; import java.sql.Statement; import java.util.*; import java.util.function.BiFunction; import java.util.function.Supplier; import static javax.swing.UIManager.put; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static ru.otus.homework.services.BooksServiceImpl.FIND_ALL_HEADER; import static ru.otus.homework.services.BooksServiceImpl.FIND_ALL_HEADER_BOOKS_AUTHORS; import static ru.otus.outside.utils.TestData.*; @DisplayName("Class BooksServiceImpl") class BooksServiceImplTest { private DataSource dataSource; private JdbcBookDao dao; private BooksServiceImpl service; @Test @DisplayName("is instantiated with new BooksServiceImpl()") void isInstantiatedWithNew() { new BooksServiceImpl(null); } private void printFindAll() { System.out.println("transformList = " + service.findAll()); } private BooksServiceImpl createService() { dataSource = injectTestDataSource(); NamedParameterJdbcTemplate jdbc = new NamedParameterJdbcTemplate(dataSource); dao = new JdbcBookDao(jdbc); return new BooksServiceImpl(dao); } @Nested @DisplayName("when new default") class WhenNew { @BeforeEach void createNewQuestions() { service = createService(); } @Test @DisplayName("injected values in BooksServiceImpl()") void defaults() { assertThat(service).hasFieldOrPropertyWithValue("bookDao", dao); } } @Nested @DisplayName("BooksServiceImpl methods") class ServiceMethods { private final String[] TEST_RECORD = new String[]{ Long.toString(TEST_ID), TEST_ISBN, TEST_TITLE, Integer.toString(TEST_NUM), TEST_COPYRIGHT, Long.toString(TEST_ID), Long.toString(0L), }; private final String[] TEST_RECORD_BOOKS_AUTHORS = new String[]{ Long.toString(TEST_ID), TEST_ISBN, TEST_TITLE, Integer.toString(TEST_NUM), TEST_COPYRIGHT, TEST_PUBLISHER_NAME, TEST_GENRE_NAME, TEST_FIRST_NAME, TEST_LAST_NAME }; @BeforeEach void createNewService() throws SQLException { service = createService(); inserToTables(dataSource); } @AfterEach void deleteFromTable() throws SQLException { clearTables(dataSource); } @Test void findAll() { List<String[]> testList = service.findById(TEST_ID); List<String[]> expected = new ArrayList<>(); expected.add(FIND_ALL_HEADER); expected.add(TEST_RECORD); assertArrayEquals(expected.get(0), testList.get(0)); assertArrayEquals(expected.get(1), testList.get(1)); assertEquals(testList.get(0).length, testList.get(1).length); } @Test void findAllBooksAndTheirAuthors() { List<String[]> expected = new ArrayList<>(); expected.add(FIND_ALL_HEADER_BOOKS_AUTHORS); expected.add(TEST_RECORD_BOOKS_AUTHORS); List<String[]> testList = service.findAllBooksAndTheirAuthors(); assertArrayEquals(expected.get(0), testList.get(0)); assertArrayEquals(expected.get(1), testList.get(1)); } @Test void findById() { List<String[]> expected = new ArrayList<>(); expected.add(FIND_ALL_HEADER); expected.add(TEST_RECORD); List<String[]> testList = service.findById(TEST_ID); System.out.println(Arrays.toString(testList.get(1))); assertArrayEquals(expected.get(0), testList.get(0)); assertArrayEquals(expected.get(1), testList.get(1)); } @Test void findByIsbn() { List<String[]> expected = new ArrayList<>(); expected.add(FIND_ALL_HEADER); expected.add(TEST_RECORD); List<String[]> testList = service.findByIsbn(TEST_ISBN); assertArrayEquals(expected.get(0), testList.get(0)); assertArrayEquals(expected.get(1), testList.get(1)); } @Test void findByTitle() { List<String[]> expected = new ArrayList<>(); expected.add(FIND_ALL_HEADER); expected.add(TEST_RECORD); List<String[]> testList = service.findByTitle(TEST_TITLE); assertArrayEquals(expected.get(0), testList.get(0)); assertArrayEquals(expected.get(1), testList.get(1)); } @Test void insert() { assertTrue(service.insert( TEST_ISBN + TEST, TEST_TITLE + TEST, TEST_NUM + 1, TEST_COPYRIGHT, TEST_ID, 0L ) > 0); } @Test void update() throws SQLException { boolean autoCommit = autoCommitOn(dataSource); long id = service.update( TEST_ID, TEST_ISBN + TEST, TEST_TITLE + TEST, TEST_NUM, TEST_COPYRIGHT, TEST_ID, 0L ); assertEquals(id, TEST_ID); List<String[]> expected = new ArrayList<>(); expected.add(FIND_ALL_HEADER); expected.add(new String[]{ Long.toString(id), TEST_ISBN + TEST, TEST_TITLE + TEST, Integer.toString(TEST_NUM), TEST_COPYRIGHT, Long.toString(TEST_ID), Long.toString(0L), }); List<String[]> testList = service.findById(id); autoCommitRestore(dataSource, autoCommit); assertArrayEquals(expected.get(0), testList.get(0)); // TODO assertArrayEquals(expected.get(1), testList.get(1)); } @Test void delete() throws SQLException { assertEquals(2, service.findAll().size()); boolean autoCommit = autoCommitOn(dataSource); Statement statement = dataSource.getConnection().createStatement(); statement.execute(DELETE_FROM_AUTHOR_ISBN); service.delete(TEST_ID); assertEquals(1, service.findAll().size()); autoCommitRestore(dataSource, autoCommit); } } @Nested @DisplayName("BooksServiceImpl methods mock ") class ServiceMethodsMockDao { private BooksServiceImpl createServiceMockDao(Book b, Author a) { b.getAuthors().add(a); dao = mock(JdbcBookDao.class); when(dao.findAllBooksAndTheirAuthors()).thenReturn(new ArrayList<Book>(){{ add(b); }}); return new BooksServiceImpl(dao); } @Test void findAllBooksAndTheirAuthors_mock_AuthorNull() { final String[] TEST_RECORD_BOOKS_AUTHORS = new String[]{ Long.toString(TEST_ID), TEST_ISBN, TEST_TITLE, Integer.toString(TEST_NUM), TEST_COPYRIGHT, TEST_PUBLISHER_NAME, TEST_GENRE_NAME, TEST_FIRST_NAME, TEST_LAST_NAME }; List<String[]> expected = new ArrayList<>(); expected.add(FIND_ALL_HEADER_BOOKS_AUTHORS); expected.add(TEST_RECORD_BOOKS_AUTHORS); service = createServiceMockDao(createTestBook13(), createTestAuthor13()); List<String[]> testList = service.findAllBooksAndTheirAuthors(); assertArrayEquals(expected.get(0), testList.get(0)); assertArrayEquals(expected.get(1), testList.get(1)); } @Test void findAllBooksAndTheirAuthors_mock_BookNull() { service = createServiceMockDao(createTestBook13(), null); // assertThrows(RuntimeException.class, () -> service.findAllBooksAndTheirAuthors()); service.findAllBooksAndTheirAuthors(); } } }
package view; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; /** * CombatScreenView prompts the players to combat and * displays the stats of the players currently involved in combat. */ public class CombatScreenView implements ViewInterface { private final Pane rootPane; private final int width; private final int height; private final Text header; private final List<Text> toRemove = new ArrayList<>(); private final Button combatButton; private final Button exitButton; private final List<Button> combatButtonList; private final HashMap<String, Circle> playerCircles; public CombatScreenView(Group root, int width, int height) { this.width = width; this.height = height; playerCircles = new HashMap<>(); combatButtonList = new ArrayList<>(); rootPane = new Pane(); rootPane.setPrefSize(width, height); rootPane.setStyle("-fx-background-color: black"); root.getChildren().add(rootPane); combatButton = new Button(); combatButton.setPrefSize(width / 5, height / 16); combatButton.setLayoutX(width / 2 - combatButton.getPrefWidth() / 2); combatButton.setLayoutY(height - combatButton.getPrefHeight() - 50); combatButton.setText("Battle!"); combatButton.setFont(Font.font("Ink Free", 25)); addNode(combatButton); combatButtonList.add(combatButton); exitButton = new Button(); exitButton.setPrefSize(width / 10, height / 10); exitButton.setLayoutX(width - exitButton.getPrefWidth() - 10); exitButton.setLayoutY(10); exitButton.setText("Exit battle"); exitButton.setFont(Font.font("Ink Free", 20)); combatButtonList.add(exitButton); exitButton.setDisable(true); addNode(exitButton); header = new Text("The insane one is about to strike you"); header.setFont(Font.font("Ink Free", 45)); header.setWrappingWidth(400); header.setLayoutX(width / 2 - header.getWrappingWidth() / 2); header.setLayoutY(50); header.setFill(Color.WHITE); header.setTextAlignment(TextAlignment.CENTER); addNode(header); } public void setStaminaText(HashMap<String, Integer> staminaNameMap, HashMap<String, Integer> damageMap) { removeTextLabels(); Text staminaText; Text damageText; for (String s : staminaNameMap.keySet()) { staminaText = new Text(); staminaText.setLayoutY(playerCircles.get(s).getCenterY() + 30); staminaText.setLayoutX(playerCircles.get(s).getCenterX() - 30); staminaText.setText("Stamina: " + staminaNameMap.get(s).toString()); staminaText.setFont(Font.font("Ink Free", 15)); staminaText.setFill(Color.WHITE); addNode(staminaText); toRemove.add(staminaText); if (!damageMap.isEmpty() && damageMap.get(s) != 0) { damageText = new Text(); damageText.setLayoutX(playerCircles.get(s).getCenterX() + 20); damageText.setLayoutY(playerCircles.get(s).getCenterY()); damageText.setText("Damage: -" + damageMap.get(s).toString()); damageText.setFont(Font.font("Ink Free", 20)); damageText.setFill(Color.RED); addNode(damageText); toRemove.add(damageText); } } } void removeTextLabels() { for (Text t : toRemove) { rootPane.getChildren().remove(t); } toRemove.clear(); } public void initPlayerCircles(List<String> nonHauntedNames, List<String> hauntedNames) { int xDelta = 50; int yDelta = 40; removeCircles(); Circle currentCircle; for (int i = 0; i < nonHauntedNames.size(); i++) { currentCircle = new Circle(10); currentCircle.setCenterX(width / 2 + xDelta); currentCircle.setCenterY(height / 2 - yDelta * (nonHauntedNames.size() - 1) / 2 + yDelta * i); currentCircle.setFill(Color.BLUE); playerCircles.put(nonHauntedNames.get(i), currentCircle); addNode(currentCircle); } for (int i = 0; i < hauntedNames.size(); i++) { currentCircle = new Circle(10); currentCircle.setCenterX(width / 2 - xDelta); currentCircle.setCenterY(height / 2 + 30 * i); currentCircle.setFill(Color.RED); playerCircles.put(hauntedNames.get(i), currentCircle); addNode(currentCircle); } } private void removeCircles() { Collection<Circle> removableCircles = playerCircles.values(); for (Circle c : removableCircles) { rootPane.getChildren().remove(c); } playerCircles.clear(); } public List<Button> getCombatButton() { return combatButtonList; } @Override public void viewToFront() { rootPane.toFront(); } @Override public void addNode(Node node) { rootPane.getChildren().add(node); } }
//package regrep; // ///** // * 正则表达式练习 // */ // //public class RegrepExec { // public static void main(String[] args) { // /** // * 每一个正则在编译之后都是一个Pattern对象 // */ // //demo1 qq号码的校验 // // String qq="1234567890"; // boolean res=checkQQ(qq); // // } //}
package com.yixin.dsc.service.common; import java.math.BigDecimal; import java.util.Date; import com.yixin.common.utils.InvokeResult; import com.yixin.dsc.dto.DscContractCancelDto; import com.yixin.dsc.dto.query.DscFundsQueryDto; import com.yixin.dsc.dto.query.DscSettleCalculationResultDto; import com.yixin.dsc.dto.query.DscSettleLoanInfoDto; /** * 调用结算通用service * * @author YixinCapital -- chenjiacheng * 2018年09月10日 10:11 **/ public interface DscSettleCommonService { /** * 退车试算接口 * * @param applyNo 申请编号 * @param apptdt 试算申请日期 * @param bankSymbol 银行标志 * @return 出参 * @author YixinCapital -- chenjiacheng * 2018/9/10 10:20 */ DscSettleCalculationResultDto settleComputer(String applyNo, Date apptdt, String bankSymbol); /** * 获取贷款信息 * @param applyNo 申请编号 * @return * @author YixinCapital -- wangwenlong * 2018年9月10日 下午7:51:04 */ DscSettleLoanInfoDto getLoanInfo(String applyNo); /** * 获取取消标识 * @param applyNo 申请编号 * @param financeCode 资方编码 * @return * @author YixinCapital -- wangwenlong * 2018年9月10日 下午8:09:04 */ DscContractCancelDto getCancelInfo(String applyNo,String financeCode); /** * 查询银行扣补息款、退回补息款、分润信息 * * @param queryParam * @return */ InvokeResult queryBankFunds(DscFundsQueryDto queryParam); /** * 向结算推送放款信息 * @param applyNo 订单编号 * @param bankSeq 银行流水 * @param loanDime 放款时间 * @param loanAmount 放款金额 * @param loanSuccess 是否放款成功 * @return 是否推送成功 * @author YixinCapital -- wangwenlong * 2018年10月15日 下午1:34:41 */ Boolean pushFk(String applyNo,String bankSeq,Date loanDime,BigDecimal loanAmount,Boolean loanSuccess); }
package vlad.fp.services.synchronous.rpc.server; import vlad.fp.services.model.BrandID; import vlad.fp.services.model.Credits; import vlad.fp.services.model.Invoice; import vlad.fp.services.model.InvoiceID; import vlad.fp.services.synchronous.api.BillingService; import vlad.fp.services.synchronous.rpc.RpcUtils; import java.util.concurrent.ExecutorService; public class BillingRpcServer implements BillingService { private final ExecutorService executor; private final BillingService delegate; public BillingRpcServer(ExecutorService executor, BillingService delegate) { this.executor = executor; this.delegate = delegate; } @Override public InvoiceID transfer(BrandID sender, BrandID receiver, Credits credits) { return RpcUtils.execute(executor, () -> delegate.transfer(sender, receiver, credits)); } @Override public Invoice getInvoice(InvoiceID invoiceID) { return RpcUtils.execute(executor, () -> delegate.getInvoice(invoiceID)); } }
package com.cts.sr.moviecruiser.movie.utils; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import org.springframework.web.client.RestTemplate; import com.cts.sr.moviecruiser.movie.data.MovieDTO; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class MovieUtils { public static List<MovieDTO> getMovies(String endPointURL){ List<MovieDTO> movieList = new ArrayList<MovieDTO>(); try{ RestTemplate restTemplate = new RestTemplate(); String jsonResponse = restTemplate.getForObject(endPointURL, String.class); ObjectMapper om = new ObjectMapper(); om.configure(Feature.AUTO_CLOSE_SOURCE, true); JsonNode jsonNode = om.readTree(jsonResponse); JsonNode resultsNode = jsonNode.at("/results"); movieList = om.readValue(resultsNode.toString(), new TypeReference<List<MovieDTO>>(){}); } catch(Exception ex){ AppLogger.error("Exception occurred in getMovies", ex); } return movieList; } public static String getAbsoluteURL(String url,Object[] args){ return MessageFormat.format(url, args); } public static String getObjectAsString(Object obj){ try { return new ObjectMapper().writeValueAsString(obj); } catch (Exception e) { AppLogger.error("Exception occurred in getObjectAsString", e); } return null; } }
package kodlamaio.hrms.business.concretes; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import kodlamaio.hrms.business.abstracts.CvService; import kodlamaio.hrms.business.abstracts.ProgramingTechnologyService; import kodlamaio.hrms.core.utilities.results.DataResult; import kodlamaio.hrms.core.utilities.results.Result; import kodlamaio.hrms.core.utilities.results.SuccessDataResult; import kodlamaio.hrms.core.utilities.results.SuccessResult; import kodlamaio.hrms.dataAccess.abstracts.ProgramingTechnologyDao; import kodlamaio.hrms.entities.concretes.ProgramingTechnology; import kodlamaio.hrms.entities.concretes.dto.ProgramingTechnologyDto; @Service public class ProgramingTechnologyManager implements ProgramingTechnologyService { private ProgramingTechnologyDao programingTechnologyDao; private CvService cvService; @Autowired public ProgramingTechnologyManager(ProgramingTechnologyDao programingTechnologyDao,CvService cvService) { super(); this.programingTechnologyDao = programingTechnologyDao; this.cvService=cvService; } @Override public DataResult<List<ProgramingTechnology>> getAllByCv_CvId(int cvId) { return new SuccessDataResult<List<ProgramingTechnology>>(this.programingTechnologyDao.getAllByCv_CvId(cvId)); } @Override public Result add(ProgramingTechnologyDto programingTechnologyDto) { ProgramingTechnology programingTechnologyAdd = new ProgramingTechnology(); programingTechnologyAdd.setProgramingTechnology(programingTechnologyDto.getProgramingTechnology()); programingTechnologyAdd.setCv(cvService.getById(programingTechnologyDto.getCvId()).getData()); programingTechnologyDao.save(programingTechnologyAdd); return new SuccessResult(); } @Override public Result addAll(List<ProgramingTechnology> programingTechnologies) { // TODO Auto-generated method stub return null; } @Override public Result update(ProgramingTechnologyDto programingTechnologyDto, int id) { ProgramingTechnology programingTechnologyUpdate = programingTechnologyDao.getOne(id); programingTechnologyUpdate.setProgramingTechnology(programingTechnologyDto.getProgramingTechnology()); programingTechnologyDao.save(programingTechnologyUpdate); return new SuccessResult(); } @Override public Result delete(int id) { this.programingTechnologyDao.deleteById(id); return new SuccessResult(); } @Override public DataResult<ProgramingTechnology> getById(int id) { ProgramingTechnology programingTechnology = programingTechnologyDao.findById(id); return new SuccessDataResult<ProgramingTechnology>(programingTechnology); } // @Override // public DataResult<List<ProgramingTechnology>> getAllByCandidateId(int id) { // return new SuccessDataResult<List<ProgramingTechnology>>(this.programingTechnologyDao.getAllByCandidateId(id), // "Success"); // } // // @Override // public Result add(ProgramingTechnology programingTechnology) { // this.programingTechnologyDao.save(programingTechnology); // return new SuccessResult("Success"); // } // // @Override // public Result update(ProgramingTechnology programingTechnology) { // return null; // } // // @Override // public Result delete(ProgramingTechnology programingTechnology) { // return null; // } // // @Override // public Result addAll(List<ProgramingTechnology> programingTechnologies) { // this.programingTechnologyDao.saveAll(programingTechnologies); // return new SuccessResult("Success"); // } }
public class Main { public static void main(String[] args) { int[] numere = {8,4,9,1,2,222}; int k=-1,aux=0,n=9; int mij=numere.length; for(int i=0;i<numere.length-1;i++) { for (int j = 0; j < numere.length-i-1; j++) { if (numere[j] > numere[j+1]) { aux = numere[j]; numere[j] = numere[j+1]; numere[j+1] = aux; k++; } } k=0; } //if(k==0) { // for (int m = 0; m < numere.length; m++) // System.out.print( numere[m] + " "); //}else //System.out.println("The array is not sorted"); for(int i=0;i<mij-1;i++) { if(numere[i]==n) { System.out.println("The number has been found and it is: "+numere[i]); k=1; break;} } for(int j=mij;j<numere.length;j++) { if(numere[j]==n) { System.out.println("The number has been found and it is: "+numere[j]); k=1; break;} } if(k!=1) System.out.println("The number can't be found"); } }
package converter.Entity2Dto; import dao.AnimalDao; import dto.AnimalDtoByte; import entity.Animal; import entity.AnimalI18n; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component public class AnimalI18n2AnimalDtoByteConverter implements Converter<List<AnimalI18n>, List<AnimalDtoByte>> { @Autowired AnimalDao animalDao; @Override public List<AnimalDtoByte> convert(List<AnimalI18n> animalI18n) { List<AnimalDtoByte> animalDtoByteList = new ArrayList<>(); List<Animal> getAll = animalDao.getAll(); for (Animal animals : getAll) { AnimalDtoByte animalDtoByte = new AnimalDtoByte(); animalDtoByte.setIdAnimal(animals.getAnimalId()); animalDtoByte.setImageAnimal(animals.getAnimalImage()); animalDtoByte.setAudioAnimal(animals.getAnimalAudio()); animalDtoByte.setCategoryId(animals.getCategoryAnimal().getCategoryId()); for (AnimalI18n nameAnimal : animalI18n) { if (nameAnimal.getIdAnimals().getAnimalId() == animals.getAnimalId()) { animalDtoByte.setNameAnimal(nameAnimal.getNameAnimalI18n()); } } animalDtoByteList.add(animalDtoByte); } return animalDtoByteList; } }
package com.mapper; import com.bean.User; import org.apache.ibatis.annotations.Param; import tk.mybatis.mapper.common.Mapper; import java.util.List; public interface UserMapper extends Mapper<User> { List<User> getUser(@Param("user") User user); Integer getCountByPhone(String phone); }
package com.github.io24m.validate4java.validator; import com.github.io24m.validate4java.ValidateMetadata; /** * @author lk1 * @description * @create 2021-01-29 14:40 */ public interface BaseValidator<T> { boolean filter(ValidateMetadata<T> metadata); boolean pass(ValidateMetadata<T> metadata); boolean check(Object value, ValidateMetadata<T> metadata); String errorMessage(ValidateMetadata<T> metadata); }
package com.itsdf07.okhttp3.callback; /** * @Description * @Author itsdf07 * @Time 2018/9/28/028 */ public interface HttpDataCallback extends HttpBaseCallback{ }
package zm.gov.moh.core.service.worker; import android.content.Context; import org.threeten.bp.LocalDateTime; import org.threeten.bp.format.DateTimeFormatter; import androidx.annotation.NonNull; import androidx.work.WorkerParameters; import zm.gov.moh.core.model.Key; import zm.gov.moh.core.repository.database.entity.system.EntityType; import zm.gov.moh.core.utils.ConcurrencyUtils; public class PullMetaDataRemoteWorker extends RemoteWorker { public PullMetaDataRemoteWorker(@NonNull Context context, @NonNull WorkerParameters workerParams){ super(context, workerParams); } @Override @NonNull public Result doWork() { //TODO: Adjust the number of task pool size according to the number tasks invoking onTaskCompleted(); taskPoolSize = 17; if(lastMetadataSyncDate != null) MIN_DATETIME = LocalDateTime.parse(lastMetadataSyncDate); //Get from rest API and insert into database asynchronously getConcept(accessToken, MIN_DATETIME, OFFSET,LIMIT); getConceptName(accessToken, MIN_DATETIME, OFFSET,LIMIT); getConceptAnswer(accessToken, MIN_DATETIME,OFFSET, LIMIT); getLocations(accessToken, MIN_DATETIME, OFFSET, LIMIT); //Location attributes ConcurrencyUtils.consumeAsync( locationAttributes -> { repository.getDatabase().locationAttributeDao().insert(locationAttributes); onTaskCompleted(); }, //consumer this::onError, repository.getRestApi().getLocationAttributes(accessToken), //producer TIMEOUT); //Location attributes types ConcurrencyUtils.consumeAsync( locationAttributeTypes -> { repository.getDatabase().locationAttributeTypeDao().insert(locationAttributeTypes); onTaskCompleted(); } , //consumer this::onError, repository.getRestApi().getLocationAttributeTypes(accessToken), //producer TIMEOUT); //Location tag types ConcurrencyUtils.consumeAsync( locationTag -> { repository.getDatabase().locationTagDao().insert(locationTag); onTaskCompleted(); } , //consumer this::onError, repository.getRestApi().getLocationTags(accessToken), //producer TIMEOUT); //Location tag map types ConcurrencyUtils.consumeAsync( locationTagMap -> { repository.getDatabase().locationTagMapDao().insert(locationTagMap); onTaskCompleted(); } , //consumer this::onError, repository.getRestApi().getLocationTagMaps(accessToken), //producer TIMEOUT); //Patient identifier types ConcurrencyUtils.consumeAsync( patientIdentifierTypes ->{ repository.getDatabase().patientIdentifierTypeDao().insert(patientIdentifierTypes); onTaskCompleted(); }, //consumer this::onError, repository.getRestApi().getPatientIdentifierTypes(accessToken), //producer TIMEOUT); //Encounter types ConcurrencyUtils.consumeAsync( encounterTypes ->{ repository.getDatabase().encounterTypeDao().insert(encounterTypes); onTaskCompleted(); }, //consumer this::onError, repository.getRestApi().getEncounterTypes(accessToken), //producer TIMEOUT); //Visit types ConcurrencyUtils.consumeAsync( visitTypes ->{ repository.getDatabase().visitTypeDao().insert(visitTypes); onTaskCompleted(); }, //consumer this::onError, repository.getRestApi().getVisitTypes(accessToken), //producer TIMEOUT); // Drugs ConcurrencyUtils.consumeAsync( drugs ->{ repository.getDatabase().drugDao().insert(drugs); onTaskCompleted(); },//consumer this::onError, repository.getRestApi().getDrugs(accessToken), //producer TIMEOUT); // Provider Attributes ConcurrencyUtils.consumeAsync( attributes ->{ repository.getDatabase().providerAttributeDao().insert(attributes); onTaskCompleted(); },//consumer this::onError, repository.getRestApi().getProviderAttribute(accessToken), //producer TIMEOUT); // Provider Attribute Types ConcurrencyUtils.consumeAsync( attributes ->{ repository.getDatabase().providerAttributeTypeDao().insert(attributes); onTaskCompleted(); },//consumer this::onError, repository.getRestApi().getProviderAttributeType(accessToken), //producer TIMEOUT); // PersonAttribute Types ConcurrencyUtils.consumeAsync( personAttributes -> { repository.getDatabase().personAttributeDao().insert(personAttributes); onTaskCompleted(); }, // consumer this::onError, repository.getRestApi().getPersonAttributes(accessToken), // producer TIMEOUT); // PersonAttributeType Types ConcurrencyUtils.consumeAsync( personAttributeTypes -> { repository.getDatabase().personAttributeTypeDao().insert(personAttributeTypes); onTaskCompleted(); }, // consumer this::onError, repository.getRestApi().getPersonAttributeTypes(accessToken), // producer TIMEOUT); // EncounterProvider Types ConcurrencyUtils.consumeAsync( encounterProviders -> { repository.getDatabase().encounterProviderDao().insert(encounterProviders); onTaskCompleted(); }, // consumer this::onError, repository.getRestApi().getEncounterProviders(accessToken), // producer TIMEOUT); if(awaitResult().equals(Result.success())){ repository.getDefaultSharePrefrences().edit() .putString(Key.LAST_METADATA_SYNC_DATETIME, LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)) .apply(); } return awaitResult(); } //Concept name public void getConceptName(String accessToken, LocalDateTime MIN_DATETIME,final long offset, int limit){ ConcurrencyUtils.consumeAsync( conceptNames -> { if(conceptNames.length > 0){ db.conceptNameDao().insert(conceptNames); updateMetadata(conceptNames, EntityType.CONCEPT_NAME); getConceptName(accessToken,MIN_DATETIME,offset + limit,limit); }else onTaskCompleted(); }, //consumer this::onError, repository.getRestApi().getConceptNames(accessToken,MIN_DATETIME,offset,limit), //producer TIMEOUT); } //Concept answer public void getConceptAnswer(String accessToken, LocalDateTime MIN_DATETIME,final long offset, int limit){ ConcurrencyUtils.consumeAsync( conceptAnswers -> { if(conceptAnswers.length > 0){ db.conceptAnswerDao().insert(conceptAnswers); updateMetadata(conceptAnswers, EntityType.CONCEPT_ANSWER); getConceptAnswer(accessToken,MIN_DATETIME,offset + limit,limit); }else onTaskCompleted(); }, //consumer this::onError, repository.getRestApi().getConceptAnswers(accessToken,MIN_DATETIME,offset,limit), //producer TIMEOUT); } //Concept public void getConcept(String accessToken, LocalDateTime MIN_DATETIME,final long offset, int limit){ ConcurrencyUtils.consumeAsync( concepts -> { if(concepts.length > 0){ db.conceptDao().insert(concepts); updateMetadata(concepts, EntityType.CONCEPT); getConcept(accessToken,MIN_DATETIME,offset + limit,limit); }else this.onTaskCompleted(); }, //consumer this::onError, repository.getRestApi().getConcept(accessToken,MIN_DATETIME,offset,limit), //producer TIMEOUT); } //Location public void getLocations(String accessToken, LocalDateTime MIN_DATETIME,final long offset, int limit){ ConcurrencyUtils.consumeAsync( locations -> { if(locations.length > 0){ db.locationDao().insert(locations); updateMetadata(locations, EntityType.LOCATION); getLocations(accessToken,MIN_DATETIME,offset + limit,limit); }else onTaskCompleted(); }, //consumer this::onError, repository.getRestApi().getLocations(accessToken,MIN_DATETIME,offset,limit), //producer TIMEOUT); } }
package officehours05_03; import java.util.ArrayList; import java.util.Arrays; public class FourOrLess { public static void main(String[] args) { //remove in ArrayList //remove(0) ArrayList<String> list =new ArrayList<>(Arrays.asList("apples", "tree", "loop", "cat", "animal", "shortcut")); ArrayList<String> list2 =new ArrayList<>(); for(String each : list){ if(each.length() <= 4){ list2.add(each); } } System.out.println(list2); } }
package com.vietmedia365.voaapp.service; import com.vietmedia365.voaapp.model.Chapter; import com.vietmedia365.voaapp.model.Story; import java.util.List; import retrofit.Callback; import retrofit.http.GET; import retrofit.http.Path; import retrofit.http.Query; /** * Created by pat109 on 9/26/2014. */ public interface StoryService { @GET(value = "/shortstory/stories") public void getStories(@Query("type") String type, @Query("sort") String sort, @Query("page") int page, Callback<List<Story>> listCallback); @GET(value = "/shortstory/stories/{id}") public void getStory(@Path("id") String id, Callback<Story> storyCallback); @GET(value = "/story/{id}/chapters") public void getChapters(@Path("id") String id, @Query("page") int page, Callback<List<Chapter>> listCallback); @GET(value = "/chapter/{id}") public void getChapter(@Path("id") String id, Callback<Chapter> chapterCallback); @GET(value = "/chapter/{id}/next") public void getChapterNext(@Path("id") String id, Callback<Chapter> chapterCallback); @GET(value = "/chapter/{id}/previous") public void getChapterPrevious(@Path("id") String id, Callback<Chapter> chapterCallback); @GET(value = "/story/{id}/chapter/{episode}") public void getChapter(@Path("id") String id, @Path("episode") String episode, Callback<Chapter> chapterCallback); @GET(value = "/shortstory/search") public void search(@Query("q") String query, @Query("page") int page, Callback<List<Story>> listCallback); }
package collections.main_task.confection; public abstract class Sweetness { private String nameSweetness; private int weightSweetness; public Sweetness(String nameSweetness, int weightSweetness) { this.nameSweetness = nameSweetness; this.weightSweetness = weightSweetness; } public String getNameSweetness() { return nameSweetness; } public void setNameSweetness(String nameSweetness) { this.nameSweetness = nameSweetness; } public int getWeightSweetness() { return weightSweetness; } public abstract double getCountSugarOneHundredGrams(); public void setWeightSweetness(int weightSweetness) { if (weightSweetness <= 0) { throw new IllegalArgumentException("Weight should be more than 0"); } this.weightSweetness = weightSweetness; } @Override public String toString() { return "[" + nameSweetness + ", weightSweetness=" + weightSweetness + ']'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Sweetness sweetness = (Sweetness) o; if (Double.compare(sweetness.weightSweetness, weightSweetness) != 0) return false; return nameSweetness != null ? nameSweetness.equals(sweetness.nameSweetness) : sweetness.nameSweetness == null; } @Override public int hashCode() { int result; long temp; result = nameSweetness != null ? nameSweetness.hashCode() : 0; temp = Double.doubleToLongBits(weightSweetness); result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } }
package com.union.design.auth.jwt; import org.apache.commons.lang3.StringUtils; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AuthenticationFailureHandler; import org.springframework.security.web.authentication.AuthenticationSuccessHandler; import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Objects; public class JwtAuthenticationFilter extends OncePerRequestFilter { private final RequestMatcher requireAuthenticationRequestMatcher; private final JwtTokenManager tokenManager; private AuthenticationManager authenticationManager; private AuthenticationSuccessHandler authenticationSuccessHandler; private AuthenticationFailureHandler authenticationFailureHandler; public JwtAuthenticationFilter(JwtTokenManager tokenManager) { this.tokenManager = tokenManager; requireAuthenticationRequestMatcher = new RequestHeaderRequestMatcher("Authorization"); } @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!requireAuthenticationRequestMatcher.matches(request)) { filterChain.doFilter(request, response); return; } Authentication authentication = null; AuthenticationException exception = null; String authorization = StringUtils.removeStart("Bearer ", request.getHeader("Authorization")); if (StringUtils.isNotBlank(authorization)) { authentication = authenticationManager.authenticate(tokenManager.getAuthentication(authorization)); } else { exception = new InsufficientAuthenticationException("token is empty"); } if (Objects.nonNull(authentication)) { authenticationSuccessHandler.onAuthenticationSuccess(request, response, authentication); } else { authenticationFailureHandler.onAuthenticationFailure(request, response, exception); } } public JwtAuthenticationFilter setAuthenticationSuccessHandler(AuthenticationSuccessHandler authenticationSuccessHandler) { this.authenticationSuccessHandler = authenticationSuccessHandler; return this; } public JwtAuthenticationFilter setAuthenticationFailureHandler(AuthenticationFailureHandler authenticationFailureHandler) { this.authenticationFailureHandler = authenticationFailureHandler; return this; } }
package com.tatteam.popthecamera.android; import android.os.Bundle; import android.os.Handler; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.badlogic.gdx.backends.android.AndroidFragmentApplication; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.InterstitialAd; import com.tatteam.popthecamera.Constants; import com.tatteam.popthecamera.GDXGameLauncher; /** * Created by ThanhNH on 9/29/2015. */ public class GameFragment extends AndroidFragmentApplication implements GDXGameLauncher.OnGameListener { public static final String KEY_GAME_MODE = "game_mode"; public static final int GAME_MODE_CLASSIC_SLOW = 1; public static final int GAME_MODE_CLASSIC_MEDIUM = 2; public static final int GAME_MODE_CLASSIC_FAST = 3; public static final int GAME_MODE_CLASSIC_CRAZY = 4; public static final int GAME_MODE_UNLIMITED = 10; private Handler handler; private GDXGameLauncher gameLauncher; private InterstitialAd interstitialAd; private int lossGameCounter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { lossGameCounter = 0; handler = new Handler(); setupAds(); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration(); gameLauncher = new GDXGameLauncher(); gameLauncher.setOnGameListener(this); Bundle bundle = this.getArguments(); int gameMode = bundle.getInt(KEY_GAME_MODE, GAME_MODE_CLASSIC_MEDIUM); switch (gameMode) { case GAME_MODE_CLASSIC_SLOW: gameLauncher.setGameMode(Constants.GameMode.CLASSIC_SLOW); break; case GAME_MODE_CLASSIC_MEDIUM: gameLauncher.setGameMode(Constants.GameMode.CLASSIC_MEDIUM); break; case GAME_MODE_CLASSIC_FAST: gameLauncher.setGameMode(Constants.GameMode.CLASSIC_FAST); break; case GAME_MODE_CLASSIC_CRAZY: gameLauncher.setGameMode(Constants.GameMode.CLASSIC_CRAZY); break; case GAME_MODE_UNLIMITED: gameLauncher.setGameMode(Constants.GameMode.UNLIMITED); break; } return initializeForView(gameLauncher, config); } @Override public void onLossGame(GDXGameLauncher gameLauncher, Constants.GameMode gameMode, int currentLevel, int score) { displayAdsIfNeeded(gameMode, currentLevel, score); } @Override public void onGameBackPressed() { getFragmentManager().popBackStack(); } private void displayAdsIfNeeded(Constants.GameMode gameMode, int currentLevel, int score) { if (!MainActivity.ADS_ENABLE) return; lossGameCounter++; if (gameMode == Constants.GameMode.UNLIMITED) { if (lossGameCounter % 3 == 0) { displayAds(); } } else { if (gameMode == Constants.GameMode.CLASSIC_SLOW) { if (currentLevel >= 4 && lossGameCounter % 3 == 0) { displayAds(); } } else if (gameMode == Constants.GameMode.CLASSIC_MEDIUM) { if (currentLevel >= 4 && lossGameCounter % 3 == 0) { displayAds(); } } else if (gameMode == Constants.GameMode.CLASSIC_FAST) { if (currentLevel >= 4 && lossGameCounter % 4 == 0) { displayAds(); } } else if (gameMode == Constants.GameMode.CLASSIC_CRAZY) { if (currentLevel >= 4 && lossGameCounter % 4 == 0) { displayAds(); } } } } private void displayAds() { if (!MainActivity.ADS_ENABLE) return; updateOnUIThread(new Runnable() { @Override public void run() { interstitialAd.show(); } }); } private void updateOnUIThread(Runnable runnable) { handler.post(runnable); } private void setupAds() { if (!MainActivity.ADS_ENABLE) return; interstitialAd = new InterstitialAd(this.getActivity()); interstitialAd.setAdUnitId(getString(R.string.big_banner_ad_unit_id)); requestNewInterstitial(); interstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { requestNewInterstitial(); } }); } private void requestNewInterstitial() { AdRequest adRequest = new AdRequest.Builder().build(); interstitialAd.loadAd(adRequest); } }