text
stringlengths
10
2.72M
// Generated by view binder compiler. Do not edit! package com.designurway.idlidosa.databinding; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.core.widget.NestedScrollView; import androidx.recyclerview.widget.RecyclerView; import androidx.viewbinding.ViewBinding; import com.designurway.idlidosa.R; import java.lang.NullPointerException; import java.lang.Override; import java.lang.String; public final class FragmentHomeBinding implements ViewBinding { @NonNull private final ConstraintLayout rootView; @NonNull public final TextView addressLayout; @NonNull public final Button btnEmergency; @NonNull public final ImageView img1; @NonNull public final LinearLayout linearOffer; @NonNull public final LinearLayout linearSos; @NonNull public final ProgressBar progress; @NonNull public final RecyclerView recyclerViewBulk; @NonNull public final RecyclerView recyclerViewCombo; @NonNull public final RecyclerView recyclerViewFeatured; @NonNull public final NestedScrollView scrollViewDashboard; @NonNull public final TextView textBulk; @NonNull public final TextView textCombo; @NonNull public final TextView textFeatured; private FragmentHomeBinding(@NonNull ConstraintLayout rootView, @NonNull TextView addressLayout, @NonNull Button btnEmergency, @NonNull ImageView img1, @NonNull LinearLayout linearOffer, @NonNull LinearLayout linearSos, @NonNull ProgressBar progress, @NonNull RecyclerView recyclerViewBulk, @NonNull RecyclerView recyclerViewCombo, @NonNull RecyclerView recyclerViewFeatured, @NonNull NestedScrollView scrollViewDashboard, @NonNull TextView textBulk, @NonNull TextView textCombo, @NonNull TextView textFeatured) { this.rootView = rootView; this.addressLayout = addressLayout; this.btnEmergency = btnEmergency; this.img1 = img1; this.linearOffer = linearOffer; this.linearSos = linearSos; this.progress = progress; this.recyclerViewBulk = recyclerViewBulk; this.recyclerViewCombo = recyclerViewCombo; this.recyclerViewFeatured = recyclerViewFeatured; this.scrollViewDashboard = scrollViewDashboard; this.textBulk = textBulk; this.textCombo = textCombo; this.textFeatured = textFeatured; } @Override @NonNull public ConstraintLayout getRoot() { return rootView; } @NonNull public static FragmentHomeBinding inflate(@NonNull LayoutInflater inflater) { return inflate(inflater, null, false); } @NonNull public static FragmentHomeBinding inflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent, boolean attachToParent) { View root = inflater.inflate(R.layout.fragment_home, parent, false); if (attachToParent) { parent.addView(root); } return bind(root); } @NonNull public static FragmentHomeBinding bind(@NonNull View rootView) { // The body of this method is generated in a way you would not otherwise write. // This is done to optimize the compiled bytecode for size and performance. int id; missingId: { id = R.id.address_layout; TextView addressLayout = rootView.findViewById(id); if (addressLayout == null) { break missingId; } id = R.id.btn_emergency; Button btnEmergency = rootView.findViewById(id); if (btnEmergency == null) { break missingId; } id = R.id.img1; ImageView img1 = rootView.findViewById(id); if (img1 == null) { break missingId; } id = R.id.linear_offer; LinearLayout linearOffer = rootView.findViewById(id); if (linearOffer == null) { break missingId; } id = R.id.linear_sos; LinearLayout linearSos = rootView.findViewById(id); if (linearSos == null) { break missingId; } id = R.id.progress; ProgressBar progress = rootView.findViewById(id); if (progress == null) { break missingId; } id = R.id.recycler_view_bulk; RecyclerView recyclerViewBulk = rootView.findViewById(id); if (recyclerViewBulk == null) { break missingId; } id = R.id.recycler_view_combo; RecyclerView recyclerViewCombo = rootView.findViewById(id); if (recyclerViewCombo == null) { break missingId; } id = R.id.recycler_view_featured; RecyclerView recyclerViewFeatured = rootView.findViewById(id); if (recyclerViewFeatured == null) { break missingId; } id = R.id.scroll_view_dashboard; NestedScrollView scrollViewDashboard = rootView.findViewById(id); if (scrollViewDashboard == null) { break missingId; } id = R.id.text_bulk; TextView textBulk = rootView.findViewById(id); if (textBulk == null) { break missingId; } id = R.id.text_combo; TextView textCombo = rootView.findViewById(id); if (textCombo == null) { break missingId; } id = R.id.text_featured; TextView textFeatured = rootView.findViewById(id); if (textFeatured == null) { break missingId; } return new FragmentHomeBinding((ConstraintLayout) rootView, addressLayout, btnEmergency, img1, linearOffer, linearSos, progress, recyclerViewBulk, recyclerViewCombo, recyclerViewFeatured, scrollViewDashboard, textBulk, textCombo, textFeatured); } String missingId = rootView.getResources().getResourceName(id); throw new NullPointerException("Missing required view with ID: ".concat(missingId)); } }
package com.onlyu.reactiveprog.services.reactive; import com.onlyu.reactiveprog.ReactiveprogApplication; import com.onlyu.reactiveprog.domain.Ingredient; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import static org.junit.Assert.assertEquals; @RunWith(SpringRunner.class) @SpringBootTest(classes = ReactiveprogApplication.class) @WebAppConfiguration public class IngredientReactiveServiceTest { @Autowired private IngredientReactiveService ingredientReactiveService; @Before public void setUp() { } @After public void tearDown() { } @Test public void findByRecipeIdAndIngredientDescriptionNormal() { Ingredient ingredient = ingredientReactiveService.findByRecipeIdAndIngredientDescriptionNormal( "5b96979045a50d070268f719", "cilantro"); assertEquals("Cilantro", ingredient.getDescription()); } }
package com.an.distributed.election.message; import com.an.distributed.election.core.Message; import com.an.distributed.election.core.ProtocolException; import java.io.ByteArrayOutputStream; import java.io.IOException; /** * @ClassName Ok * @Description Ok * @Author an * @Date 2019/7/4 上午9:20 * @Version 1.0 */ public class Ok extends Message { public static String COMMAND = "ok"; private int id; public Ok(byte[] payload) { super(payload); } public Ok(int id) { this.id = id; } @Override public void parse() throws ProtocolException { id = (int) readUint32(); } @Override protected byte[] doSerialize() throws IOException, ProtocolException { ByteArrayOutputStream stream = new ByteArrayOutputStream(); uint32ToByteStream(id, stream); return stream.toByteArray(); } @Override public String getCommand() { return Ok.COMMAND; } @Override public int getLength() { return 4; } @Override public String toString() { return "Ok{" + "id=" + id + ", header=" + header + '}'; } }
package mekfarm.inventories; import net.minecraft.item.ItemStack; /** * Created by CF on 2016-11-07. */ public interface IInternalItemHandler { int getSlots(); void setStackInSlot(int slot, ItemStack stack, boolean internal); ItemStack getStackInSlot(int slot, boolean internal); ItemStack insertItem(int slot, ItemStack stack, boolean simulate, boolean internal); ItemStack extractItem(int slot, int amount, boolean simulate, boolean internal); }
package leetCode; import java.util.HashMap; import java.util.Map; /** * Created by gengyu.bi on 2014/12/29. */ public class UniquePathsII { Map<String, Integer> store = new HashMap<String, Integer>(); public int uniquePathsWithObstacles(int[][] obstacleGrid) { int m = obstacleGrid.length - 1; int n = obstacleGrid[0].length - 1; if (obstacleGrid[m][n] == 1 || obstacleGrid[0][0] == 1) { return 0; } return uniquePaths(m, n, obstacleGrid); } private int uniquePaths(int m, int n, int[][] obstacleGrid) { if (m == 0 && n == 0) { return 1; } if (m == 0 || n == 0) { if (m == 0) { if (obstacleGrid[m][n - 1] == 1) { return 0; } else { return uniquePaths(m, n - 1, obstacleGrid); } } else { if (obstacleGrid[m - 1][n] == 1) { return 0; } else { return uniquePaths(m - 1, n, obstacleGrid); } } } else { String key = m + "," + n; if (store.get(key) != null) { return store.get(key); } else { int a = obstacleGrid[m - 1][n] == 1 ? 0 : uniquePaths(m - 1, n, obstacleGrid); int b = obstacleGrid[m][n - 1] == 1 ? 0 : uniquePaths(m, n - 1, obstacleGrid); int value = a + b; store.put(key, value); return value; } } } public static void main(String[] args) { UniquePathsII uniquePathsII = new UniquePathsII(); int r = uniquePathsII.uniquePathsWithObstacles( new int[][]{{0, 1, 0, 0, 0}, {1, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}}); System.out.println(r); } }
/** * Java. Level 2. Lesson 4. Example of homework * * @author Sergey Iryupin * @version 0.1.1 dated Nov 07, 2017 */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; class HW4Lesson extends JFrame implements ActionListener { final String TITLE_OF_PROGRAM = "Client for net.chat"; final int START_LOCATION = 200; final int WINDOW_WIDTH = 350; final int WINDOW_HEIGHT = 450; final String BTN_ENTER = "Enter"; final String LOG_FILE_NAME = "logchat.txt"; JTextArea dialogue; // area for dialog JTextField message; // field for entering messages public static void main(String[] args) { new HW4Lesson(); } /** * Constructor: * Creating a window and all the necessary elements on it */ HW4Lesson() { setTitle(TITLE_OF_PROGRAM); setDefaultCloseOperation(EXIT_ON_CLOSE); setBounds(START_LOCATION, START_LOCATION, WINDOW_WIDTH, WINDOW_HEIGHT); // area for dialog dialogue = new JTextArea(); dialogue.setEditable(false); JScrollPane scrollBar = new JScrollPane(dialogue); // panel for checkbox, message field and button JPanel bp = new JPanel(); bp.setLayout(new BoxLayout(bp, BoxLayout.X_AXIS)); message = new JTextField(); message.addActionListener(this); JButton enter = new JButton(BTN_ENTER); enter.addActionListener(this); // adding all elements to the window bp.add(message); bp.add(enter); add(BorderLayout.CENTER, scrollBar); add(BorderLayout.SOUTH, bp); setVisible(true); } /** * Listener of events from message field and enter button */ @Override public void actionPerformed(ActionEvent event) { if (message.getText().trim().length() > 0) { dialogue.append(message.getText() + "\n"); try (PrintWriter pw = new PrintWriter(new FileWriter(LOG_FILE_NAME, true))) { pw.println(message.getText()); pw.flush(); } catch (IOException ex) { } } message.setText(""); message.requestFocusInWindow(); } }
package com.flyusoft.apps.jointoil.dao.impl; import java.util.Date; import java.util.List; import org.springframework.stereotype.Repository; import com.flyusoft.apps.jointoil.dao.TwoBoosterCompressorDao; import com.flyusoft.apps.jointoil.entity.TwoBoosterCompressor; import com.flyusoft.common.dao.impl.BaseHibernateDaoImpl; import com.flyusoft.common.orm.Page; @Repository public class TwoBoosterCompressorDaoImpl extends BaseHibernateDaoImpl<TwoBoosterCompressor,String> implements TwoBoosterCompressorDao{ private final static String QUERY_MONITORDATA_BY_LAST_MONITORTIME = "from TwoBoosterCompressor data where data.compressorCode = ? order by data.time desc"; private final static String QUERY_DATA_BY_WELLID_AND_TIME_INTERVAL = "from TwoBoosterCompressor data where data.compressorCode=? and (data.time between ? and ?) order by data.time"; private final static String QUERY_ALL_LAST_DATA="select com.* from fly_two_booster_compressor com group by com.id,com.compressor_code order by com.time desc,com.compressor_code asc limit ?"; private final static String QUERY_DATA_BY_TIME = "from TwoBoosterCompressor where compressorCode=? and time between ? and ? order by time desc"; @Override public TwoBoosterCompressor searchMonitorDataByLastTime(String compressorCode) { List<TwoBoosterCompressor> list=createQuery(QUERY_MONITORDATA_BY_LAST_MONITORTIME, compressorCode).list(); if(list!=null&&list.size()>0){ return list.get(0); } return null; } @SuppressWarnings("unchecked") @Override public List<TwoBoosterCompressor> searchDataByCompressorCodeAndTimeInterval( String _compressorCode, Date _startDate, Date _endDate) { return createQuery(QUERY_DATA_BY_WELLID_AND_TIME_INTERVAL, _compressorCode, _startDate, _endDate).list(); } @Override public List<TwoBoosterCompressor> getAllLastTwoBoosterCompressors( int compressorNum) { // TODO Auto-generated method stub return null; } @Override public Page<TwoBoosterCompressor> getTwoBoosterMsg( Page<TwoBoosterCompressor> pageMonitor, String compressorCode, Date start_date, Date end_date) { return findPage(pageMonitor, QUERY_DATA_BY_TIME, compressorCode,start_date,end_date); } }
package com.yevhenchmykhun.filter; import com.yevhenchmykhun.util.HibernateUtil; import org.hibernate.SessionFactory; import org.hibernate.StaleObjectStateException; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; @WebFilter(filterName = "HibernateSessionRequestFilter", urlPatterns = {"/*"}) public class HibernateSessionRequestFilter implements Filter { private SessionFactory sessionFactory; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { try { sessionFactory.getCurrentSession().beginTransaction(); chain.doFilter(request, response); sessionFactory.getCurrentSession().getTransaction().commit(); } catch (StaleObjectStateException e) { // Compensation actions throw e; } catch (Throwable e) { // Rollback only e.printStackTrace(); try { if (sessionFactory.getCurrentSession().getTransaction() != null) { System.out .println("Trying to rollback database transaction after exception."); sessionFactory.getCurrentSession().getTransaction() .rollback(); } } catch (Throwable ex) { System.out .println("Could not rollback transaction after exception!"); } } } public void init(FilterConfig fConfig) throws ServletException { sessionFactory = HibernateUtil.getSessionFactory(); } public void destroy() { } }
package com.example.lab3; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; public class BMIActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_bmi); Intent intent = getIntent(); String person = intent.getStringExtra("name"); String message = intent.getStringExtra("bmi"); //display the messages in a TextView TextView tv = (TextView) findViewById(R.id.textView3); TextView lv = (TextView) findViewById(R.id.textView3); tv.setText(person + message); } }
package com.icanit.app_v2.activity; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.view.ViewPager; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.icanit.app_v2.R; import com.icanit.app_v2.adapter.MerchandizeCateLvAdapter; import com.icanit.app_v2.adapter.MyMerchandiseLvAdapter; import com.icanit.app_v2.common.IConstants; import com.icanit.app_v2.entity.AppCategory; import com.icanit.app_v2.entity.AppGoods; import com.icanit.app_v2.entity.AppMerchant; import com.icanit.app_v2.exception.AppException; import com.icanit.app_v2.ui.AutoChangeCheckRadioGroup; import com.icanit.app_v2.util.AppUtil; import com.icanit.app_v2.util.DeviceInfoUtil; public class MerchandizeListActivity extends Activity implements OnClickListener, TextWatcher { private AppMerchant merchant; private ImageButton backButton, searchButton; private FrameLayout shoppingCart; private View lvHeader; private TextView category, search, collection, recommend, location, minCost, postscript, title, cartItemQuantity; private ListView lv; private MyMerchandiseLvAdapter merLvAdapter; private MerCateChooseDialogBuilder dialog01; private ImageView animateImage; private ViewGroup container; private FrameLayout adContainer; private ViewPager adContent; private AutoChangeCheckRadioGroup adIndicator; private Button textDisposer; private ViewGroup vg; private EditText searchField; private Handler handler = new Handler(Looper.getMainLooper()); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_merchandize_list); try { init(); AppUtil.getServiceFactory().getUserBrowsingDaoInstance(this) .addToBrowsedMerchant(merchant, AppUtil.getLoginPhoneNum()); initLv(); bindListeners(); } catch (AppException e) { e.printStackTrace(); } } protected void onResume() { super.onResume(); fillMerchantInfo(); if (adIndicator != null) adIndicator.restartAd(); if (merLvAdapter != null) { merLvAdapter.updateCartItemQuantity(); merLvAdapter.notifyDataSetChanged(); } } protected void onPause() { super.onPause(); if (adIndicator != null) adIndicator.stopAd(); } protected void onDestroy() { super.onDestroy(); if (dialog01 != null) dialog01.dismissDialog(); } private void initDialog() { if (merLvAdapter == null || merLvAdapter.getGoodsList() == null) return; dialog01 = new MerCateChooseDialogBuilder(this); IConstants.THREAD_POOL.submit(new Runnable() { public void run() { final List<AppCategory> cateList = new ArrayList<AppCategory>(); // final List<AppGoods> // goodsList=AppUtil.getServiceFactory().getDataServiceInstance(MerchandizeListActivity.this). // getProductsInfoByStoreId(merchant.id); setCateListsCount(cateList, merLvAdapter.getGoodsList()); handler.post(new Runnable() { public void run() { dialog01.setMerCateList(cateList); // merLvAdapter.setGoodsList(goodsList); } }); } }); } private void setCateListsCount(List<AppCategory> cateList, List<AppGoods> goodsList) { AppGoods goods; for (int i = 0; i < goodsList.size(); i++) { goods = goodsList.get(i); if(!cateContains(cateList, goods.cateId)){ cateList.add(new AppCategory(goods.cateId,goods.cateName,0,0,1)); } } } private boolean cateContains(List<AppCategory> cateList,int cateid){ for(int i=0;i<cateList.size();i++){ if(cateList.get(i).id==cateid){ cateList.get(i).count++; return true; } } return false; } private void fillMerchantInfo() { title.setText(merchant.merName); location.setText(merchant.location); minCost.setText("起送价格:"+AppUtil.formatMoney(merchant.deliverPrice)); postscript.setText(merchant.detail); collection.setSelected(AppUtil.hadCollected(merchant.id)); if (AppUtil.hadRecommended(merchant.id)) { recommend.setText(merchant.recommend + 1 + ""); recommend.setSelected(true); } else { recommend.setText(merchant.recommend + ""); recommend.setSelected(false); } } private void init() throws AppException { lvHeader = LayoutInflater.from(this).inflate( R.layout.header4lv_merchandizelist, null, false); backButton = (ImageButton) findViewById(R.id.imageButton1); shoppingCart = (FrameLayout) findViewById(R.id.frameLayout1); category = (TextView) lvHeader.findViewById(R.id.textView1); search = (TextView) lvHeader.findViewById(R.id.textView2); collection = (TextView) lvHeader.findViewById(R.id.textView3); recommend = (TextView) lvHeader.findViewById(R.id.textView4); location = (TextView) lvHeader.findViewById(R.id.textView5); minCost = (TextView) lvHeader.findViewById(R.id.textView6); postscript = (TextView) lvHeader.findViewById(R.id.textView7); searchButton = (ImageButton) lvHeader.findViewById(R.id.imageButton1); searchField = (EditText) lvHeader.findViewById(R.id.editText1); textDisposer = (Button) lvHeader.findViewById(R.id.button1); vg = (ViewGroup) lvHeader.findViewById(R.id.relativeLayout1); title = (TextView) findViewById(R.id.textView9); cartItemQuantity = (TextView) findViewById(R.id.textView10); lv = (ListView) findViewById(R.id.listView1); animateImage = (ImageView) findViewById(R.id.imageView1); container = (ViewGroup) findViewById(R.id.relativeLayout2); adContainer = (FrameLayout) lvHeader.findViewById(R.id.frameLayout3); merchant = (AppMerchant) getIntent().getSerializableExtra( IConstants.MERCHANT_KEY); } private void findAdGoodsList(List<AppGoods> goodsList) throws AppException { adContainer.removeAllViews(); if (goodsList == null) return; final List<AppGoods> adGoodsList = new ArrayList<AppGoods>(); for (int i = 0; i < goodsList.size(); i++) { AppGoods goods = goodsList.get(i); // TODO advertisement // if (goods.advertStatus == 1) // adGoodsList.add(goods); } if (adGoodsList == null || adGoodsList.isEmpty()) { AppUtil.setNoAdImage(adContainer, this); } else { adContent = AppUtil.setMerchandizeAdPagers(adContainer, adContent, adGoodsList, MerchandizeListActivity.this); Object obj = adContent.getTag(); if (obj != null) adIndicator = (AutoChangeCheckRadioGroup) obj; } } private void initLv() throws AppException { lv.addHeaderView(lvHeader, null, false); lv.setAdapter(merLvAdapter = new MyMerchandiseLvAdapter(this, cartItemQuantity, container, animateImage, merchant)); IConstants.THREAD_POOL.submit(new Runnable() { public void run() { try { final List<AppGoods> goodsList = AppUtil .getServiceFactory() .getDataServiceInstance( MerchandizeListActivity.this) .getProductsInfoByStoreId(merchant.id); handler.post(new Runnable() { public void run() { try { findAdGoodsList(goodsList); } catch (AppException e) { e.printStackTrace(); } merLvAdapter.setGoodsList(goodsList); } }); } catch (final AppException e) { e.printStackTrace(); } } }); /* * lv.setOnItemClickListener(new OnItemClickListener() { public void * onItemClick(AdapterView<?> parent, View v, int position, long id) { * shoppingCartService * .addCartItem(merLvAdapter.getGoodsListByCate().get( * position),merchant); ImageView imageView = * (ImageView)v.findViewById(R.id.imageView1); try { * AnimationUtil.startBuyingAnimation * (animateImage,rlContainer,imageView, * shoppingCart,MerchandizeListActivity.this); } catch (Exception e) { * e.printStackTrace(); } * * } }); */ AppUtil.getListenerUtilInstance().setOnScrollListener(lv, merLvAdapter); } private void bindListeners() { AppUtil.bindBackListener(backButton); shoppingCart.setOnClickListener(this); category.setOnClickListener(this); recommend.setOnClickListener(this); collection.setOnClickListener(this); textDisposer.setOnClickListener(this); searchField.addTextChangedListener(this); AppUtil.bindSearchEditTextTrigger(search, searchButton, vg); } // private List<Map<String,Object>> getCateData(){ // List<Map<String,Object>> data = new ArrayList<Map<String,Object>>(); // String[] sary = new String[]{"全部商品","未分类","饮料","干调","方便面", // "生活用品","小食品","巧克力","瓜子","饼干","烟酒","国产烟"}; // for(int i =0;i<sary.length;i++){ // Map<String,Object> map = new HashMap<String,Object>(); // map.put("cateName", sary[i]);map.put("count", (int)(Math.random()*1000)); // data.add(map); // } // return data; // } public void showMerchandizeDetail(AppGoods goods) { Intent intent = new Intent() .setClassName(getPackageName(), MerchandizeDetailActivity.class.getCanonicalName()) .putExtra(IConstants.GOODS_KEY, goods) .putExtra(IConstants.MERCHANT_KEY, merchant); startActivity(intent); } /** * * @author Administrator * */ class MerCateChooseDialogBuilder { private Dialog merCateChooseDialog; private MerchandizeCateLvAdapter adapter; public MerCateChooseDialogBuilder(Context context) { merCateChooseDialog = new Dialog(context, R.style.dialogStyle); merCateChooseDialog.setCanceledOnTouchOutside(true); View contentView = LayoutInflater.from(context).inflate( R.layout.dialog_merchandize_cates, null, false); merCateChooseDialog.setContentView(contentView, new LayoutParams( (int) (DeviceInfoUtil.getScreenWidth() * 0.9), (int) (DeviceInfoUtil.getScreenHeight() * 0.8))); ListView lv = (ListView) contentView.findViewById(R.id.listView1); lv.setAdapter(adapter = new MerchandizeCateLvAdapter(context)); lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { Toast.makeText(MerchandizeListActivity.this, adapter.getMerCateList().get(position).cateName, Toast.LENGTH_LONG).show(); merCateChooseDialog.dismiss(); merLvAdapter.classifyGoodsListByCateId(adapter .getMerCateList().get(position)); } }); } public void setMerCateList(List<AppCategory> merCateList) { System.out.println(merCateList + " @merchantdizeListActivity"); adapter.setMerCateList(merCateList); } public void showDialog() { merCateChooseDialog.show(); } public void dismissDialog() { merCateChooseDialog.dismiss(); } } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { if (after == 0) { if (textDisposer != null) textDisposer.setVisibility(View.GONE); } else { if (textDisposer != null) textDisposer.setVisibility(View.VISIBLE); } } @Override public void onTextChanged(CharSequence content, int start, int before, int count) { merLvAdapter.searchGoods(content); } @Override public void onClick(View v) { if (v == shoppingCart) { Intent intent = new Intent(MerchandizeListActivity.this, ShoppingCartSubstituteActivity.class); startActivity(intent); } else if (v == category) { if (dialog01 == null) { initDialog(); } if (dialog01 != null) dialog01.showDialog(); } else if (v == recommend) { AppUtil.recommend(merchant, recommend, MerchandizeListActivity.this); } else if (v == collection) { try { AppUtil.handlerCollectionEvent(merchant, collection, MerchandizeListActivity.this); } catch (AppException e) { e.printStackTrace(); } } else if (v == textDisposer) { searchField.setText(""); } } }
package component; import message.CMessage; import message.MTakeDamage; import message.Message; import org.newdawn.slick.GameContainer; import org.newdawn.slick.state.StateBasedGame; public class CHealth extends Component { private float health; public CHealth(){ this.id = "Health"; this.health = 100f; } public CHealth(float health){ this.id = "Health"; this.health = health; } public void takeDamage(MTakeDamage message){ health -= message.getDamage(); } public void takeDamage(float damage){ health -= damage; } @Override public void update(GameContainer gc, StateBasedGame sb, int delta) { if (health < 0 && owner != null) owner.destroy(); } @Override public void readMessage(Message message) { if (message.getText() == "TakeDamage"){ takeDamage((MTakeDamage) message); } } @Override public void readMessage(CMessage message) { // TODO Auto-generated method stub } @Override public void setDependencies() { // TODO Auto-generated method stub } public float getHealth() { return health; } }
package com.sai.one.algorithms.arrays; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by white on 12/7/2016. * http://www.programcreek.com/2015/01/leetcode-number-of-islands-ii-java/ */ public class MatrixNoOfIslands2 { public static void main(String args[]) { int[][] grid = null; numIslands2(5, 4, grid); } public static List<Integer> numIslands2(int m, int n, int[][] positions) { int[] rootArray = new int[m * n]; Arrays.fill(rootArray, -1); ArrayList<Integer> result = new ArrayList<Integer>(); int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}}; int count = 0; for (int k = 0; k < positions.length; k++) { count++; int[] p = positions[k]; int index = p[0] * n + p[1]; rootArray[index] = index;//set root to be itself for each node for (int r = 0; r < 4; r++) { int i = p[0] + directions[r][0]; int j = p[1] + directions[r][1]; if (i >= 0 && j >= 0 && i < m && j < n && rootArray[i * n + j] != -1) { //get neighbor's root int thisRoot = getRoot(rootArray, i * n + j); if (thisRoot != index) { rootArray[thisRoot] = index;//set previous root's root count--; } } result.add(count); } } return result; } public static int getRoot(int[] arr, int i) { while (arr[i] != i) { i = arr[arr[i]]; } return i; } }
/** * JPA domain objects. */ package com.eikesi.demo.domain;
package cn.itheima.ExamDemo.Test_04; public class Tram { private String brand; private int price; private int mile; public Tram() { } public Tram(String brand, int price, int mile) { this.brand = brand; this.price = price; this.mile = mile; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getMile() { return mile; } public void setMile(int mile) { this.mile = mile; } }
package multithreading.demo1; public class NumberPrinter implements Runnable { private String threadName; public NumberPrinter(String threadName) { super(); this.threadName = threadName; } @Override public void run() { for(int i=0; i<10; i++) { System.out.println(threadName + ": " + i); try { Thread.sleep(300); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
package hw2.task1_literal; /*** * Created by Maksim on 12.12.2017 */ public class Literal { public static void main(String[] args) { boolean varBool = true; String varString = "Hello, World!"; char varChar = '\u2622'; int varIntBin = 0b10101; //21 int varIntOct = 0707; //455 int varIntDec = 777; //77 int varIntHex = 0x654321; //6636321 float varFl = 123.456f; double varDouble = 123456.789D; System.out.println(varBool); System.out.println(varString); System.out.println(varChar); System.out.println(varIntBin); System.out.println(varIntOct); System.out.println(varIntDec); System.out.println(varIntHex); System.out.println(varFl); System.out.println(varDouble); } }
package com.sapl.retailerorderingmsdpharma.MyDatabase; /** * Created by Mrunal on 12/02/2018. */ import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteStatement; import com.sapl.retailerorderingmsdpharma.activities.MyApplication; import com.sapl.retailerorderingmsdpharma.models.OrderReviewModel; import com.sapl.retailerorderingmsdpharma.models.SubItemDataModel; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.SplittableRandom; /** * Created by Acer on 20/06/2016. */ public class TABLE_TEMP_ORDER_DETAILS { public static String LOG_TAG = "TABLE_TEMP_ORDER_DETAILS"; public static String NAME = "TempOrderDetails"; public static String COL_ID = "ID", COL_ORDER_ID = "OrderID", COL_ITEM_ID = "ItemID", COL_ITEM_NAME = "item_Name", COL_QUANTITY_ONE = "LargeUnit", COL_QUANTITY_TWO = "SmallUnit", COL_RATE = "Rate", /// ---->discounted_price_of_btl COL_DISCOUNTED_PRICE_OF_CASE = "discounted_price_cases", COL_AMOUNT = "Amount", COL_FREE_QUANTITY_ONE = "FreeLargeUnitQty", COL_FREE_QUANTITY_TWO = "FreeSmallUnitQty"; public static String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + NAME + " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_ORDER_ID + " TEXT," + COL_ITEM_ID + " TEXT," + COL_ITEM_NAME + " TEXT," + COL_QUANTITY_ONE + " TEXT," + COL_QUANTITY_TWO + " TEXT," + COL_RATE + " TEXT ," + COL_DISCOUNTED_PRICE_OF_CASE + " TEXT ," + COL_AMOUNT + " TEXT," + COL_FREE_QUANTITY_ONE + " TEXT ," + COL_FREE_QUANTITY_TWO + " TEXT )"; public static void insert_temp_bulk_OrderDetails(JSONArray jsonArray) { try { MyApplication.logi(LOG_TAG, "in TABLE_TEMP_ORDER_DETAILS->"); SQLiteDatabase db = MyApplication.db.getWritableDatabase(); db.beginTransaction(); String insert_sql = "insert into " + NAME + " ( " + COL_ID + ", " + COL_ORDER_ID + ", " + COL_ITEM_ID + ", " + COL_ITEM_NAME + ", " + COL_QUANTITY_ONE + ", " + COL_QUANTITY_TWO + ", " + COL_RATE + ", " + COL_DISCOUNTED_PRICE_OF_CASE + ", " + COL_AMOUNT + "," + COL_FREE_QUANTITY_ONE + "," + COL_FREE_QUANTITY_TWO + ") VALUES(?,?,?,?,?,?,?,?,?,?,?)"; MyApplication.logi(LOG_TAG, "insert_sql TABLE_TEMP_ORDER_DETAILS" + insert_sql); SQLiteStatement statement = db.compileStatement(insert_sql); JSONObject jsonObject = null; int count_array = jsonArray.length(); MyApplication.logi(LOG_TAG, "COUNT ISS->" + count_array); try { for (int i = 0; i < count_array; i++) { jsonObject = jsonArray.getJSONObject(i); statement.clearBindings(); statement.bindString(1, jsonObject.getString(COL_ID)); statement.bindString(2, jsonObject.getString(COL_ORDER_ID)); statement.bindString(3, jsonObject.getString(COL_ITEM_ID)); statement.bindString(4, jsonObject.getString(COL_ITEM_NAME)); statement.bindString(5, jsonObject.getString(COL_QUANTITY_ONE)); statement.bindString(6, jsonObject.getString(COL_QUANTITY_TWO)); statement.bindString(7, jsonObject.getString(COL_RATE)); statement.bindString(8, jsonObject.getString(COL_DISCOUNTED_PRICE_OF_CASE)); statement.bindString(9, jsonObject.getString(COL_AMOUNT)); statement.bindString(10, jsonObject.getString(COL_FREE_QUANTITY_ONE)); statement.bindString(11, jsonObject.getString(COL_FREE_QUANTITY_TWO)); statement.execute(); } MyApplication.logi(LOG_TAG, "EndTime->"); db.setTransactionSuccessful(); db.endTransaction(); } catch (JSONException e) { MyApplication.logi(LOG_TAG, "JSONException TABLE_TEMP_ORDER_DETAILS--->" + e.getMessage()); } } catch (Exception e) { MyApplication.logi(LOG_TAG, " TABLE_TEMP_ORDER_DETAILS exception--->" + e.getMessage()); } } public static int insertOrderDetails(String order_id, String str_item_id, String str_item_name, String str_quantity1, String str_quantity2, String discounted_price_of_btl, String discounted_price_of_case, float str_amt, String free_btls, String free_cases, String flag) { MyApplication.logi(LOG_TAG, "str_quantity1------->" + str_quantity1); MyApplication.logi(LOG_TAG, "str_quantity2------->" + str_quantity2); MyApplication.logi(LOG_TAG,"AMTTTTT"); MyApplication.logi(LOG_TAG, "in insertOrderDetails"); SQLiteDatabase db = MyApplication.db.getReadableDatabase(); ContentValues initialValues1 = new ContentValues(); initialValues1.put(COL_ORDER_ID, order_id); initialValues1.put(COL_ITEM_ID, str_item_id); initialValues1.put(COL_ITEM_NAME, str_item_name); initialValues1.put(COL_QUANTITY_ONE, str_quantity1); initialValues1.put(COL_QUANTITY_TWO, str_quantity2); initialValues1.put(COL_RATE, discounted_price_of_btl); /////discounted_price_of_BTL initialValues1.put(COL_DISCOUNTED_PRICE_OF_CASE, discounted_price_of_case); /////discounted_price_of_case initialValues1.put(COL_AMOUNT, str_amt); initialValues1.put(COL_FREE_QUANTITY_ONE, free_cases); initialValues1.put(COL_FREE_QUANTITY_TWO, free_btls); //initialValues1.put(COL_AMOUNT, str_amt); MyApplication.logi(LOG_TAG, "TempOrderDetails->" + initialValues1); if (flag == "insert_data") { MyApplication.logi(LOG_TAG, "IN INSERT"); long ret = db.insert(NAME, null, initialValues1); MyApplication.logi(LOG_TAG, "in TempOrderDetails ret->" + ret); if (ret > 0) { MyApplication.logi(LOG_TAG, "Successfull in TempOrderDetails ret ->" + ret); return 0; } else { MyApplication.logi(LOG_TAG, "Not successfiull in TempOrderDetails ret->" + ret); return 1; } } else if (flag == "update_data") { MyApplication.logi(LOG_TAG, "IN UPDATE"); long ret1 = db.update(NAME, initialValues1, "ItemID=? and OrderID=?", new String[]{str_item_id, order_id}); MyApplication.logi(LOG_TAG, "in TempOrderDetails ret->" + ret1); if (ret1 > 0) { MyApplication.logi(LOG_TAG, "UPDATED Successfull in TempOrderDetails ret ->" + ret1); return 0; } else { MyApplication.logi(LOG_TAG, "UPDATED Not successfiull in TempOrderDetails ret->" + ret1); return 1; } } return -1; } public static ArrayList<OrderReviewModel> getOrders(String order_id) { MyApplication.logi(LOG_TAG, "in getOrders"); String product_name; byte[] product_img_path; String no_of_cases; String no_of_bottels; String no_of_cases_free; String no_of_btls_free; String item_id; double amt; float discounted_single_btl_rate = 0.f, discounted_single_case_rate; SQLiteDatabase db = MyApplication.db.getReadableDatabase(); ArrayList<OrderReviewModel> res = new ArrayList<>(); String query = "SELECT RetailerImages.ImageDetails AS iImagePath, tod.Amount as Amountd,* FROM TempOrderDetails tod" + " ,TempRetailerOrderMaster tom LEFT JOIN RetailerImages" + " on cast(tod.ItemID as int) = RetailerImages.ImageId where tom.OrderID = tod.OrderID AND tom.OrderId ='" + order_id + "'"; /* String query = "SELECT RetailerImages.ImageDetails AS iImagePath, tod.Amount as Amountd,* FROM TempOrderDetails tod" + " ,TempRetailerOrderMaster tom LEFT JOIN RetailerImages" + " on cast(tod.ItemID as int) = RetailerImages.ImageId where tom.OrderID = tod.OrderID AND tom.OrderId ='" + order_id + "' AND tom.DistributorID = '" + Dist_id + "'"; */ //tom.DistributorID=Dist_id /* String query = "SELECT RetailerImages.ImageDetails AS iImagePath, tod.Amount as Amountd,* FROM TempOrderDetails tod ,TempRetailerOrderMaster tom,RetailerImages" + " where tom.OrderID = tod.OrderID AND tom.OrderId ='" + order_id + "' AND tod.ItemID = RetailerImages.ImageId"; */ MyApplication.logi(LOG_TAG, "QUERY FOR getOrders IS-->" + query); try { Cursor c = db.rawQuery(query, null); int count = c.getCount(); if (count > 0) { c.moveToFirst(); do { product_name = c.getString(c.getColumnIndexOrThrow("item_Name")); product_img_path = c.getBlob(c.getColumnIndexOrThrow("iImagePath")); no_of_cases = c.getString(c.getColumnIndexOrThrow("LargeUnit")); no_of_bottels = c.getString(c.getColumnIndexOrThrow("SmallUnit")); /* no_of_cases_free = c.getString(c.getColumnIndexOrThrow("SmallUnit")); no_of_btls_free = c.getString(c.getColumnIndexOrThrow("SmallUnit"));*/ item_id = c.getString(c.getColumnIndexOrThrow("ItemID")); amt = c.getDouble(c.getColumnIndexOrThrow("Amountd")); String amt1 = String.format("%.2f", amt); discounted_single_btl_rate = c.getFloat(c.getColumnIndexOrThrow("Rate")); discounted_single_case_rate = c.getFloat(c.getColumnIndexOrThrow("discounted_price_cases")); String total_after_edit = "0"; MyApplication.logi(LOG_TAG, "product_name---->" + product_name); MyApplication.logi(LOG_TAG, "no_of_cases---->" + no_of_cases); MyApplication.logi(LOG_TAG, "no_of_bottels---->" + no_of_bottels); MyApplication.logi(LOG_TAG, "item_id---->" + item_id); MyApplication.logi(LOG_TAG, "Amount---->" + amt1); MyApplication.logi(LOG_TAG, "single_btl_rate---->" + discounted_single_btl_rate); MyApplication.logi(LOG_TAG, "discounted_single_case_rate---->" + discounted_single_case_rate); OrderReviewModel previewModel = new OrderReviewModel(item_id, product_name, product_img_path, no_of_cases, no_of_bottels, "0", "0", amt1, discounted_single_btl_rate, discounted_single_case_rate, total_after_edit); MyApplication.logi(LOG_TAG, "PREVIEW Model---->" + previewModel); res.add(previewModel); } while (c.moveToNext()); } c.close(); } catch (Exception e) { MyApplication.logi(LOG_TAG, "getOrders in Exception" + e.getMessage()); } return res; } public static ArrayList<OrderReviewModel> getOrdersnew(String order_id,String Dist_id) { MyApplication.logi(LOG_TAG, "in getOrders"); String product_name; byte[] product_img_path; String no_of_cases; String no_of_bottels; String no_of_cases_free; String no_of_btls_free; String item_id; String DiscountType; String DiscountRate; double amt; float discounted_single_btl_rate = 0.f, discounted_single_case_rate; SQLiteDatabase db = MyApplication.db.getReadableDatabase(); ArrayList<OrderReviewModel> res = new ArrayList<>(); /* String query = "SELECT RetailerImages.ImageDetails AS iImagePath, tod.Amount as Amountd,* FROM TempOrderDetails tod" + " ,TempRetailerOrderMaster tom LEFT JOIN RetailerImages" + " on cast(tod.ItemID as int) = RetailerImages.ImageId where tom.OrderID = tod.OrderID AND tom.OrderId ='" + order_id + "'"; */ /* String query = "SELECT RetailerImages.ImageDetails AS iImagePath, tod.Amount as Amountd,* FROM TempOrderDetails tod" + " ,TempRetailerOrderMaster tom LEFT JOIN RetailerImages" + " on cast(tod.ItemID as int) = RetailerImages.ImageId where tom.OrderID = tod.OrderID AND tom.OrderId ='" + order_id + "' AND tom.DistributorID = '" + Dist_id + "'"; */ String query = "SELECT RetailerImages.ImageDetails AS iImagePath, tod.Amount as Amountd,p.SalesRate,p.DiscoutType,p.DiscountRate,* FROM TempOrderDetails tod ," + "TempRetailerOrderMaster tom,PriceListDetails p LEFT JOIN RetailerImages on cast(tod.ItemID as int) = RetailerImages.ImageId " + "where tom.OrderID = tod.OrderID AND tom.OrderId ='"+ order_id +"' " + "and p.PriceListID = '"+ Dist_id +"' and p.ItemID = tod.ItemID "; //tom.DistributorID=Dist_id /* String query = "SELECT RetailerImages.ImageDetails AS iImagePath, tod.Amount as Amountd,* FROM TempOrderDetails tod ,TempRetailerOrderMaster tom,RetailerImages" + " where tom.OrderID = tod.OrderID AND tom.OrderId ='" + order_id + "' AND tod.ItemID = RetailerImages.ImageId"; */ MyApplication.logi(LOG_TAG, "QUERY FOR getOrders IS-->" + query); try { Cursor c = db.rawQuery(query, null); int count = c.getCount(); if (count > 0) { c.moveToFirst(); do { product_name = c.getString(c.getColumnIndexOrThrow("item_Name")); product_img_path = c.getBlob(c.getColumnIndexOrThrow("iImagePath")); no_of_cases = c.getString(c.getColumnIndexOrThrow("LargeUnit")); no_of_bottels = c.getString(c.getColumnIndexOrThrow("SmallUnit")); /* no_of_cases_free = c.getString(c.getColumnIndexOrThrow("SmallUnit")); no_of_btls_free = c.getString(c.getColumnIndexOrThrow("SmallUnit"));*/ item_id = c.getString(c.getColumnIndexOrThrow("ItemID")); amt = c.getDouble(c.getColumnIndexOrThrow("Amountd")); String amt1 = String.format("%.2f", amt); discounted_single_btl_rate = c.getFloat(c.getColumnIndexOrThrow("SalesRate")); discounted_single_case_rate = c.getFloat(c.getColumnIndexOrThrow("SalesRate")); DiscountRate = c.getString(c.getColumnIndexOrThrow("DiscountRate")); DiscountType = c.getString(c.getColumnIndexOrThrow("DiscoutType")); String total_after_edit = "0"; MyApplication.logi(LOG_TAG, "product_name---->" + product_name); MyApplication.logi(LOG_TAG, "no_of_cases---->" + no_of_cases); MyApplication.logi(LOG_TAG, "no_of_bottels---->" + no_of_bottels); MyApplication.logi(LOG_TAG, "item_id---->" + item_id); MyApplication.logi(LOG_TAG, "Amount---->" + amt1); MyApplication.logi(LOG_TAG, "single_btl_rate---->" + discounted_single_btl_rate); MyApplication.logi(LOG_TAG, "discounted_single_case_rate---->" + discounted_single_case_rate); OrderReviewModel previewModel = new OrderReviewModel(item_id, product_name, product_img_path, no_of_cases, no_of_bottels, "0", "0", amt1, discounted_single_btl_rate, discounted_single_case_rate, total_after_edit,DiscountRate,DiscountType); MyApplication.logi(LOG_TAG, "PREVIEW Model---->" + previewModel); res.add(previewModel); } while (c.moveToNext()); } c.close(); } catch (Exception e) { MyApplication.logi(LOG_TAG, "getOrders in Exception" + e.getMessage()); } return res; } public static JSONObject getData(JSONObject jsonObject) { JSONArray jsonArray_master = new JSONArray(); MyApplication.logi(LOG_TAG, "IN JSONObject getDat "); SQLiteDatabase db = MyApplication.db.getReadableDatabase(); // String query = "SELECT * FROM " + NAME+ " where OrderID = '"+MyApplication.get_session(MyApplication.SESSION_ORDER_ID)+"'"; String query = "SELECT * FROM TempOrderDetails "; MyApplication.logi(LOG_TAG, "query getData-------->" + query); Cursor c = db.rawQuery(query, null); String retailerId = TABLE_PCUSTOMER.getCustId(); MyApplication.logi(LOG_TAG, "retailerId-------->" + retailerId); JSONArray jsonArray_details_master; JSONArray jsonArray_details = new JSONArray(); int count = c.getCount(); MyApplication.logi(LOG_TAG, "count="+count); //String DistributorId=TABLE_TEMP_RETAILER_ORDER_MASTER.getDistId(); try { if (c.getCount() > 0) { c.moveToFirst(); do { JSONObject jsonObject1 = new JSONObject(); String order_Id = c.getString(c.getColumnIndexOrThrow("OrderID")); jsonObject1.put("OrderId", order_Id); // jsonObject1.put("DistributorId", DistributorId); jsonObject1.put("RetailerId", retailerId); jsonObject1.put("OrderDate", c.getString(c.getColumnIndexOrThrow("OrderDate"))); String total_amt = TABLE_TEMP_ORDER_DETAILS.getSumOfAllItems(order_Id); if (total_amt == null) { jsonObject1.put("TotalAmount", "0"); MyApplication.set_session(MyApplication.SESSION_TOTAL_RPS_FOR_DASHBOARD_VALUE, "0.0"); } else { jsonObject1.put("TotalAmount", total_amt); MyApplication.set_session(MyApplication.SESSION_TOTAL_RPS_FOR_DASHBOARD_VALUE, total_amt); } jsonObject1.put("OrderStatus", "1"); jsonObject1.put("OrderRemarks", ""); jsonObject1.put("OrderRating", "0"); if (total_amt == null) { MyApplication.logi(LOG_TAG, "AMT IS 0"); } else { jsonArray_master.put(jsonObject1); } jsonArray_details = TABLE_TEMP_ORDER_DETAILS.getDetailsData(order_Id, jsonArray_details); } while (c.moveToNext()); jsonObject.put("OrderMaster", jsonArray_master); jsonObject.put("OrderDetails", jsonArray_details); } } catch (JSONException e) { e.printStackTrace(); } MyApplication.logi(LOG_TAG, "IN JSONObject jsonObject " + jsonObject); return jsonObject; } public static long deletePreviewOrder(String itemId, String orderId) { MyApplication.logi(LOG_TAG, "deletePreviewOrder-->itemit-->" + itemId + "ordeerid-->" + orderId); SQLiteDatabase db = MyApplication.db.getReadableDatabase(); long ret = db.delete(NAME, COL_ITEM_ID + " =? AND " + COL_ORDER_ID + " =? ", new String[]{"" + itemId, "" + orderId}); MyApplication.logi(LOG_TAG, "deletePreviewOrder" + ret); return ret; } public static JSONArray getDetailsData(String order_ID, JSONArray jsonArray_details) { // JSONArray jsonArray_details = new JSONArray(); MyApplication.logi(LOG_TAG, "IN JSONObject getDetailsData "); double amt, rate; SQLiteDatabase db = MyApplication.db.getReadableDatabase(); String query = "SELECT * FROM " + NAME + " WHERE " + COL_ORDER_ID + "='" + order_ID + "'"; Cursor c = db.rawQuery(query, null); int countt = c.getCount(); MyApplication.logi(LOG_TAG, "COUNT FOR CARTS-->" + countt); MyApplication.set_session(MyApplication.SESSION_SUBMIT_ORDER_CARTS_COUNT, countt + ""); try { if (c.getCount() > 0) { c.moveToFirst(); do { JSONObject jsonObject = new JSONObject(); jsonObject.put("OrderId", c.getString(c.getColumnIndexOrThrow(COL_ORDER_ID))); jsonObject.put("ItemID", c.getString(c.getColumnIndexOrThrow(COL_ITEM_ID))); jsonObject.put("LargeUnitQty", c.getString(c.getColumnIndexOrThrow(COL_QUANTITY_ONE))); jsonObject.put("SmallUnitQty", c.getString(c.getColumnIndexOrThrow(COL_QUANTITY_TWO))); /*jsonObject.put("FreeLargeUnitQty", c.getString(c.getColumnIndexOrThrow(COL_FREE_QUANTITY_ONE))); jsonObject.put("FreeSmallUnitQty", c.getString(c.getColumnIndexOrThrow(COL_FREE_QUANTITY_TWO)));*/ jsonObject.put("FreeLargeUnitQty", "0"); jsonObject.put("FreeSmallUnitQty", "0"); amt = c.getDouble(c.getColumnIndexOrThrow(COL_AMOUNT)); String amt1 = String.format("%.2f", amt); rate = c.getDouble(c.getColumnIndexOrThrow(COL_RATE)); String rate1 = String.format("%.2f", rate); jsonObject.put("Rate", rate1); jsonObject.put("Amount", amt1); /* jsonObject.put("Rate", c.getString(c.getColumnIndexOrThrow(COL_RATE))); jsonObject.put("Amount", c.getString(c.getColumnIndexOrThrow(COL_AMOUNT)));*/ jsonArray_details.put(jsonObject); } while (c.moveToNext()); } } catch (JSONException e) { e.printStackTrace(); } return jsonArray_details; } public static String getSumOfAllItemsnew(String orderId) { String total = "0.0"; String queery; SQLiteDatabase db = MyApplication.db.getReadableDatabase(); //queery = "SELECT SUM(TempOrderDetails.Amount) as TOTAL FROM " + NAME + " where OrderID = " + orderId; queery = "SELECT SUM(TempOrderDetails.Amount) as TOTAL FROM " + NAME ; //+ " where OrderID = " + orderId; Cursor cur = db.rawQuery(queery, null); MyApplication.logi(LOG_TAG, "getSumOfAllItems(), queery" + queery); if (cur.getCount() > 0) { cur.moveToFirst(); total = cur.getString(cur.getColumnIndexOrThrow("TOTAL")); } MyApplication.logi(LOG_TAG, "getSumOfAllItems(), total------------>" + total); return total; } public static String getSumOfAllItems(String orderId) { MyApplication.logi(LOG_TAG, "IN getSumOfAllItems "); String total = null; String queery; SQLiteDatabase db = MyApplication.db.getReadableDatabase(); queery = "SELECT SUM(TempOrderDetails.Amount) as TOTAL FROM " + NAME + " where OrderID = " + orderId; Cursor cur = db.rawQuery(queery, null); MyApplication.logi(LOG_TAG, "queery" + queery); if (cur.getCount() > 0) { cur.moveToFirst(); total = cur.getString(cur.getColumnIndexOrThrow("TOTAL")); MyApplication.logi(LOG_TAG, "IN total------------>" + total); } return total; } public static int check_Item_is_Already_Present(String orderId, String itemId) { MyApplication.logi(LOG_TAG, "in check_Item_is_Already_Present"); SQLiteDatabase db = MyApplication.db.getReadableDatabase(); ContentValues initialValues1 = new ContentValues(); String query = "SELECT * FROM TempOrderDetails where OrderID = " + orderId + " and ItemID = " + itemId; Cursor c = db.rawQuery(query, null); int count = c.getCount(); if (count > 0) { c.moveToFirst(); MyApplication.logi(LOG_TAG, "item is present I.E already saved to cart before"); return 1; } else { MyApplication.logi(LOG_TAG, "NEW save to cart "); return 0; } } public static ArrayList<SubItemDataModel> getListOfAlreadySavedToCartItems(String OrderId) { SQLiteDatabase db = MyApplication.db.getReadableDatabase(); ArrayList<SubItemDataModel> res = new ArrayList<>(); String itemId = ""; // String qury = "SELECT * FROM TempOrderDetails WHERE OrderID"; String qury = "SELECT * FROM TempOrderDetails WHERE OrderID ="+OrderId; //ORDER ID CHECKED ON 10/04 BCZ THE SAME ITEMS WHICH ARE ADDED TO CART ARE GETTING FOR ALL THE RETAILERS AS THOSE RETAILERS HAVE THOSE ITEMS Cursor c = db.rawQuery(qury, null); if (c.getCount() > 0) { c.moveToFirst(); do { /* (String offer, String discount_type, float bottle_price, float case_value, int item_id, String sub_item_name, String offer_tagline, String total_price, String no_of_free_case, String no_of_free_bottle, String product_image_path, float item_total, String cases, String bottles)*/ /* itemId = c.getString(c.getColumnIndexOrThrow("ItemID"));*/ res.add(new SubItemDataModel("", "", 0.f, 0.f, c.getInt(c.getColumnIndexOrThrow("ItemID")), c.getString(c.getColumnIndexOrThrow("item_Name")), "", c.getString(c.getColumnIndexOrThrow("Amount")), c.getString(c.getColumnIndexOrThrow("FreeLargeUnitQty")), c.getString(c.getColumnIndexOrThrow("FreeSmallUnitQty")), null, 0.f, c.getString(c.getColumnIndexOrThrow("LargeUnit")), c.getString(c.getColumnIndexOrThrow("SmallUnit")))); MyApplication.logi(LOG_TAG, "resss isssssss------------>" + res); } while (c.moveToNext()); } if (c != null) { c.close(); } MyApplication.logi(LOG_TAG, "resppppp of getListOfAlreadySavedToCartItems----> " + res); return res; } public static void deleteAllRecords(String orderId) { MyApplication.logi(LOG_TAG, "deleteAllRecords for orderdetails"); SQLiteDatabase db = MyApplication.db.getWritableDatabase(); int ret = db.delete(NAME, "OrderID =?", new String[]{orderId}); if (ret > 0) { MyApplication.logi(LOG_TAG, "orderdetails DELETED SUCCESSFULLY" + ret); } else { MyApplication.logi(LOG_TAG, "orderdetails DELETED UNSUCCESSFULLY" + ret); } } public static int countOfAddToCardItems(String OrderID) { MyApplication.logi(LOG_TAG, "IN count countOfAddToCardItems"); String query = ""; int resp = 0; SQLiteDatabase db = MyApplication.db.getWritableDatabase(); query = "SELECT COUNT(ID) as count FROM TempOrderDetails where OrderID ="+OrderID; MyApplication.logi(LOG_TAG, "IN count countOfAddToCardItems query--->"+query+"OrderID-->"+OrderID); Cursor c = db.rawQuery(query, null); if (c.getCount() > 0) { c.moveToFirst(); do { resp = c.getInt(c.getColumnIndexOrThrow("count")); MyApplication.logi(LOG_TAG, "IN count countOfAddToCardItems resp-->>"+resp); } while (c.moveToNext()); } return resp; } public static boolean istrue(String orderId) { MyApplication.logi(LOG_TAG, "in istrue"); int count; boolean resp =false ; MyApplication.logi(LOG_TAG, "in istrue()" + orderId); SQLiteDatabase db = MyApplication.db.getWritableDatabase(); //String query = "SELECT * from "+NAME+" where "+"PriceListID" +" =" + dist_id+""; // String query = "SELECT DISTINCT SalesRate from PriceListDetails where ItemID =" + item_id; // String query = "select SalesRate from PriceListDetails where ItemID=item_id and PriceListID=dist_id"; String query = "select * from TempOrderDetails where TempOrderDetails.OrderID = 'orderId'and (TempOrderDetails.LargeUnit > 0 or TempOrderDetails.SmallUnit > 0)"; MyApplication.logi("", "In getSalesRate query :" + query); Cursor c = db.rawQuery(query, null); count = c.getCount(); MyApplication.logi(LOG_TAG, "COUNT OF istrue IS-->" + count); if (count > 0) { resp= true; // c.moveToFirst(); /*do { try { resp = Integer.parseInt(c.getString(c.getColumnIndexOrThrow("SalesRate"))); } catch (NumberFormatException e) { e.printStackTrace(); } MyApplication.logi(LOG_TAG, "RESPPPPP-->" + resp); } while (c.moveToNext());*/ } else{ resp=false; } return resp; } public static void delete_table() { SQLiteDatabase db = MyApplication.db.getWritableDatabase(); String str1 = "select * from " + NAME; Cursor c = db.rawQuery(str1, null); int count= c.getCount(); MyApplication.logi(LOG_TAG, "Count"+count); int numRows = db.delete(NAME, null, null); MyApplication.logi(LOG_TAG, "In delete_tbl_timetable_sync"); MyApplication.logi(LOG_TAG, "DeletedRows:->" + numRows); } }
package com.mpowa.android.powapos.apps.powatools.util; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.mpowa.android.powapos.apps.powatools.R; import java.util.ArrayList; /** * Created by Powa on 7/23/15. */ public class CustomSpinnerAdapter extends ArrayAdapter<String> { private Activity context; ArrayList<String> firmwares; public CustomSpinnerAdapter(Activity context, int resource, ArrayList<String> firmwares) { super(context, resource, firmwares); this.context = context; this.firmwares = firmwares; } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; if (row == null) { LayoutInflater inflater = context.getLayoutInflater(); row = inflater.inflate(R.layout.spinner_row_nothing_selected, parent, false); } String current = firmwares.get(position); TextView name = (TextView) row.findViewById(R.id.text_firmware); name.setText(current); return row; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { View row = convertView; if (row == null) { LayoutInflater inflater = context.getLayoutInflater(); row = inflater.inflate(R.layout.spinner_row_nothing_selected, parent, false); } String current = firmwares.get(position); TextView name = (TextView) row.findViewById(R.id.text_firmware); name.setText(current); return row; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.aot; import java.io.ByteArrayOutputStream; import java.io.IOException; import org.junit.jupiter.api.Test; import org.springframework.aot.generate.GeneratedFiles.Kind; import org.springframework.aot.generate.InMemoryGeneratedFiles; import org.springframework.aot.hint.MemberCategory; import org.springframework.aot.hint.TypeReference; import org.springframework.aot.hint.predicate.RuntimeHintsPredicates; import org.springframework.aot.test.generate.TestGenerationContext; import org.springframework.core.io.InputStreamSource; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link CglibClassHandler}. * * @author Stephane Nicoll */ class CglibClassHandlerTests { private static final byte[] TEST_CONTENT = new byte[] { 'a' }; private final TestGenerationContext generationContext; private final CglibClassHandler handler; public CglibClassHandlerTests() { this.generationContext = new TestGenerationContext(); this.handler = new CglibClassHandler(this.generationContext); } @Test void handlerGeneratedClassCreatesRuntimeHintsForProxy() { String className = "com.example.Test$$SpringCGLIB$$0"; this.handler.handleGeneratedClass(className, TEST_CONTENT); assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of(className)) .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)) .accepts(this.generationContext.getRuntimeHints()); } @Test void handlerLoadedClassCreatesRuntimeHintsForProxy() { this.handler.handleLoadedClass(CglibClassHandler.class); assertThat(RuntimeHintsPredicates.reflection().onType(CglibClassHandler.class) .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)) .accepts(this.generationContext.getRuntimeHints()); } @Test void handlerRegisterGeneratedClass() throws IOException { String className = "com.example.Test$$SpringCGLIB$$0"; this.handler.handleGeneratedClass(className, TEST_CONTENT); InMemoryGeneratedFiles generatedFiles = this.generationContext.getGeneratedFiles(); assertThat(generatedFiles.getGeneratedFiles(Kind.SOURCE)).isEmpty(); assertThat(generatedFiles.getGeneratedFiles(Kind.RESOURCE)).isEmpty(); String expectedPath = "com/example/Test$$SpringCGLIB$$0.class"; assertThat(generatedFiles.getGeneratedFiles(Kind.CLASS)).containsOnlyKeys(expectedPath); assertContent(generatedFiles.getGeneratedFiles(Kind.CLASS).get(expectedPath), TEST_CONTENT); } private void assertContent(InputStreamSource source, byte[] expectedContent) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); source.getInputStream().transferTo(out); assertThat(out.toByteArray()).isEqualTo(expectedContent); } }
package com.ctse.automatedbirthdaywisher; import android.app.DialogFragment; import android.app.TimePickerDialog; import android.content.Intent; import android.database.Cursor; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.TimePicker; import java.util.Calendar; import java.util.regex.Pattern; public class AddWishManuallyActivity extends AppCompatActivity { private static final String TAG = "AddWishManuallyActivity"; private static int RESULT_LOAD_IMAGE = 1; ImageView imageView; TextView setDateTv, setTimeTv; EditText nameTv, numbertv, msgEt; Button browse, save; String name, number, time, date, msg; byte[] img; Process process; MyDBHelper dbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_wish_manually); this.setTitle(getString(R.string.add_wish)); imageView = (ImageView) findViewById(R.id.imageView3); nameTv = (EditText) findViewById(R.id.editText); numbertv = (EditText) findViewById(R.id.editText2); setDateTv = (TextView) findViewById(R.id.textView15); setTimeTv = (TextView) findViewById(R.id.textView16); msgEt = (EditText) findViewById(R.id.textView9); browse = (Button) findViewById(R.id.button2); save = (Button) findViewById(R.id.button); process = new Process(); dbHelper = new MyDBHelper(this); //open gallery browse.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, RESULT_LOAD_IMAGE); } }); //set time setTimeTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar mcurrentTime = Calendar.getInstance(); int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY); int minute = mcurrentTime.get(Calendar.MINUTE); TimePickerDialog mTimePicker; mTimePicker = new TimePickerDialog(AddWishManuallyActivity.this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) { setTimeTv.setText(selectedHour + ":" + selectedMinute); } }, hour, minute, true); mTimePicker.setTitle(R.string.set_time); mTimePicker.show(); } }); //set date setDateTv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogFragment newFragment = new DatePickerFragment(); Bundle args = new Bundle(); args.putInt("textField", R.id.textView15); newFragment.setArguments(args); newFragment.show(getFragmentManager(), "Date Picker"); } }); //save save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { name = nameTv.getText().toString(); number = numbertv.getText().toString(); time = setTimeTv.getText().toString(); date = setDateTv.getText().toString(); msg = msgEt.getText().toString(); img = process.drawableTobyte(imageView.getDrawable()); if (name != null && number != null && msg != null && !msg.isEmpty() && !name.isEmpty() && !number.isEmpty()) { if (process.isValidMobile(number) && Pattern.matches("[0-9:]*", time) && Pattern.matches("[0-9\\/]*", date)) { if (date.substring(5).equals(process.getSystemDate())) { dbHelper.insertWish(number, time, date, msg, name, img, 1); } else { dbHelper.insertWish(number, time, date, msg, name, img, 0); } Snackbar.make(v, R.string.data_added, Snackbar.LENGTH_LONG).show(); boolean sent = process.sentMessage(getApplicationContext(), date, name, number, msg); if (sent) { Snackbar.make(v, "Your wish sent to " + name, Snackbar.LENGTH_LONG).show(); } Log.d(TAG, "data added"); AddWishManuallyActivity.super.onBackPressed(); } else { Snackbar.make(v, R.string.invalid_data_formats, Snackbar.LENGTH_LONG).show(); Log.d(TAG, "data not added,invalid data formats"); } } else { Snackbar.make(v, R.string.data_not_added, Snackbar.LENGTH_LONG).show(); Log.d(TAG, "data not added,empty fields"); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //choose image from gallery if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) { Uri selectedImage = data.getData(); String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); cursor.close(); imageView.setImageBitmap(process.getRoundedShape(BitmapFactory.decodeFile(picturePath))); } } }
/** * Project Name:market * File Name:ProviderMysqlImpl.java * Package Name:com.market.mysql.impl * Date:2020年4月29日下午3:22:01 * Copyright (c) 2020, 277809183@qq.com All Rights Reserved. * */ /** * Project Name:market * File Name:ProviderMysqlImpl.java * Package Name:com.market.mysql.impl * Date:2020年4月29日下午3:22:01 * Copyright (c) 2020, 837806955@qq.com All Rights Reserved. * */ package com.market.mysql.impl; /** * ClassName:ProviderMysqlImpl <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON. <br/> * Date: 2020年4月29日 下午3:22:01 <br/> * @author Future * @version * @since JDK 1.8 * @see */ import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.market.entity.Provider; import com.market.mysql.BaseMysql; import com.market.mysql.ProviderMysql; /** * ClassName: ProviderMysqlImpl <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON(可选). <br/> * * date: 2020年4月29日 下午3:22:01 <br/> * * @author Li Zhengyu * @version * @since JDK 1.8 */ public class ProviderMysqlImpl extends BaseMysql implements ProviderMysql { public List<Provider> queryAll() { List<Provider> providers = new ArrayList<Provider>(); Provider provider = null; String sql = "select * from suppinfo"; Object[] params = {}; rs = this.executeQuery(sql, params); try { while (rs.next()) { String sname = rs.getString("sname"); String scast = rs.getString("scast"); String sid = rs.getString("sid"); String sadmin = rs.getString("sadmin"); String sphone = rs.getString("sphone"); String sinfo = rs.getString("sinfo"); String saddress = rs.getString("saddress"); provider = new Provider(sid, sname, sadmin, sphone, saddress, scast, sinfo); providers.add(provider); } } catch (SQLException e) { e.printStackTrace(); } finally { this.closeResource(rs, pstmt, conn); } return providers; } public List<Provider> search(String sname) { List<Provider> providers = new ArrayList<Provider>(); Provider provider = null; String sql = "select * from suppinfo where sname=?"; Object[] params = { sname }; rs = this.executeQuery(sql, params); try { while (rs.next()) { String name = rs.getString("sname"); String scast = rs.getString("scast"); String sid = rs.getString("sid"); String sadmin = rs.getString("sadmin"); String sphone = rs.getString("sphone"); String sinfo = rs.getString("sinfo"); String saddress = rs.getString("saddress"); provider = new Provider(sid, name, sadmin, sphone, saddress, scast, sinfo); providers.add(provider); } } catch (SQLException e) { e.printStackTrace(); } finally { this.closeResource(rs, pstmt, conn);// �ر���Դ } return providers; } @Override public boolean register(Provider provider) { boolean flag = false; try { String sql = "insert into suppinfo values(?,?,?,?,?,?,?)"; Object[] params = { provider.getSid(), provider.getSname(), provider.getSadmin(), provider.getSphone(), provider.getSaddress(), provider.getScast(), provider.getSinfo() }; result = this.executeUpdate(sql, params); if (result != 0) { flag = true; } } catch (Exception e) { e.printStackTrace(); } finally { this.closeResource(null, pstmt, conn); } return flag; } public boolean delete(String name) { boolean flag = false; try { String sql = "delete from suppinfo where sname=?"; Object[] params = { name }; result = this.executeUpdate(sql, params); if (result != 0) { flag = true; } } catch (Exception e) { e.printStackTrace(); } finally { this.closeResource(null, pstmt, conn); } return flag; } public boolean change(String id, String phone, String address) { boolean flag = false; try { String sql = "UPDATE suppinfo SET sphone=?,saddress=? where sid=?"; Object[] params = { phone, address, id }; result = this.executeUpdate(sql, params); if (result != 0) { flag = true; } } catch (Exception e) { e.printStackTrace(); } finally { this.closeResource(null, pstmt, conn); } return flag; } }
package pojo; import io.restassured.RestAssured; import static io.restassured.RestAssured.*; import java.util.ArrayList; import java.util.List; import org.testng.annotations.Test; public class GoogleMapTest { @Test public void AddGoogleMap() { Googlemap_pojo map=new Googlemap_pojo(); LocationClass loc=new LocationClass(); loc.setLat(-38.383494); loc.setLat(33.427362); map.setLocation(loc); map.setAccuracy(50); map.setName("Frontline house"); map.setPhone_number("(+91) 983 893 3937"); map.setAddress("29, side layout, cohen 09"); List<String> str=new ArrayList<String>(); str.add("shoe park"); str.add("shop"); map.setTypes(str); map.setWebsite("http://google.com"); map.setLanguage("French-IN"); RestAssured.baseURI="https://rahulshettyacademy.com"; String res=given().queryParam("key", "qaclick123").body(map) .when().post("/maps/api/place/add/json"). then().assertThat().statusCode(200) .extract().response().asString(); System.out.println(res); } }
package com.nematjon.edd_client_season_two.receivers; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.util.Log; import com.google.android.gms.location.Geofence; import com.google.android.gms.location.GeofencingEvent; import com.nematjon.edd_client_season_two.DbMgr; import java.util.List; public class GeofenceRcvr extends BroadcastReceiver { private static final String TAG = "GeofenceReceiver"; @Override public void onReceive(Context context, Intent intent) { SharedPreferences confPrefs = context.getSharedPreferences("Configurations", Context.MODE_PRIVATE); PendingResult pendingIntent = goAsync(); Task asyncTask = new Task(pendingIntent, intent, confPrefs); asyncTask.execute(); } private static class Task extends AsyncTask<String, Integer, String> { private final PendingResult pendingResult; private final Intent intent; private final SharedPreferences confPrefs; boolean entered = false; private Task(PendingResult pendingResult, Intent intent, SharedPreferences confPrefs) { this.pendingResult = pendingResult; this.intent = intent; this.confPrefs = confPrefs; } @Override protected String doInBackground(String... string) { GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent); if (geofencingEvent.hasError()) { String error = String.valueOf(geofencingEvent.getErrorCode()); Log.e(TAG, "Error code: " + error); return "Error: " + error; } // Get the transition type. int geofenceTransition = geofencingEvent.getGeofenceTransition(); List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences(); int dataSourceId = confPrefs.getInt("GEOFENCE", -1); assert dataSourceId != -1; if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) { entered = true; long nowTime = System.currentTimeMillis(); for (Geofence geofence : triggeringGeofences) DbMgr.saveMixedData(dataSourceId, nowTime, 1.0f, nowTime, geofence.getRequestId(), "ENTER"); } else if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) { long nowTime = System.currentTimeMillis(); for (Geofence geofence : triggeringGeofences) { DbMgr.saveMixedData(dataSourceId, nowTime, 1.0f, nowTime, geofence.getRequestId(), "EXIT"); } } return "Success"; } @Override protected void onPostExecute(String s) { super.onPostExecute(s); // Must call finish() so the BroadcastReceiver can be recycled. Log.e(TAG, "Geofence result: " + s); // sendNotification(s, entered); pendingResult.finish(); } } }
package com.natsu.threaddemo.threadZExample; public class ThreadExample { public static void main(String[] args) { test02(); } public static void test01() { ThreadPool pool = new ThreadPool(); for (int i = 0; i < 5; i++) { Runnable task = new Runnable() { @Override public void run() { System.out.println(" execute "); } }; pool.add(task); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } /** * 每个任务执行时间都是1s, 刚开始时间是 */ public static void test02(){ ThreadPool pool= new ThreadPool(); int sleep=1000; while(true){ pool.add(new Runnable(){ @Override public void run() { //System.out.println("执行任务"); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); try { Thread.sleep(sleep); sleep = sleep>100?sleep-100:sleep; } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
/* * 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 com.koshish.java.hibernate.ecommerce.DAO.Model; import java.io.Serializable; import java.util.Date; import java.util.List; /** * * @author Koshish Rijal */ public class PurchaseInfo implements Serializable{ private int purchaseId; private Date purchaseDate; private int totalPrice; private int totalDiscount; private int totalProfit; public PurchaseInfo() { } public PurchaseInfo(int purchaseId, Date purchaseDate) { this.purchaseId = purchaseId; this.purchaseDate = purchaseDate; } public int getPurchaseId() { return purchaseId; } public void setPurchaseId(int purchaseId) { this.purchaseId = purchaseId; } public Date getPurchaseDate() { return purchaseDate; } public void setPurchaseDate(Date purchaseDate) { this.purchaseDate = purchaseDate; } public int getTotalPrice() { return totalPrice; } public void setTotalPriceDiscountAndProfit(List<ProductInfo> productInfoList) { totalPrice=0; totalDiscount=0; for( ProductInfo productInfo:productInfoList){ totalPrice+=productInfo.getSellPrice(); totalDiscount+=productInfo.getDiscount(); totalProfit+=productInfo.getProfit(); } } public int getTotalDiscount() { return totalDiscount; } public int getTotalProfit() { return totalProfit; } @Override public String toString() { return "PurchaseInfo{" + "purchaseId=" + purchaseId + ", purchaseDate=" + purchaseDate + ", totalPrice=" + totalPrice + ", totalDiscount=" + totalDiscount + '}'; } }
/* * 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 Testing.JWebUnitTesting; import static net.sourceforge.jwebunit.junit.JWebUnit.*; import net.sourceforge.jwebunit.util.TestingEngineRegistry; import org.junit.*; /** * * @author User */ public class RecipeSearchTest { @Before public void prepare() { setTestingEngineKey(TestingEngineRegistry.TESTING_ENGINE_HTMLUNIT); // use HtmlUnit setBaseUrl("http://www.kitchenhuntr.com"); } @Test public void testContent() { beginAt("recipe_search.jsp"); // start at recipe_search.jsp assertTitleEquals("Kitchen Hunt - Search"); // the page should be titled "Kitchen Hunt - Search" } public static void main(String[] args) { RecipeSearchTest test = new RecipeSearchTest(); test.prepare(); test.testContent(); } }
package com.example.aizat.homework2; import android.app.Fragment; import android.widget.Button; public class HomeActivity extends FragmentHostActivity { protected Fragment getFragment () { return HomeFragment.newInstance(); } }
package tutorial03_cssselector; import static org.assertj.core.api.Assertions.assertThat; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; //www.softwaretestinghelp.com/css-selector-selenium-locator-selenium-tutorial-6/ public class Tutorial03Test { static WebDriver driver; @BeforeClass public static void setup(){ driver = new FirefoxDriver(); } @AfterClass public static void cleanup(){ driver.close(); driver.quit(); } @Test public void testLocateByCSS_Id(){ driver.get("http://accounts.google.com"); new WebDriverWait(driver, 10).until(ExpectedConditions.titleContains("Sign in")); // Find Web Element by cssSelector id WebElement txtEmail = driver.findElement(By.cssSelector("input#Email")); // Verifications assertThat(txtEmail).isNotNull(); assertThat(txtEmail.getAttribute("name")).isEqualTo("Email"); assertThat(txtEmail.getAttribute("placeholder")).isEqualTo("Enter your email"); assertThat(txtEmail.getTagName()).isEqualTo("input"); // Type some text into Email txtEmail.sendKeys("SampleEmailLogin"); // Verification assertThat(txtEmail.getAttribute("value")).isEqualTo("SampleEmailLogin"); } @Test public void testLocateByCSS_Class(){ driver.get("http://accounts.google.com"); new WebDriverWait(driver, 10).until(ExpectedConditions.titleContains("Sign in")); // Find Web Element by cssSelector: class WebElement lblOneGoogleAccount = driver.findElement(By.cssSelector("p.tagline")); // Verifications: assertThat(lblOneGoogleAccount).isNotNull(); assertThat(lblOneGoogleAccount.getText()).isEqualTo("One Google Account for everything Google"); } @Test public void testLocateByCSS_Attributes(){ driver.get("http://accounts.google.com"); new WebDriverWait(driver, 10).until(ExpectedConditions.titleContains("Sign in")); // Find Web Element by cssSelector: attributes WebElement btnNext = driver.findElement(By.cssSelector("input[type='submit'][value='Next']")); // Verifications: assertThat(btnNext).isNotNull(); assertThat(btnNext.getTagName()).isEqualTo("input"); assertThat(btnNext.getAttribute("type")).isEqualTo("submit"); } @Test public void testLocateByCSS_Id_Attributes(){ driver.get("http://accounts.google.com"); new WebDriverWait(driver, 10).until(ExpectedConditions.titleContains("Sign in")); // Find Web Element by cssSelector id + attribute WebElement txtEmail = driver.findElement(By.cssSelector("input#Email[placeholder='Enter your email']")); // Verifications assertThat(txtEmail).isNotNull(); assertThat(txtEmail.getAttribute("name")).isEqualTo("Email"); assertThat(txtEmail.getAttribute("placeholder")).isEqualTo("Enter your email"); assertThat(txtEmail.getTagName()).isEqualTo("input"); // Type some text into Email txtEmail.sendKeys("LocateByIDAndAttribute"); // Verification assertThat(txtEmail.getAttribute("value")).isEqualTo("LocateByIDAndAttribute"); } @Test public void testLocateByCSS_Class_Attributes(){ driver.get("http://accounts.google.com"); new WebDriverWait(driver, 10).until(ExpectedConditions.titleContains("Sign in")); // Find Web Element by cssSelector class + attribute WebElement btnNext = driver.findElement(By.cssSelector("input.rc-button-submit[type='submit'][value='Next']")); // Verifications: assertThat(btnNext).isNotNull(); assertThat(btnNext.getTagName()).isEqualTo("input"); assertThat(btnNext.getAttribute("type")).isEqualTo("submit"); } @Test public void testLocateByCSS_Attribute_Substring(){ driver.get("http://accounts.google.com"); new WebDriverWait(driver, 10).until(ExpectedConditions.titleContains("Sign in")); // Find Web Element by cssSelector: Attribute Prefix Match WebElement txtEmail = driver.findElement(By.cssSelector("input[name^='Ema']")); // Verifications assertThat(txtEmail).isNotNull(); assertThat(txtEmail.getAttribute("name")).isEqualTo("Email"); assertThat(txtEmail.getAttribute("placeholder")).isEqualTo("Enter your email"); assertThat(txtEmail.getTagName()).isEqualTo("input"); // Find Web Element by cssSelector: Attribute Suffix Match txtEmail = null; txtEmail = driver.findElement(By.cssSelector("input[placeholder$=' email']")); // Verifications assertThat(txtEmail).isNotNull(); assertThat(txtEmail.getAttribute("name")).isEqualTo("Email"); assertThat(txtEmail.getAttribute("placeholder")).isEqualTo("Enter your email"); assertThat(txtEmail.getTagName()).isEqualTo("input"); // Find Web Element by cssSelector: Attribute Substring Match txtEmail = null; txtEmail = driver.findElement(By.cssSelector("input[placeholder*=' your ']")); // Verifications assertThat(txtEmail).isNotNull(); assertThat(txtEmail.getAttribute("name")).isEqualTo("Email"); assertThat(txtEmail.getAttribute("placeholder")).isEqualTo("Enter your email"); assertThat(txtEmail.getTagName()).isEqualTo("input"); } }
package ca.oneroof.oneroof.ui.purchase; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.EditText; import android.widget.ListView; import androidx.annotation.NonNull; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.Navigation; import java.util.ArrayList; import ca.oneroof.oneroof.R; import ca.oneroof.oneroof.api.Division; import ca.oneroof.oneroof.api.Purchase; import ca.oneroof.oneroof.databinding.FragmentAddPurchaseBinding; import ca.oneroof.oneroof.viewmodel.HouseViewModel; /** * A simple {@link Fragment} subclass. * Use the {@link AddPurchaseFragment#newInstance} factory method to * create an instance of this fragment. */ public class AddPurchaseFragment extends Fragment { public MutableLiveData<Integer> totalAmount = new MutableLiveData<>(0); private HouseViewModel viewmodel; private EditText memoText; private ArrayList<DivisionEdit> divisions = new ArrayList<>(); private DivisionEditAdapter divisionEditAdapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); viewmodel = new ViewModelProvider(getActivity()).get(HouseViewModel.class); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); FragmentAddPurchaseBinding binding = DataBindingUtil.inflate(inflater, R.layout.fragment_add_purchase, container, false); binding.setViewmodel(viewmodel); binding.setFragment(this); binding.setLifecycleOwner(this); setHasOptionsMenu(true); View view = binding.getRoot(); memoText = view.findViewById(R.id.memo_text); DivisionEdit divEdit = new DivisionEdit( viewmodel.house.data.getValue().data.roommateNames, viewmodel.house.data.getValue().data.roommates); divEdit.roommateEnables.set(viewmodel.house.data.getValue().data.roommates.indexOf( viewmodel.roommateId.getValue() ), true); divisions.add(divEdit); ListView divisionList = view.findViewById(R.id.division_list); divisionEditAdapter = new DivisionEditAdapter(getContext(), R.layout.item_division_edit, divisions, totalAmount); divisionList.setAdapter(divisionEditAdapter); return view; } public void clickAddDivision(View v) { divisionEditAdapter.add(new DivisionEdit( viewmodel.house.data.getValue().data.roommateNames, viewmodel.house.data.getValue().data.roommates)); } public void clickSavePurchase() { InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(getView().getWindowToken(), 0); Purchase purchase = new Purchase(); purchase.memo = memoText.getText().toString(); purchase.purchaser = viewmodel.roommateId.getValue(); purchase.divisions = new ArrayList<>(); purchase.amount = totalAmount.getValue(); for (DivisionEdit edit : divisions) { Division division = new Division(); division.amount = edit.amount; division.roommates = new ArrayList<>(); for (int i = 0; i < edit.roommateEnables.size(); i++) { if (edit.roommateEnables.get(i)) { division.roommates.add(edit.roommates.get(i)); } } purchase.divisions.add(division); } viewmodel.postPurchase(purchase); Navigation.findNavController(getView()) .popBackStack(); } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.menu_add_purchase, menu); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.action_save_purchase) { clickSavePurchase(); return true; } return super.onOptionsItemSelected(item); } }
import.java.util*. class CaculaAreaCirculo{ public static void main (String []arg){ Scanner Lee = new Scanner(System.in); Circulo circulito = new Circulo();
package com.example.szupek.datepickerszupek.model; /** * Created by szupek on 2016-12-29. */ public class Wesele { private String data; private String miejscowosc; private String lokal; private String imie; private String nazwisko; private String uklon; private String godzinaUklonu; private String cena; private String wyjazd; private String tel_Mlody; private String tel_Mloda; private String notatki; public Wesele(){ } public Wesele(String data, String miejscowosc, String lokal, String imie, String nazwisko, String uklon, String godzinaUklonu, String cena, String wyjazd, String tel_Mlody, String tel_Mloda, String notatki){ this.data=data; this.miejscowosc=miejscowosc; this.lokal=lokal; this.imie=imie; this.nazwisko=nazwisko; this.uklon=uklon; this.godzinaUklonu=godzinaUklonu; this.cena=cena; this.wyjazd=wyjazd; this.tel_Mlody=tel_Mlody; this.tel_Mloda=tel_Mloda; this.notatki=notatki; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getMiejscowosc() { return miejscowosc; } public void setMiejscowosc(String miejscowosc) { this.miejscowosc = miejscowosc; } public String getLokal() { return lokal; } public void setLokal(String lokal) { this.lokal = lokal; } public String getImie() { return imie; } public void setImie(String imie) { this.imie = imie; } public String getNazwisko() { return nazwisko; } public void setNazwisko(String nazwisko) { this.nazwisko = nazwisko; } public String getUklon() { return uklon; } public void setUklon(String uklon) { this.uklon = uklon; } public String getGodzinaUklonu() { return godzinaUklonu; } public void setGodzinaUklonu(String godzinaUklonu) { this.godzinaUklonu = godzinaUklonu; } public String getCena() { return cena; } public void setCena(String cena) { this.cena = cena; } public String getWyjazd() { return wyjazd; } public void setWyjazd(String wyjazd) { this.wyjazd = wyjazd; } public String getTel_Mlody() { return tel_Mlody; } public void setTel_Mlody(String tel_Mlody) { this.tel_Mlody = tel_Mlody; } public String getTel_Mloda() { return tel_Mloda; } public void setTel_Mloda(String tel_Mloda) { this.tel_Mloda = tel_Mloda; } public String getNotatki() { return notatki; } public void setNotatki(String notatki) { this.notatki = notatki; } }
package ar.edu.utn.d2s.model.config; public class PointOfInterestConfig { /** * This is a simulation of a NoSql Database, which we would have used for * saving static data such as close range for different points of interest */ public static final double POI_CLOSE_RANGE = 0.5; public static final double BUS_CLOSE_RANGE = 0.1; public static final int BANKS_START_HOURS = 10; public static final int BANKS_START_MINUTES = 0; public static final int BANKS_END_HOURS = 15; public static final int BANKS_END_MINUTES = 0; }
/* * Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.saml.idp; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import pl.edu.icm.unity.saml.SamlProperties; import pl.edu.icm.unity.stdext.identity.IdentifierIdentity; import pl.edu.icm.unity.stdext.identity.PersistentIdentity; import pl.edu.icm.unity.stdext.identity.TargetedPersistentIdentity; import pl.edu.icm.unity.stdext.identity.TransientIdentity; import pl.edu.icm.unity.stdext.identity.UsernameIdentity; import pl.edu.icm.unity.stdext.identity.X500Identity; import eu.unicore.samly2.SAMLConstants; import eu.unicore.samly2.exceptions.SAMLRequesterException; /** * Maps SAML identity to the Unity identity. In the first place the configuration is used, * as a fallback the hardcoded defaults. * @author K. Benedyczak */ public class IdentityTypeMapper { private Map<String, String> configuredMappings; private static final Map<String, String> DEFAULTS; static { DEFAULTS = new HashMap<String, String>(); DEFAULTS.put(SAMLConstants.NFORMAT_PERSISTENT, TargetedPersistentIdentity.ID); DEFAULTS.put(SAMLConstants.NFORMAT_UNSPEC, TargetedPersistentIdentity.ID); DEFAULTS.put(SAMLConstants.NFORMAT_DN, X500Identity.ID); DEFAULTS.put(SAMLConstants.NFORMAT_TRANSIENT, TransientIdentity.ID); DEFAULTS.put("unity:persistent", PersistentIdentity.ID); DEFAULTS.put("unity:identifier", IdentifierIdentity.ID); DEFAULTS.put("unity:userName", UsernameIdentity.ID); } public IdentityTypeMapper(SamlProperties config) { Set<String> keys = config.getStructuredListKeys(SamlProperties.IDENTITY_MAPPING_PFX); configuredMappings = new HashMap<String, String>(keys.size()); configuredMappings.putAll(DEFAULTS); for (String key: keys) { String localId = config.getValue(key+SamlProperties.IDENTITY_LOCAL); String samlId = config.getValue(key+SamlProperties.IDENTITY_SAML); if (localId.trim().equals("")) configuredMappings.remove(samlId); else configuredMappings.put(samlId, localId); } } /** * @param samlIdentity * @return Unity identity type of the SMAL identity * @throws SAMLRequesterException if the requested type has no mapping */ public String mapIdentity(String samlIdentity) throws SAMLRequesterException { String ret = configuredMappings.get(samlIdentity); if (ret != null) return ret; throw new SAMLRequesterException(SAMLConstants.SubStatus.STATUS2_INVALID_NAMEID_POLICY, samlIdentity + " is not supported by this service."); } public Set<String> getSupportedIdentityTypes() { return new HashSet<String>(configuredMappings.keySet()); } }
package com.raymon.provider.dao.user; import java.util.List; import java.util.Map; import com.raymon.api.pojo.user.URolePermissionPojo; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Component; @Component @Mapper public interface URolePermissionMapper { int insert(URolePermissionPojo record); int insertSelective(URolePermissionPojo record); List<URolePermissionPojo> findRolePermissionByPid(Long id); List<URolePermissionPojo> findRolePermissionByRid(Long id); List<URolePermissionPojo> find(URolePermissionPojo entity); int deleteByPid(Long id); int deleteByRid(Long id); int delete(URolePermissionPojo entity); int deleteByRids(Map<String, Object> resultMap); }
package com.jhc.servlet; import com.jhc.dao.*; import com.jhc.entity.Content; import com.jhc.entity.Interface; import com.jhc.entity.Result; import com.jhc.entity.User; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.util.ArrayList; import java.util.List; @WebServlet(name = "Submit", value = "/Submit") public class SubmitServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String highlight_text = request.getParameter("highlight_text"); int cost = Integer.parseInt(request.getParameter("cost")); HttpSession session = request.getSession(); User user = (User)session.getAttribute("user"); Interface inter = (Interface)session.getAttribute("inter"); Integer contentIndex = (Integer) session.getAttribute("contentIndex"); // Content content = (Content)session.getAttribute("content"); List<Content> contents = (ArrayList<Content>)session.getAttribute("contents"); Content content = contents.get(contentIndex); String username = user.getUsername(); // //监督实验:取得实际界面inter // Interface inter = new Interface(); // int interfaceIdExp = interExp.getInterfaceId(); // int interOffsetExp = interExp.getOffset(); // if(interfaceIdExp == 16){ // InterfaceDao id = new InterfaceDaoImpl(); // inter = ((InterfaceDaoImpl) id).getExpInterface(username,interOffsetExp); // }else{ // inter = interExp; // } int InterfaceId = inter.getInterfaceId(); String contentId = content.getContentId(); String result = request.getParameter("result"); Result res = new Result(); res.setUsername(username); res.setContentId(contentId); res.setInterfaceId(InterfaceId); res.setResult(result); res.setHighlight_text(highlight_text); res.setCost(cost); ResultDao rd = new ResultDaoImpl(); if(rd.submit(res)){ // request.getRequestDispatcher("/GetContent").forward(request, response); //将页面索引置为下一页 session.setAttribute("contentIndex",contentIndex + 1); response.sendRedirect("/Labeling/GetContent"); }else{ session.setAttribute("errorInfo","提交失败,请重试"); request.getRequestDispatcher("/error.jsp").forward(request, response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
<<<<<<< HEAD /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package prgitejemplo; /** * * @author bertoa */ //Aņado esta linea en la rama testing public class GitAux { public void metodoAlumno1(){ System.out.println(" modificado por alum 1"); // insertado por alum1 } public void metodoAlumno2(){ // Modificado por SilvioMS System.out.println("metodo 2"); } public void metodoComunitario(){ System.out.println("alumno2 escribimos todos"); //modificacaciones alumno1 System.out.println("Alumno1 inserta esta sentencia "); // Modicaciones alumno2 System.out.println("Alumno2 inserta esta sentencia"); } public void testGitAux(){ // metodo rama testing System.out.println("Metodo de testing"); } //Aņado esta linea con un comentario } >>>>>>> e9cb4e320c7f6cbebf5ca9a21e53a1e5e1e9992e
import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JScrollPane; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JScrollBar; public class Scores extends JFrame{ private Window window=new Window("Scores",600,440); public Scores(){ /*JFrame frame =new JFrame("Scores"); frame.setVisible(true); frame.setResizable(false); frame.getContentPane().setBackground(new Color(255, 153, 0)); frame.setMaximumSize(new Dimension(600, 440)); frame.setMinimumSize(new Dimension(600, 440));*/ window.getFrame().setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); //frame.setLocationRelativeTo(null); //frame.getContentPane().setLayout(null); JLabel lblNewLabel = new JLabel("Scores"); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel.setFont(new Font("Verdana", Font.PLAIN, 20)); lblNewLabel.setBounds(205, 11, 212, 45); window.getFrame().getContentPane().add(lblNewLabel); JPanel panel = new JPanel(); panel.setBackground(new Color(204, 204, 255)); panel.setForeground(new Color(102, 153, 204)); panel.setBounds(10, 66, 574, 186); window.getFrame().getContentPane().add(panel); panel.setLayout(null); JLabel lblNewLabel_1 = new JLabel("Player Plakoto Portes Asodyo Fevga Total Points"); lblNewLabel_1.setFont(new Font("Verdana", Font.PLAIN, 13)); lblNewLabel_1.setBounds(10, 11, 570, 22); panel.add(lblNewLabel_1); JButton btnNewButton = new JButton("Go Back"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { window.getFrame().dispose(); new Menu(); } }); btnNewButton.setBackground(new Color(0, 102, 153)); btnNewButton.setForeground(new Color(255, 255, 204)); btnNewButton.setFont(new Font("Verdana", Font.PLAIN, 15)); btnNewButton.setBounds(230, 331, 144, 45); window.getFrame().getContentPane().add(btnNewButton); window.getFrame().setVisible(true); } }
package xtext; import com.google.common.base.Objects; import com.google.inject.Injector; import java.io.File; import java.net.URI; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Consumer; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.xtext.nodemodel.ICompositeNode; import org.eclipse.xtext.nodemodel.util.NodeModelUtils; import org.eclipse.xtext.resource.XtextResourceSet; import org.eclipse.xtext.validation.CheckMode; import org.eclipse.xtext.validation.IResourceValidator; import org.eclipse.xtext.validation.Issue; import org.eclipse.xtext.xbase.lib.CollectionLiterals; import org.eclipse.xtext.xbase.lib.Conversions; import org.eclipse.xtext.xbase.lib.Exceptions; import org.eclipse.xtext.xbase.lib.Functions.Function1; import org.eclipse.xtext.xbase.lib.InputOutput; import org.eclipse.xtext.xbase.lib.IterableExtensions; import org.eclipse.xtext.xbase.lib.ListExtensions; import xtext.AventuraGraficaStandaloneSetup; import xtext.aventuraGrafica.AbrirCerrar; import xtext.aventuraGrafica.Accion; import xtext.aventuraGrafica.Comandos; import xtext.aventuraGrafica.DescribirObjetos; import xtext.aventuraGrafica.EjecutarAccion; import xtext.aventuraGrafica.ElementosDelJuego; import xtext.aventuraGrafica.Entrar; import xtext.aventuraGrafica.Estado; import xtext.aventuraGrafica.Habitacion; import xtext.aventuraGrafica.Inicializacion; import xtext.aventuraGrafica.Juego; import xtext.aventuraGrafica.Jugador; import xtext.aventuraGrafica.ListarAcciones; import xtext.aventuraGrafica.ListarObjetosInventario; import xtext.aventuraGrafica.Model; import xtext.aventuraGrafica.Objeto; import xtext.aventuraGrafica.PreguntarObjetos; import xtext.aventuraGrafica.RecogerObjeto; import xtext.aventuraGrafica.Regla; import xtext.aventuraGrafica.impl.RecogibleImpl; /** * Interprete para Aventura Grafica */ @SuppressWarnings("all") public class AventuraGraficInterpreter { private Habitacion habitacionActual = null; private Jugador jugadorActual = null; public static void main(final String[] args) { boolean _isEmpty = ((List<String>)Conversions.doWrapArray(args)).isEmpty(); if (_isEmpty) { throw new RuntimeException( "Debe invocar este interprete con la ruta completa a un archivo como argumento!"); } final String fileName = args[0]; final Model model = AventuraGraficInterpreter.parsear(fileName); AventuraGraficInterpreter _aventuraGraficInterpreter = new AventuraGraficInterpreter(); _aventuraGraficInterpreter.interpret(model); } public static Model parsear(final String fileName) { try { AventuraGraficaStandaloneSetup _aventuraGraficaStandaloneSetup = new AventuraGraficaStandaloneSetup(); final Injector injector = _aventuraGraficaStandaloneSetup.createInjectorAndDoEMFRegistration(); final XtextResourceSet resourceSet = injector.<XtextResourceSet>getInstance(XtextResourceSet.class); File _file = new File(fileName); URI _uRI = _file.toURI(); String _string = _uRI.toString(); org.eclipse.emf.common.util.URI _createURI = org.eclipse.emf.common.util.URI.createURI(_string); final Resource resource = resourceSet.createResource(_createURI); resource.load(Collections.<Object, Object>unmodifiableMap(CollectionLiterals.<Object, Object>newHashMap())); AventuraGraficInterpreter.validate(injector, resource); EList<EObject> _contents = resource.getContents(); EObject _get = _contents.get(0); return ((Model) _get); } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } } public static void validate(final Injector injector, final Resource resource) { try { final IResourceValidator validator = injector.<IResourceValidator>getInstance(IResourceValidator.class); final List<Issue> issues = validator.validate(resource, CheckMode.ALL, null); boolean _isEmpty = issues.isEmpty(); boolean _not = (!_isEmpty); if (_not) { final Consumer<Issue> _function = new Consumer<Issue>() { @Override public void accept(final Issue it) { String _string = it.toString(); InputOutput.<String>println(_string); } }; issues.forEach(_function); System.exit((-1)); } } catch (Throwable _e) { throw Exceptions.sneakyThrow(_e); } } public void interpret(final Model model) { EList<Juego> _juegos = model.getJuegos(); final Consumer<Juego> _function = new Consumer<Juego>() { @Override public void accept(final Juego j) { AventuraGraficInterpreter.this.interpretarJuego(j); } }; _juegos.forEach(_function); } public void interpretarJuego(final Juego juego) { EList<Jugador> _jugador = juego.getJugador(); Jugador _get = _jugador.get(0); this.jugadorActual = _get; Inicializacion _inicializacion = juego.getInicializacion(); this.imprimirUbicacionInicio(_inicializacion); EList<Objeto> _objetos = juego.getObjetos(); final Consumer<Objeto> _function = new Consumer<Objeto>() { @Override public void accept(final Objeto s) { AventuraGraficInterpreter.this.imprimir(s); } }; _objetos.forEach(_function); EList<Habitacion> _habitaciones = juego.getHabitaciones(); final Consumer<Habitacion> _function_1 = new Consumer<Habitacion>() { @Override public void accept(final Habitacion s) { AventuraGraficInterpreter.this.imprimir(s); } }; _habitaciones.forEach(_function_1); EList<Comandos> _comandos = juego.getComandos(); final Consumer<Comandos> _function_2 = new Consumer<Comandos>() { @Override public void accept(final Comandos s) { ICompositeNode _findActualNodeFor = NodeModelUtils.findActualNodeFor(s); String _text = _findActualNodeFor.getText(); InputOutput.<String>println(_text); AventuraGraficInterpreter.this.exec(s); } }; _comandos.forEach(_function_2); } public void imprimirUbicacionInicio(final Inicializacion lugar) { Habitacion _donde = lugar.getDonde(); Regla _regla = _donde.getRegla(); String _mensaje = _regla.getMensaje(); InputOutput.<String>println(_mensaje); Habitacion _donde_1 = lugar.getDonde(); this.habitacionActual = _donde_1; } protected Object _imprimir(final Objeto obj) { return null; } protected Object _imprimir(final Habitacion hab) { return null; } protected Object _exec(final DescribirObjetos des) { Objeto _aObjeto = des.getAObjeto(); String _descripcion = _aObjeto.getDescripcion(); return InputOutput.<String>println(_descripcion); } protected Object _exec(final PreguntarObjetos pre) { String _xblockexpression = null; { EList<Objeto> aux = this.habitacionActual.getObjetos(); EList<Objeto> _inventario = this.jugadorActual.getInventario(); aux.removeAll(_inventario); final Function1<Objeto, String> _function = new Function1<Objeto, String>() { @Override public String apply(final Objeto it) { return it.getName(); } }; List<String> _map = ListExtensions.<Objeto, String>map(aux, _function); String _string = _map.toString(); String _plus = ("Hay: " + _string); _xblockexpression = InputOutput.<String>println(_plus); } return _xblockexpression; } protected Object _exec(final ListarObjetosInventario inv) { Jugador _aJugador = inv.getAJugador(); EList<Objeto> _inventario = _aJugador.getInventario(); final Function1<Objeto, String> _function = new Function1<Objeto, String>() { @Override public String apply(final Objeto it) { return it.getName(); } }; List<String> _map = ListExtensions.<Objeto, String>map(_inventario, _function); String _string = _map.toString(); return InputOutput.<String>println(_string); } protected Object _exec(final ListarAcciones listar) { Objeto _aObje = listar.getAObje(); EList<Accion> _acciones = _aObje.getAcciones(); final Function1<Accion, Boolean> _function = new Function1<Accion, Boolean>() { @Override public Boolean apply(final Accion accion) { return Boolean.valueOf(AventuraGraficInterpreter.this.chequearSiSeLista(accion)); } }; Iterable<Accion> _filter = IterableExtensions.<Accion>filter(_acciones, _function); final Function1<Accion, String> _function_1 = new Function1<Accion, String>() { @Override public String apply(final Accion it) { return it.getName(); } }; Iterable<String> _map = IterableExtensions.<Accion, String>map(_filter, _function_1); String _string = _map.toString(); String _plus = ("Se puede : " + _string); return InputOutput.<String>println(_plus); } public boolean chequearSiSeLista(final Accion accion) { Estado _estadodos = accion.getEstadodos(); String _valor = _estadodos.getValor(); String _valorActual = accion.getValorActual(); return Objects.equal(_valor, _valorActual); } protected Object _exec(final EjecutarAccion accionEjecutada) { Accion _accion = accionEjecutada.getAccion(); return this.chequearAccion(_accion); } protected Object _chequearAccion(final Entrar accionEntrar) { Habitacion _xblockexpression = null; { Habitacion _habitacion = accionEntrar.getHabitacion(); Regla _regla = _habitacion.getRegla(); String _mensaje = _regla.getMensaje(); InputOutput.<String>println(_mensaje); Habitacion _habitacion_1 = accionEntrar.getHabitacion(); _xblockexpression = this.habitacionActual = _habitacion_1; } return _xblockexpression; } protected Object _chequearAccion(final AbrirCerrar accionAbrir) { String _xifexpression = null; String _nuevoValor = accionAbrir.getNuevoValor(); Estado _estado = accionAbrir.getEstado(); String _valor = _estado.getValor(); boolean _equals = Objects.equal(_nuevoValor, _valor); if (_equals) { Estado _estado_1 = accionAbrir.getEstado(); String _plus = ("Accion no disponibe ya que el estado de la puerta ya es " + _estado_1); _xifexpression = InputOutput.<String>println(_plus); } else { Estado _estado_2 = accionAbrir.getEstado(); String _nuevoValor_1 = accionAbrir.getNuevoValor(); _estado_2.setValor(_nuevoValor_1); } return _xifexpression; } protected Object _exec(final RecogerObjeto recoger) { String _xifexpression = null; EList<Objeto> _inventario = this.jugadorActual.getInventario(); final Function1<Objeto, Boolean> _function = new Function1<Objeto, Boolean>() { @Override public Boolean apply(final Objeto inv) { Objeto _aObjeto = recoger.getAObjeto(); return Boolean.valueOf(Objects.equal(_aObjeto, inv)); } }; boolean _exists = IterableExtensions.<Objeto>exists(_inventario, _function); if (_exists) { Objeto _aObjeto = recoger.getAObjeto(); String _name = _aObjeto.getName(); String _plus = (_name + " ya pertenece a tu inventario"); _xifexpression = InputOutput.<String>println(_plus); } else { String _xifexpression_1 = null; Objeto _aObjeto_1 = recoger.getAObjeto(); boolean _esRecogible = this.esRecogible(_aObjeto_1); if (_esRecogible) { String _xblockexpression = null; { EList<Objeto> _inventario_1 = this.jugadorActual.getInventario(); Objeto _aObjeto_2 = recoger.getAObjeto(); _inventario_1.add(_aObjeto_2); Objeto _aObjeto_3 = recoger.getAObjeto(); String _name_1 = _aObjeto_3.getName(); String _plus_1 = ("Se recogio " + _name_1); _xblockexpression = InputOutput.<String>println(_plus_1); } _xifexpression_1 = _xblockexpression; } else { Objeto _aObjeto_2 = recoger.getAObjeto(); String _name_1 = _aObjeto_2.getName(); String _plus_1 = ("No se pudo recoger " + _name_1); _xifexpression_1 = InputOutput.<String>println(_plus_1); } _xifexpression = _xifexpression_1; } return _xifexpression; } public boolean esRecogible(final Objeto objeto) { EList<Accion> _acciones = objeto.getAcciones(); final Function1<Accion, Boolean> _function = new Function1<Accion, Boolean>() { @Override public Boolean apply(final Accion acc) { Class<? extends Accion> _class = acc.getClass(); return Boolean.valueOf(_class.equals(RecogibleImpl.class)); } }; return IterableExtensions.<Accion>exists(_acciones, _function); } public Object imprimir(final ElementosDelJuego hab) { if (hab instanceof Habitacion) { return _imprimir((Habitacion)hab); } else if (hab instanceof Objeto) { return _imprimir((Objeto)hab); } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object>asList(hab).toString()); } } public Object exec(final Comandos des) { if (des instanceof DescribirObjetos) { return _exec((DescribirObjetos)des); } else if (des instanceof EjecutarAccion) { return _exec((EjecutarAccion)des); } else if (des instanceof ListarAcciones) { return _exec((ListarAcciones)des); } else if (des instanceof ListarObjetosInventario) { return _exec((ListarObjetosInventario)des); } else if (des instanceof PreguntarObjetos) { return _exec((PreguntarObjetos)des); } else if (des instanceof RecogerObjeto) { return _exec((RecogerObjeto)des); } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object>asList(des).toString()); } } public Object chequearAccion(final Accion accionAbrir) { if (accionAbrir instanceof AbrirCerrar) { return _chequearAccion((AbrirCerrar)accionAbrir); } else if (accionAbrir instanceof Entrar) { return _chequearAccion((Entrar)accionAbrir); } else { throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object>asList(accionAbrir).toString()); } } }
package com.lenovohit.hcp.base.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.NotFound; import org.hibernate.annotations.NotFoundAction; import com.lenovohit.hcp.base.annotation.RedisSequence; /** * 收费组套 * * @author victor * */ @Entity @Table(name = "ITEM_GROUP_INFO") public class ChargePkg extends HcpBaseModel { /** * 业务类型:收费记账 */ public static final String BIZ_CLASS_FINANCE = "1"; /** * 业务类型:医生站 */ public static final String BIZ_CLASS_DOC = "2"; /** * 共享等级:个人 */ public static final String SHARE_LEVEL_PERSONAL = "1"; /** * 共享等级:部门 */ public static final String SHARE_LEVEL_DEPARTMENT = "2"; /** * 共享等级:全院 */ public static final String SHARE_LEVEL_HOSPITAL = "3"; private static final long serialVersionUID = 4613177437589474502L; private String comboId;// 套餐ID, private String comboName;// 套餐名称, private String busiClass;// 业务分类1-收费记账,2-医生站 private String drugFlag; // 药品标志 private Department useDept;// 科室, private String comm;// 备注 private String spellCode;// 拼音|超过10位无检索意义, private String wbCode;// 五笔, private String userCode;// 自定义码, private boolean stop;// 停用标志|1停0-启, private String shareLevel; // 共享等级(1:个人 2:科室 3:全院) @RedisSequence public String getComboId() { return comboId; } public void setComboId(String comboId) { this.comboId = comboId; } public String getComboName() { return comboName; } public void setComboName(String comboName) { this.comboName = comboName; } @ManyToOne @JoinColumn(name = "USE_DEPT", nullable = true) @NotFound(action = NotFoundAction.IGNORE) public Department getUseDept() { return useDept; } public void setUseDept(Department useDept) { this.useDept = useDept; } public String getBusiClass() { return busiClass; } public void setBusiClass(String busiClass) { this.busiClass = busiClass; } public String getComm() { return comm; } public void setComm(String comm) { this.comm = comm; } public String getSpellCode() { return spellCode; } public void setSpellCode(String spellCode) { this.spellCode = spellCode; } public String getWbCode() { return wbCode; } public void setWbCode(String wbCode) { this.wbCode = wbCode; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } @Column(name = "STOP_FLAG") public boolean isStop() { return stop; } public void setStop(boolean stop) { this.stop = stop; } public String getShareLevel() { return shareLevel; } public void setShareLevel(String shareLevel) { this.shareLevel = shareLevel; } public String getDrugFlag() { return drugFlag; } public void setDrugFlag(String drugFlag) { this.drugFlag = drugFlag; } }
package com.bryantp.cartesian; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static org.junit.Assert.assertEquals; /** * @author Bryan Perino */ public class CartesianTest { @Test public void testBasicExpression() { final String expression = "{A,B}"; List<String> answers = CartesianProductSolver.solve(expression); String[] expectedAnswers = new String[]{"A", "B"}; assertEquals(2, expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testSimpleExpression() { final String expression = "A{B,C}D{E,F}"; List<String> answer = CartesianProductSolver.solve(expression); final String[] expectedAnswers = {"ABDE", "ABDF", "ACDE", "ACDF"}; assertEquals(answer.toString(), expectedAnswers.length, answer.size()); verifyContents(answer, expectedAnswers); } @Test public void testHangingValueExpression() { final String expression = "A{B,C}D"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"ABD", "ACD"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testHangingValueSingleStandaloneExpression() { final String expression = "A{B,C,D}E"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"ABE", "ACE", "ADE"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testRecursiveExpression() { final String expression = "A{B,C{D,E}}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"AB", "ACD", "ACE"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testRecursiveHangingValueExpression() { final String expression = "A{B,C{D,E}}F"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"ABF", "ACDF", "ACEF"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testSingleRecursiveExpression() { final String expression = "ab{c,d}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"abc", "abd"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testDoublyRecursiveExpression() { final String expression = "ab{c,d{e,f}}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"abc", "abde", "abdf"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testTriplyRecursiveExpression() { final String expression = "ab{c,d{e,f{g,h}}}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"abc", "abde", "abdfg", "abdfh"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testTripleRecursiveDoubleExpression() { final String expression = "ab{c,d{e,f{gg,h}}}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"abc", "abde", "abdfgg", "abdfh"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testSingleRecursiveDoubleExpression() { final String expression = "a{b,c}d{e,f}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"abde", "abdf", "acde", "acdf"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testSingleRecursiveDoubleTrailingExpression() { final String expression = "a{b,c}d{e,f}g{h,i}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"abdegh", "abdegi", "abdfgh", "abdfgi", "acdegh", "acdegi", "acdfgh", "acdfgi"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testDoubleRecursiveSingleEmbeddedTrailingExpression() { final String expression = "a{b,c{d,e}f}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"ab", "acdf", "acef"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testDoubleEmbeddedSingleTrailingExpression() { final String expression = "a{b,c{d,e}}f"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"abf", "acdf", "acef"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testTwoDoubleEmbeddedSingleTrailingExpression() { final String expression = "a{b,z,c{d,e}f}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = {"ab", "az", "acdf", "acef"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testSingleEmbeddedSingleTrailingExpression() { final String expression = "ab{c,d}e"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = {"abce", "abde"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testSingleRecursiveDoubleTrailingExpressionTwo() { final String expression = "a{b,c}d{e,f,g}hi"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = {"abdehi", "abdfhi", "abdghi", "acdehi", "acdfhi", "acdghi"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testSingleRecursiveSingleTrailingDouble() { final String expression = "A{B,C}DF"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = {"ABDF", "ACDF"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testDoubleRecursiveSingleExpression() { final String expression = "A{C{D,E}G,H}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = {"ACDG", "ACEG", "AH"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testDoubleRecursiveDoubleTrailingExpression() { final String expression = "a{b,c{d,e,f}g,h}ij{k,l}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = {"abijk", "abijl", "acdgijk", "acdgijl", "acegijk", "acegijl", "acfgijk", "acfgijl", "ahijk", "ahijl"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testDoubleRecursionTripleTrailingExpression() { final String expression = "a{b,c{d,e,f}g,h}ij{k,l}mno{p,q}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = {"abijkmnop", "abijkmnoq", "abijlmnop", "abijlmnoq", "acdgijkmnop", "acdgijkmnoq", "acdgijlmnop", "acdgijlmnoq", "acegijkmnop", "acegijkmnoq", "acegijlmnop", "acegijlmnoq", "acfgijkmnop", "acfgijkmnoq", "acfgijlmnop", "acfgijlmnoq", "ahijkmnop", "ahijkmnoq", "ahijlmnop", "ahijlmnoq"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testCommaInOddPlaceExpression() { final String expression = "A{B,C,{D,E}}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"AB", "AC", "AD", "AE"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testCommaInOddPlaceDoubleExpression() { final String expression = "a{b,cz,{d,e}}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"ab", "acz", "ad", "ae"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testDoubledUpExpression() { final String expression = "a{bb,cc{d,e}}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"abb", "accd", "acce"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testHangingComma() { final String expression = "A{B,}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"AB", "A"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testDoubleHangingCommaExpression() { final String expression = "A{B,,}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"AB", "A", "A"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testSimpleNonMergeExpressions() { final String expression = "{{A,B},{C,D}}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"A", "B", "C", "D"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } @Test public void testBigNonMergeExpression() { final String expression = "{{A,B},C{D,E}}"; List<String> answers = CartesianProductSolver.solve(expression); final String[] expectedAnswers = new String[]{"A", "B", "CD", "CE"}; assertEquals(answers.toString(), expectedAnswers.length, answers.size()); verifyContents(answers, expectedAnswers); } private void verifyContents(List<String> values, String[] expectedValues) { List<String> list = Arrays.stream(expectedValues).collect(Collectors.<String>toList()); verifyContents(values, list); } private void verifyContents(List<String> values, List<String> expectedValues) { if (values.size() != expectedValues.size()) Assert.fail("Values must be equal length to expectedValues"); int idx = 0; for (String s : values) { String expected = expectedValues.get(idx++); assertEquals("Value was un-expected " + s, expected, s); } } }
package com.wang.demo.produce; import java.util.LinkedList; /** * @Auther: wl * @Date: 2019/3/9 09:14 * @Description: */ public class Repertory { //仓库大小 private final int MAX_SIZE = 10; //载体 private LinkedList<Object> list = new LinkedList<>(); public void produce(){ synchronized (list){ while (list.size()+1>MAX_SIZE){ System.out.println("生产者"+Thread.currentThread().getName()+"仓库已满"); try { list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.add(new Object()); System.out.println("生产者"+Thread.currentThread().getName()+"生产一个产品,现库存"+list.size()); list.notifyAll(); } } public void customer(){ synchronized (list){ while (list.isEmpty()){ System.out.println("消费者"+Thread.currentThread().getName()+"没东西可以消费"); } list.remove(); System.out.println("消费者"+Thread.currentThread().getName()+"正在消费一个产品,库存为"+list.size()); list.notifyAll(); } } public static void main(String[] args) { Repertory repertory = new Repertory(); Thread p1 = new Thread(new Producer(repertory)); Thread p2 = new Thread(new Producer(repertory)); Thread p3 = new Thread(new Producer(repertory)); Thread c1 = new Thread(new Customer(repertory)); Thread c2 = new Thread(new Customer(repertory)); Thread c3 = new Thread(new Customer(repertory)); p1.start(); p2.start(); p3.start(); c1.start(); c2.start(); c3.start(); } }
import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import java.io.File; import java.util.Iterator; public class DOM4JRead { public static void main(String[] args) { File file = new File("xml_demo_03.xml"); SAXReader reader = new SAXReader(); Document doc = null; try { doc = reader.read(file); } catch (DocumentException e) { e.printStackTrace(); } Element root = doc.getRootElement(); Iterator iter = root.elementIterator(); while (iter.hasNext()){ Element linkMan = (Element)iter.next(); System.out.println("姓名:"+linkMan.elementText("name")); System.out.println("邮件:"+linkMan.elementText("email")); } } }
package app.prueba.caso_android.epub; import java.io.Serializable; import java.lang.reflect.Method; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import com.dropbox.sync.android.DbxPath; import app.prueba.caso_android.util.Constants; /** * @author fjnavarrol * Clase que usaremos como bean para contener los datos de un libro */ public class BookItem implements Serializable{ /** * */ private static final long serialVersionUID = 3373047714186518163L; //Con este formatter parsearemos la fecha tal y como la queramos poner en constantes private static final SimpleDateFormat dateFormat = new SimpleDateFormat(Constants.DATE_FORMAT); private String nombre; private String fecha; private String filename; private DbxPath ruta; public BookItem(String nombre){ this.nombre=nombre; } public BookItem(String nombre, String fecha) { this.nombre = nombre; this.fecha = fecha; } public BookItem(String name, Date modifiedTime) { this.nombre = name; this.fecha = dateFormat.format(modifiedTime); } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } //Aquí recogemos el nombre recortado si se sale de la pantalla, dependiendo de la constante de max length public String getNombreShort() { if(nombre.length()>Constants.MAX_TITLE_LENGHT) return nombre.substring(0,Constants.MAX_TITLE_LENGHT-3)+"..."; return nombre; } public DbxPath getRuta() { return ruta; } public void setRuta(DbxPath ruta) { this.ruta = ruta; } public void setFecha(Date modifiedTime) { this.fecha = dateFormat.format(modifiedTime); } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } public String toString(){ return nombre; } /** * @param another Objeto a comparar * @param orden - * @return Devuelve: * Si son iguales 0 * Si el objeto es mayor 1 * Si el objeto es menor al que le pasamos -1 */ public int compareTo(BookItem another,int orden) { // Metodo en el que le decimos si el objeto es anterior o no segun un campo if(orden==Constants.ORDER_BY_DATE){ try { Date time=dateFormat.parse(this.getFecha()); Date time2=dateFormat.parse(another.getFecha()); return (int) (time.getTime()-time2.getTime()); } catch (ParseException e) { } }else if(orden==Constants.ORDER_BY_NAME){ return this.getNombre().compareTo( another.getNombre()); } return 0; } public static ArrayList<BookItem> ordernarlista(ArrayList<BookItem> lista, int orden){ BookItem[] ordenacion= lista.toArray(new BookItem[0]); BookItem aux; //Hacemos la ordenacion de la burbuja for(int i=0;i<lista.size();i++){ for(int j=0+i;j<lista.size();j++){ //Hago la comparacion if( ordenacion[i].compareTo( ordenacion[j], orden)>0){ //Es mayor el i, por lo que lo ponemos posteriormente aux=ordenacion[i]; ordenacion[i]=ordenacion[j]; ordenacion[j]=aux; } } } //Devolvemos un nuevo arraylist con el array que hemos ordenado return new ArrayList<BookItem>(Arrays.asList(ordenacion)); } }
package net.dryuf.comp.gallery.dao; import java.util.Map; import java.util.List; import net.dryuf.comp.gallery.GallerySection; import net.dryuf.core.EntityHolder; import net.dryuf.core.CallerContext; import net.dryuf.transaction.TransactionHandler; public interface GallerySectionDao extends net.dryuf.dao.DynamicDao<GallerySection, net.dryuf.comp.gallery.GallerySection.Pk> { public GallerySection refresh(GallerySection obj); public GallerySection loadByPk(net.dryuf.comp.gallery.GallerySection.Pk pk); public List<GallerySection> listAll(); public void insert(GallerySection obj); public void insertTxNew(GallerySection obj); public GallerySection update(GallerySection obj); public void remove(GallerySection obj); public boolean removeByPk(net.dryuf.comp.gallery.GallerySection.Pk pk); public List<GallerySection> listByCompos(Long compos); public long removeByCompos(Long compos); public net.dryuf.comp.gallery.GallerySection.Pk importDynamicKey(Map<String, Object> data); public Map<String, Object> exportDynamicData(EntityHolder<GallerySection> holder); public Map<String, Object> exportEntityData(EntityHolder<GallerySection> holder); public GallerySection createDynamic(EntityHolder<?> composition, Map<String, Object> data); public EntityHolder<GallerySection> retrieveDynamic(EntityHolder<?> composition, net.dryuf.comp.gallery.GallerySection.Pk pk); public GallerySection updateDynamic(EntityHolder<GallerySection> roleObject, net.dryuf.comp.gallery.GallerySection.Pk pk, Map<String, Object> updates); public boolean deleteDynamic(EntityHolder<?> composition, net.dryuf.comp.gallery.GallerySection.Pk pk); public long listDynamic(List<EntityHolder<GallerySection>> results, EntityHolder<?> composition, Map<String, Object> filter, List<String> sorts, Long start, Long limit); public TransactionHandler keepContextTransaction(CallerContext callerContext); public <R> R runTransactioned(java.util.concurrent.Callable<R> code) throws Exception; public <R> R runTransactionedNew(java.util.concurrent.Callable<R> code) throws Exception; public GallerySection loadByDisplay(Long galleryId, String displayName); public void updateSectionStats(net.dryuf.comp.gallery.GallerySection.Pk gallerySectionPk); public Long getMaxSectionCounter(Long galleryId); }
package com.superoback.dto; import com.superoback.model.StatusEnum; import com.superoback.model.Task; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class TaskDTO { private Long id; private String title; private String description; private StatusEnum statusEnum; public Task toModel() { Task task = new Task(); task.setId(this.id); task.setTitle(this.title); task.setDescription(this.description); task.setStatusEntity(this.statusEnum); return task; } }
package io.nuls.crosschain.test; import io.nuls.base.basic.AddressTool; import io.nuls.base.data.CoinData; import io.nuls.base.data.CoinFrom; import io.nuls.base.data.CoinTo; import io.nuls.base.data.NulsSignData; import io.nuls.base.signture.P2PHKSignature; import io.nuls.base.signture.TransactionSignature; import io.nuls.core.crypto.ECKey; import io.nuls.core.crypto.HexUtil; import io.nuls.core.exception.NulsException; import io.nuls.core.log.Log; import io.nuls.core.rpc.info.Constants; import io.nuls.core.rpc.info.NoUse; import io.nuls.core.rpc.model.ModuleE; import io.nuls.core.rpc.model.message.Response; import io.nuls.common.NerveCoreResponseMessageProcessor; import io.nuls.crosschain.base.model.ResetChainInfoTransaction; import io.nuls.crosschain.base.model.bo.txdata.ResetChainInfoData; import org.junit.Test; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TxSendTester { @Test public void test() throws Exception { NoUse.mockModule(); String prikey = ""; ECKey ecKey = ECKey.fromPrivate(HexUtil.decode(prikey)); byte[] address = AddressTool.getAddress(ecKey.getPubKey(), 5); ResetChainInfoTransaction tx = new ResetChainInfoTransaction(); tx.setTime(System.currentTimeMillis() / 1000); ResetChainInfoData txData = new ResetChainInfoData(); txData.setJson("{\n" + " \"chainId\":2,\n" + " \"chainName\":\"nuls2\",\n" + " \"minAvailableNodeNum\":0,\n" + " \"maxSignatureCount\":100,\n" + " \"signatureByzantineRatio\":66,\n" + " \"addressPrefix\":\"tNULS\",\n" + " \"assetInfoList\":[\n" + " {\n" + " \"assetId\":1,\n" + " \"symbol\":\"NULS\",\n" + " \"assetName\":\"\",\n" + " \"usable\":true,\n" + " \"decimalPlaces\":8\n" + " },\n" + " {\n" + " \"assetId\":8,\n" + " \"symbol\":\"T1\",\n" + " \"assetName\":\"t1\",\n" + " \"usable\":true,\n" + " \"decimalPlaces\":9\n" + " },\n" + " {\n" + " \"assetId\":29,\n" + " \"symbol\":\"BIG\",\n" + " \"assetName\":\"BIG\",\n" + " \"usable\":true,\n" + " \"decimalPlaces\":2\n" + " },\n" + " {\n" + " \"assetId\":31,\n" + " \"symbol\":\"TTk\",\n" + " \"assetName\":\"token\",\n" + " \"usable\":true,\n" + " \"decimalPlaces\":7\n" + " },\n" + " {\n" + " \"assetId\":33,\n" + " \"symbol\":\"NNERVENABOXTOMOON\",\n" + " \"assetName\":\"nnn\",\n" + " \"usable\":true,\n" + " \"decimalPlaces\":10\n" + " },\n" + " {\n" + " \"assetId\":40,\n" + " \"symbol\":\"TAKER\",\n" + " \"assetName\":\"TakerSwap\",\n" + " \"usable\":true,\n" + " \"decimalPlaces\":18\n" + " },\n" + " {\n" + " \"assetId\":58,\n" + " \"symbol\":\"NABOX\",\n" + " \"assetName\":\"NABOX\",\n" + " \"usable\":true,\n" + " \"decimalPlaces\":18\n" + " },\n" + " {\n" + " \"assetId\":64,\n" + " \"symbol\":\"pg\",\n" + " \"assetName\":\"pigs\",\n" + " \"usable\":true,\n" + " \"decimalPlaces\":3\n" + " }\n" + " ],\n" + " \"verifierList\":[\n" + " \"tNULSeBaMkrt4z9FYEkkR9D6choPVvQr94oYZp\",\n" + " \"tNULSeBaMoGr2RkLZPfJeS5dFzZeNj1oXmaYNe\",\n" + " \"tNULSeBaMmShSTVwbU4rHkZjpD98JgFgg6rmhF\"\n" + " ],\n" + " \"registerTime\":0\n" + " }"); tx.setTxData(txData.serialize()); CoinData coinData = new CoinData(); CoinFrom from = new CoinFrom(); from.setAddress(address); from.setAmount(BigInteger.ZERO); from.setAssetsChainId(5); from.setAssetsId(1); from.setLocked((byte) 0); from.setNonce(HexUtil.decode("38beaaea79a72b26")); coinData.getFrom().add(from); CoinTo to = new CoinTo(); to.setAddress(address); to.setAmount(BigInteger.ZERO); to.setAssetsId(1); to.setAssetsChainId(5); to.setLockTime(0); coinData.getTo().add(to); tx.setCoinData(coinData.serialize()); TransactionSignature transactionSignature = new TransactionSignature(); List<P2PHKSignature> list = new ArrayList<>(); P2PHKSignature sig = new P2PHKSignature(); sig.setPublicKey(ecKey.getPubKey()); NulsSignData data = new NulsSignData(); data.setSignBytes(ecKey.sign(tx.getHash().getBytes())); sig.setSignData(data); list.add(sig); transactionSignature.setP2PHKSignatures(list); tx.setTransactionSignature(transactionSignature.serialize()); Log.info(tx.getHash().toHex()); Log.info(HexUtil.encode(tx.serialize())); sendTx(5, HexUtil.encode(tx.serialize())); } @SuppressWarnings("unchecked") public static void sendTx(int chainId, String tx) throws NulsException { Map<String, Object> params = new HashMap(4); params.put(Constants.CHAIN_ID, chainId); params.put("tx", tx); try { Response cmdResp = NerveCoreResponseMessageProcessor.requestAndResponse(ModuleE.TX.abbr, "tx_newTx", params); if (!cmdResp.isSuccess()) { //rollBackUnconfirmTx(chain,tx); throw new RuntimeException(); } } catch (NulsException e) { throw e; } catch (Exception e) { e.printStackTrace(); } } }
package com.ranpeak.ProjectX.activity.splashscreen.commands; public interface SplashNavigator { void handleError(Throwable throwable); void completeLoad(); }
package com.memory.platform.web.web.interseptor; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.util.AntPathMatcher; import org.springframework.util.PathMatcher; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class HttpInterseptor implements HandlerInterceptor { private PathMatcher pathMatcher = new AntPathMatcher(); private List<String> excludeUrls; public List<String> getExcludeUrls() { return excludeUrls; } public void setExcludeUrls(List<String> excludeUrls) { this.excludeUrls = excludeUrls; } @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { // TODO Auto-generated method stub } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { // TODO Auto-generated method stub } @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2){ String requestPath = arg0.getServletPath(); if(excludeUrls != null && !"".equals(excludeUrls)) { for(String urlPattern : excludeUrls){ if(pathMatcher.match(urlPattern,requestPath)){ return true; } } } try { String url = arg0.getRequestURL().toString(); if(url.startsWith("https")) { return true; } else { throw new Exception("Http is not surport!"); } } catch (Exception e) { e.printStackTrace(); } return false; } }
package com.karya.bean; public class RecruitOfferBean { private int offerId; private String applicantNamePrefix; private String applicantName; private String companyName; private String offer; private String refer; private String position; private String grade; private String ctc; private String dateOfJoin; private String line1; private String line2; private String cityOrVillage; private String stateOrTerritory; private String country; private String postalCode; private String phoneNo; private String alternativePhoneNo; private String offerLetter; /** * Get Offer Id * @return */ public int getOfferId() { return offerId; } /** * Set Offer Id * @param offerId */ public void setOfferId(int offerId) { this.offerId = offerId; } /** * Get Application Name Prefix * @return */ public String getApplicantNamePrefix() { return applicantNamePrefix; } /** * Set Application Name Prefix * @param applicantNamePrefix */ public void setApplicantNamePrefix(String applicantNamePrefix) { this.applicantNamePrefix = applicantNamePrefix; } /** * Get Application Name * @return */ public String getApplicantName() { return applicantName; } /** * Set Application Name * @param applicantName */ public void setApplicantName(String applicantName) { this.applicantName = applicantName; } /** * Get Company Name * @return */ public String getCompanyName() { return companyName; } /** * Set Company Name * @param companyName */ public void setCompanyName(String companyName) { this.companyName = companyName; } /** * Get Offer * @return */ public String getOffer() { return offer; } /** * Set Offer * @param offer */ public void setOffer(String offer) { this.offer = offer; } /** * Get Refer * @return */ public String getRefer() { return refer; } /** * Set Refer * @param refer */ public void setRefer(String refer) { this.refer = refer; } /** * Get Position * @return */ public String getPosition() { return position; } /** * Set Position * @param position */ public void setPosition(String position) { this.position = position; } /** * Get Grade * @return */ public String getGrade() { return grade; } /** * Set Grade * @param grade */ public void setGrade(String grade) { this.grade = grade; } /** * Get CTC * @return */ public String getCtc() { return ctc; } /** * Set CTC * @param ctc */ public void setCtc(String ctc) { this.ctc = ctc; } /** * Get Date of Join * @return */ public String getDateOfJoin() { return dateOfJoin; } /** * Set Date of Join * @param dateOfJoin */ public void setDateOfJoin(String dateOfJoin) { this.dateOfJoin = dateOfJoin; } /** * Get Line 1 * @return */ public String getLine1() { return line1; } /** * Set Line 1 * @param line1 */ public void setLine1(String line1) { this.line1 = line1; } /** * Get Line 2 * @return */ public String getLine2() { return line2; } /** * Set Line 2 * @param line2 */ public void setLine2(String line2) { this.line2 = line2; } /** * Get City Or Village * @return */ public String getCityOrVillage() { return cityOrVillage; } /** * Set City Or Village * @param cityOrVillage */ public void setCityOrVillage(String cityOrVillage) { this.cityOrVillage = cityOrVillage; } /** * Get State Or Territory * @return */ public String getStateOrTerritory() { return stateOrTerritory; } /** * Set State Or Territory * @param stateOrTerritory */ public void setStateOrTerritory(String stateOrTerritory) { this.stateOrTerritory = stateOrTerritory; } /** * Get Country * @return */ public String getCountry() { return country; } /** * Set Country * @param country */ public void setCountry(String country) { this.country = country; } /** * Get Postal Code * @return */ public String getPostalCode() { return postalCode; } /** * Set Postal Code * @param postalCode */ public void setPostalCode(String postalCode) { this.postalCode = postalCode; } /** * Get Phone No * @return */ public String getPhoneNo() { return phoneNo; } /** * Set Phone No * @param phoneNo */ public void setPhoneNo(String phoneNo) { this.phoneNo = phoneNo; } /** * Get Alternative Phone No * @return */ public String getAlternativePhoneNo() { return alternativePhoneNo; } /** * Set Alternative Phone No * @param applicantName */ public void setAlternativePhoneNo(String alternativePhoneNo) { this.alternativePhoneNo = alternativePhoneNo; } /** * Set Offer Letter Name * @return */ public String getOfferLetter() { return offerLetter; } /** * Get Offer Letter Name * @param offerLetter */ public void setOfferLetter(String offerLetter) { this.offerLetter = offerLetter; } }
package com.github.xuchengen.request; import com.github.xuchengen.UnionPayRequest; import com.github.xuchengen.response.UnionPayFileTransferResponse; /** * 在线网关支付--文件传输接口请求模型 * 作者:徐承恩 * 邮箱:xuchengen@gmail.com * 日期:2019/8/30 */ public class UnionPayFileTransferRequest extends UnionPayCommonRequest implements UnionPayRequest<UnionPayFileTransferResponse> { /** * 产品类型 */ private String bizType = "000000"; /** * 清算日期 */ private String settleDate; /** * 文件类型 */ private String fileType; /** * 请求方保留域 */ private String reqReserved; public String getBizType() { return bizType; } public void setBizType(String bizType) { this.bizType = bizType; } public String getSettleDate() { return settleDate; } public void setSettleDate(String settleDate) { this.settleDate = settleDate; } public String getFileType() { return fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getReqReserved() { return reqReserved; } public void setReqReserved(String reqReserved) { this.reqReserved = reqReserved; } @Override public String getApiPath() { return null; } @Override public Class<UnionPayFileTransferResponse> getResponseClass() { return UnionPayFileTransferResponse.class; } }
package com.uchain.core; import com.uchain.core.block.Block; @FunctionalInterface public interface NotificationOnBlock { void onBlock(Block block); }
//multiException handling class MultiCatchHandlingl { public static void main(String[]args) { try{ int cmd = args.length; int intvalue = 20; int c = intvalue / cmd; int arr[] = {1}; arr[10] = 44; } catch(ArithmeticException e) { System.out.println("ArithmeticException Error"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBoundsException"); } } }
package com.cloud.storage.server; public class SettingsMgmt { public static int PORT = 36663; public static final String ROOT_FOLDER = "C:\\temp\\users_folders\\"; public static long MAX_USER_FOLDER_SIZE = 2147483648L; }
/** * MIT License * <p> * Copyright (c) 2019-2022 nerve.network * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package network.nerve.converter.tx.v1; import io.nuls.base.data.BlockHeader; import io.nuls.base.data.Transaction; import io.nuls.base.protocol.TransactionProcessor; import io.nuls.core.constant.ErrorCode; import io.nuls.core.constant.TxType; import io.nuls.core.core.annotation.Autowired; import io.nuls.core.core.annotation.Component; import io.nuls.core.exception.NulsRuntimeException; import io.nuls.core.log.logback.NulsLogger; import network.nerve.converter.constant.ConverterConstant; import network.nerve.converter.constant.ConverterErrorCode; import network.nerve.converter.core.api.ConverterCoreApi; import network.nerve.converter.core.heterogeneous.docking.interfaces.IHeterogeneousChainDocking; import network.nerve.converter.core.heterogeneous.docking.management.HeterogeneousDockingManager; import network.nerve.converter.enums.BindHeterogeneousContractMode; import network.nerve.converter.helper.LedgerAssetRegisterHelper; import network.nerve.converter.manager.ChainManager; import network.nerve.converter.model.bo.Chain; import network.nerve.converter.model.bo.HeterogeneousAssetInfo; import network.nerve.converter.model.bo.NerveAssetInfo; import network.nerve.converter.model.txdata.HeterogeneousContractAssetRegCompleteTxData; import network.nerve.converter.model.txdata.HeterogeneousMainAssetRegTxData; import network.nerve.converter.storage.TxSubsequentProcessStorageService; import network.nerve.converter.utils.ConverterSignValidUtil; import network.nerve.converter.utils.HeterogeneousUtil; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author: Mimi * @date: 2020-03-23 */ @Component("HeterogeneousMainAssetRegV1") public class HeterogeneousMainAssetRegProcessor implements TransactionProcessor { @Autowired private TxSubsequentProcessStorageService txSubsequentProcessStorageService; @Override public int getType() { return TxType.HETEROGENEOUS_MAIN_ASSET_REG; } @Autowired private ChainManager chainManager; @Autowired private HeterogeneousDockingManager heterogeneousDockingManager; @Autowired private LedgerAssetRegisterHelper ledgerAssetRegisterHelper; @Autowired private ConverterCoreApi converterCoreApi; @Override public Map<String, Object> validate(int chainId, List<Transaction> txs, Map<Integer, List<Transaction>> txMap, BlockHeader blockHeader) { if (txs.isEmpty()) { return null; } Chain chain = chainManager.getChain(chainId); NulsLogger logger = chain.getLogger(); Map<String, Object> result = null; try { String errorCode = ConverterErrorCode.DATA_ERROR.getCode(); result = new HashMap<>(ConverterConstant.INIT_CAPACITY_4); List<Transaction> failsList = new ArrayList<>(); for (Transaction tx : txs) { // 异构合约主资产注册 HeterogeneousMainAssetRegTxData txData = new HeterogeneousMainAssetRegTxData(); txData.parse(tx.getTxData(), 0); // 签名验证(种子虚拟银行) ConverterSignValidUtil.validateSeedNodeSign(chain, tx); // exclude (nuls & EVM:enuls) (eth & EVM:goerliETH) if (converterCoreApi.isProtocol22() && !HeterogeneousUtil.checkHeterogeneousMainAssetReg(txData.getChainId())) { logger.error("此异构链不支持注册: {}", txData.getChainId()); ErrorCode error = ConverterErrorCode.NO_LONGER_SUPPORTED; errorCode = error.getCode(); logger.error(error.getMsg()); failsList.add(tx); continue; } IHeterogeneousChainDocking docking = heterogeneousDockingManager.getHeterogeneousDocking(txData.getChainId()); HeterogeneousAssetInfo mainAsset = docking.getMainAsset(); NerveAssetInfo nerveAssetInfo = ledgerAssetRegisterHelper.getNerveAssetInfo(mainAsset.getChainId(), mainAsset.getAssetId()); // 新注册,主资产不能存在 if(nerveAssetInfo != null && !nerveAssetInfo.isEmpty()) { logger.error("异构链主资产已存在"); ErrorCode error = ConverterErrorCode.ASSET_EXIST; errorCode = error.getCode(); logger.error(error.getMsg()); failsList.add(tx); continue; } } result.put("txList", failsList); result.put("errorCode", errorCode); } catch (Exception e) { chain.getLogger().error(e); result.put("txList", txs); result.put("errorCode", ConverterErrorCode.SYS_UNKOWN_EXCEPTION.getCode()); } return result; } @Override public boolean commit(int chainId, List<Transaction> txs, BlockHeader blockHeader, int syncStatus) { return commit(chainId, txs, blockHeader, syncStatus, false); } public boolean commit(int chainId, List<Transaction> txs, BlockHeader blockHeader, int syncStatus, boolean failRollback) { if (txs.isEmpty()) { return true; } Chain chain = null; try { chain = chainManager.getChain(chainId); for (Transaction tx : txs) { HeterogeneousMainAssetRegTxData txData = new HeterogeneousMainAssetRegTxData(); txData.parse(tx.getTxData(), 0); Integer hChainId = txData.getChainId(); IHeterogeneousChainDocking docking = heterogeneousDockingManager.getHeterogeneousDocking(hChainId); HeterogeneousAssetInfo mainAsset = docking.getMainAsset(); // 异构链主资产注册 ledgerAssetRegisterHelper.crossChainAssetReg(chainId, hChainId, mainAsset.getAssetId(), mainAsset.getSymbol(), mainAsset.getDecimals(), mainAsset.getSymbol(), mainAsset.getContractAddress()); chain.getLogger().info("[commit] 异构链主资产注册, chainId: {}, assetId: {}, symbol: {}, decimals: {}", hChainId, mainAsset.getAssetId(), mainAsset.getSymbol(), mainAsset.getDecimals()); } } catch (Exception e) { chain.getLogger().error(e); return false; } return true; } @Override public boolean rollback(int chainId, List<Transaction> txs, BlockHeader blockHeader) { return rollback(chainId, txs, blockHeader, false); } public boolean rollback(int chainId, List<Transaction> txs, BlockHeader blockHeader, boolean failCommit) { if (txs.isEmpty()) { return true; } Chain chain = null; try { chain = chainManager.getChain(chainId); for (Transaction tx : txs) { HeterogeneousMainAssetRegTxData txData = new HeterogeneousMainAssetRegTxData(); txData.parse(tx.getTxData(), 0); Integer hChainId = txData.getChainId(); IHeterogeneousChainDocking docking = heterogeneousDockingManager.getHeterogeneousDocking(hChainId); HeterogeneousAssetInfo mainAsset = docking.getMainAsset(); // 异构主资产取消注册 ledgerAssetRegisterHelper.deleteCrossChainAsset(hChainId, mainAsset.getAssetId()); } } catch (Exception e) { chain.getLogger().error(e); return false; } return true; } }
package by.twikss.finalwork.database; import by.twikss.finalwork.logics.bean.Product; import by.twikss.finalwork.logics.enums.Category; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class DataBase { public static List<Product> baseOfProduct; public DataBase() { baseOfProduct = new ArrayList<>(); baseOfProduct.addAll(Arrays.asList( Product.builder() .id(1l) .name("Tolya") .price(BigDecimal.valueOf(45.90)) .category(Category.VEGETABLES) .discount(BigDecimal.valueOf(0.25)) .description("he") .build(), Product.builder() .id(2l) .name("Onions") .price(BigDecimal.valueOf(56.30)) .category(Category.VEGETABLES) .discount(BigDecimal.valueOf(0.15)) .build(), Product.builder() .id(3l) .name("Orange") .price(BigDecimal.valueOf(78.90)) .category(Category.FRUIT) .build(), Product.builder() .id(4l) .name("Pineapple") .price(BigDecimal.valueOf(60.0)) .category(Category.FRUIT) .build() )); } }
package com.packt.jdeveloper.cookbook.hr.components.model.application.client; import com.packt.jdeveloper.cookbook.hr.components.model.application.common.HrComponentsAppModule; import oracle.jbo.client.remote.ApplicationModuleImpl; import oracle.jbo.domain.Number; // --------------------------------------------------------------------- // --- File generated by Oracle ADF Business Components Design Time. // --- Mon Nov 03 18:21:32 EST 2014 // --- Custom code may be added to this class. // --- Warning: Do not modify method signatures of generated methods. // --------------------------------------------------------------------- public class HrComponentsAppModuleClient extends ApplicationModuleImpl implements HrComponentsAppModule { /** * This is the default constructor (do not remove). */ public HrComponentsAppModuleClient() { } public void adjustCommission(Number commissionPctAdjustment) { Object _ret = this.riInvokeExportedMethod(this,"adjustCommission",new String [] {"oracle.jbo.domain.Number"},new Object[] {commissionPctAdjustment}); return; } public void refreshEmployees() { Object _ret = this.riInvokeExportedMethod(this,"refreshEmployees",null,null); return; } public void removeEmployeeFromCollection() { Object _ret = this.riInvokeExportedMethod(this,"removeEmployeeFromCollection",null,null); return; } }
package com.ctg.itrdc.janus.rpc.cluster; import com.ctg.itrdc.janus.common.extension.Adaptive; import com.ctg.itrdc.janus.common.extension.SPI; import com.ctg.itrdc.janus.rpc.Invoker; import com.ctg.itrdc.janus.rpc.RpcException; import com.ctg.itrdc.janus.rpc.cluster.support.FailoverCluster; /** * Cluster. (SPI, Singleton, ThreadSafe) * * <a href="http://en.wikipedia.org/wiki/Computer_cluster">Cluster</a> <a * href="http://en.wikipedia.org/wiki/Fault-tolerant_system">Fault-Tolerant</a> * * @author Administrator */ @SPI(FailoverCluster.NAME) public interface Cluster { /** * 将目录里面的所有的invokers进行合并 to a virtual invoker. * * @param <T> * @param directory * @return cluster invoker * @throws RpcException */ @Adaptive <T> Invoker<T> join(Directory<T> directory) throws RpcException; }
package api.visitaescuela; import api.estudiante.EntidadEstudiante; import com.itextpdf.text.*; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.List; import java.util.Optional; @Service @Transactional public class ServicioVisitaEscuela { private static final Logger logger = LoggerFactory.getLogger(ServicioVisitaEscuela.class); @Autowired private RepositorioVisitaEscuela repositorioVisitaEscuela; public EntidadVisitaEscuela guardar(EntidadVisitaEscuela entidadVisitaEscuela) { return repositorioVisitaEscuela.save(entidadVisitaEscuela); } public Optional<EntidadVisitaEscuela> obtenerPorId(int id) { return repositorioVisitaEscuela.findById(id); } public Optional<EntidadVisitaEscuela> actualizar(int id, EntidadVisitaEscuela visitaEscuela) { return obtenerPorId(id).map(record -> { record.setCargo(visitaEscuela.getCargo()); record.setCuerpo(visitaEscuela.getCuerpo()); record.setEscuela(visitaEscuela.getEscuela()); record.setFecha(visitaEscuela.getFecha()); record.setNombreAnno(visitaEscuela.getNombreAnno()); record.setNombreDirectivo(visitaEscuela.getNombreDirectivo()); record.setObservaciones(visitaEscuela.getObservaciones()); record.setProfesor(visitaEscuela.getProfesor()); record.setProvincia(visitaEscuela.getProvincia()); record.setEstudiantes(visitaEscuela.getEstudiantes()); return guardar(record); }); } public Optional<EntidadVisitaEscuela> eliminar(int id) { return obtenerPorId(id).map(record -> { repositorioVisitaEscuela.deleteById(id); return record; }); } public List<EntidadVisitaEscuela> listarTodos() { return repositorioVisitaEscuela.findAll(); } public ByteArrayInputStream obtenerActaPdf(int id) { EntidadVisitaEscuela visitaEscuela = obtenerPorId(id).get(); Document document = new Document(); ByteArrayOutputStream out = new ByteArrayOutputStream(); try { PdfWriter.getInstance(document, out); document.open(); Paragraph element; element = new Paragraph(); element.setAlignment(Element.ALIGN_RIGHT); element.setFont(FontFactory.getFont(FontFactory.TIMES)); element.add(visitaEscuela.getProvincia().getNombre() + ", " + visitaEscuela.getFecha().toString().substring(0, 10)); document.add(element); element = new Paragraph(); element.setAlignment(Element.ALIGN_RIGHT); element.setFont(FontFactory.getFont(FontFactory.TIMES)); element.add(visitaEscuela.getNombreAnno().getNombre()); document.add(element); element = new Paragraph(); element.add(" "); document.add(element); element = new Paragraph(); element.setAlignment(Element.ALIGN_LEFT); element.setFont(FontFactory.getFont(FontFactory.TIMES)); element.add(visitaEscuela.getEscuela().getNombre() + ":"); document.add(element); element = new Paragraph(); element.setAlignment(Element.ALIGN_LEFT); element.setFont(FontFactory.getFont(FontFactory.TIMES)); element.add(visitaEscuela.getCuerpo()); document.add(element); element = new Paragraph(); element.setAlignment(Element.ALIGN_LEFT); element.setFont(FontFactory.getFont(FontFactory.TIMES)); element.add("Relación de estudiantes"); document.add(element); PdfPTable table = new PdfPTable(5); table.setWidthPercentage(100); PdfPCell cell; cell = new PdfPCell(new Phrase("No", FontFactory.getFont(FontFactory.TIMES_BOLD))); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Phrase("Nombre y Apellidos", FontFactory.getFont(FontFactory.TIMES_BOLD))); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Phrase("Facultad", FontFactory.getFont(FontFactory.TIMES_BOLD))); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Phrase("Asignatura", FontFactory.getFont(FontFactory.TIMES_BOLD))); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); cell = new PdfPCell(new Phrase("Grado y Grupos", FontFactory.getFont(FontFactory.TIMES_BOLD))); cell.setHorizontalAlignment(Element.ALIGN_CENTER); table.addCell(cell); int no = 1; for (EntidadEstudiante estudiante : visitaEscuela.getEstudiantes()) { cell = new PdfPCell(new Phrase(String.valueOf(no++), FontFactory.getFont(FontFactory.TIMES))); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(estudiante.getNombre() + " " + estudiante.getApellidos(), FontFactory.getFont(FontFactory.TIMES))); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(estudiante.getFacultad().getNombre(), FontFactory.getFont(FontFactory.TIMES))); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(estudiante.getGrupoClase() != null ? estudiante.getGrupoClase().getAsignatura().getNombre() : "", FontFactory.getFont(FontFactory.TIMES))); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); cell = new PdfPCell(new Phrase(estudiante.getGrupoClase() != null ? estudiante.getGrupoClase().getGrupoDocente().getGradoEscolar().getNombre() : "", FontFactory.getFont(FontFactory.TIMES))); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_LEFT); table.addCell(cell); } document.add(table); element = new Paragraph(); element.add(" "); document.add(element); element = new Paragraph(); element.setAlignment(Element.ALIGN_LEFT); element.setFont(FontFactory.getFont(FontFactory.TIMES)); element.add("Observaciones:"); document.add(element); element = new Paragraph(); element.setAlignment(Element.ALIGN_LEFT); element.setFont(FontFactory.getFont(FontFactory.TIMES)); element.add(visitaEscuela.getObservaciones()); document.add(element); element = new Paragraph(); element.add(" "); document.add(element); element = new Paragraph(); element.setAlignment(Element.ALIGN_CENTER); element.setFont(FontFactory.getFont(FontFactory.TIMES)); element.add(visitaEscuela.getNombreDirectivo()); document.add(element); element = new Paragraph(); element.setAlignment(Element.ALIGN_CENTER); element.setFont(FontFactory.getFont(FontFactory.TIMES)); element.add(visitaEscuela.getCargo() + " y firma"); document.add(element); element = new Paragraph(); element.add(" "); document.add(element); element = new Paragraph(); element.setAlignment(Element.ALIGN_CENTER); element.setFont(FontFactory.getFont(FontFactory.TIMES)); element.add(visitaEscuela.getProfesor().getNombre()); document.add(element); element = new Paragraph(); element.setAlignment(Element.ALIGN_CENTER); element.setFont(FontFactory.getFont(FontFactory.TIMES)); element.add("Nombre, Apellidos y firma del visitante"); document.add(element); document.close(); } catch (DocumentException ex) { logger.error("Error occurred: {0}", ex); } return new ByteArrayInputStream(out.toByteArray()); } }
package com.iut.as.interfaces; public interface IDaoClient<T> extends IDao<T> { }
package com.tibco.as.util.convert.impl; import java.util.Date; public class LongToDate extends AbstractConverter<Long, Date> { @Override protected Date doConvert(Long source) { return new Date(source); } }
package com.yc.education.mapper.customer; import com.yc.education.model.customer.Customer; import com.yc.education.util.MyMapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface CustomerMapper extends MyMapper<Customer> { /** * 查询所有未被禁用的客户 * @return */ List<Customer> listGeneralCustomer(); /** * 查询现有客户(小窗口) * @param stopUse 1:停用、0:正常 * @return */ List<Customer> listExistCustomer(@Param("text")String text,@Param("stopUse")String stopUse); /** * 查询所有客户 * @param state 客户账户状态 (0、正常,1、删除) * @return */ List<Customer> listCustomerAll(@Param("state")String state); /** * @Author BlueSky * @Description //TODO 查询客户 * @Date 11:40 2018/8/20 * @Param [] * @return com.yc.education.model.customer.Customer **/ Customer getCustomer(@Param("code")String code); /** * 统计客户数量 * @return */ int getCustomerCount(); }
package de.cuuky.varo.gui.admin.inventory; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import de.cuuky.varo.gui.SuperInventory; import de.cuuky.varo.gui.utils.PageAction; import de.cuuky.varo.player.stats.stat.inventory.InventoryBackup; public class InventoryBackupShowGUI extends SuperInventory { private InventoryBackup backup; public InventoryBackupShowGUI(Player opener, InventoryBackup backup) { super("§7Inventory: §c" + backup.getVaroPlayer().getName(), opener, 45, false); this.backup = backup; open(); } @Override public boolean onOpen() { for(int i = 0; i < backup.getInventory().getInventory().getContents().length; i++) inv.setItem(i, backup.getInventory().getInventory().getContents()[i]); for(int i = 0; i < backup.getArmor().size(); i++) inv.setItem(41 + i, backup.getArmor().get(i)); return true; } @Override public void onClick(InventoryClickEvent event) {} @Override public void onInventoryAction(PageAction action) {} @Override public boolean onBackClick() { new InventoryBackupGUI(opener, backup); return true; } @Override public void onClose(InventoryCloseEvent event) {} }
package array; import java.util.HashSet; import java.util.Set; /** * Created by pradhang on 3/28/2017. * Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place. * <p> * click to show follow up. * <p> * Follow up: * Did you use extra space? * A straight forward solution using O(mn) space is probably a bad idea. * A simple improvement uses O(m + n) space, but still not the best solution. * Could you devise a constant space solution? */ public class SetMatrixZeroes { /** * Main method * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int[][] matrix = {{0, 8, 7}, {9, 0, 8}, {9, 9, 0}}; new SetMatrixZeroes().setZeroes(matrix); } public void setZeroes(int[][] matrix) { Set<Integer> row = new HashSet<>(); Set<Integer> col = new HashSet<>(); int m = matrix.length; int n = matrix[0].length; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (matrix[i][j] == 0) { row.add(i); col.add(j); } } } for (int r : row) { for (int j = 0; j < n; j++) { matrix[r][j] = 0; } } for (int c : col) { for (int i = 0; i < m; i++) { matrix[i][c] = 0; } } } }
package commands; /** * Command wrapper to represent the /~skip command in the player. Values are * given as a String containing the target jump that should be sought to. * * @author Dilshad Khatri, Alvis Koshy, Drew Noel, Jonathan Tung * @version 1.0 * @since 2017-04-01 */ public class SkipCommand implements PlayerCommand { private String skipTo = ""; /** * Constructor of the SkipCommand which sets the target jump location * * @param skipTo * String representing the jump target */ public SkipCommand(String skipTo) { this.skipTo = skipTo; } @Override public String toString() { return "Go to location: " + skipTo; } @Override public String serialize() { return "/~skip:" + skipTo; } @Override public String getEditLabel() { return "Enter location to go to"; } @Override public String getCurrentValue() { return skipTo; } @Override public void setCurrentValue(String val) { this.skipTo = val; } @Override public void editCommand() { } }
package dataStructures; public class CircularLinkedList { public static Node head = null; public static Node tail = null; public static class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } public static void createCircularLinkedlist(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; tail = newNode; } else { tail.next = newNode; tail = newNode; } tail.next = head; } public static void displayCircularLinkedlist() { tail = head; System.out.println("head address" + " " + head); while (tail.next != head) { System.out.println(tail.data); tail = tail.next; } System.out.println(tail.data); System.out.println("last element address" + " " + tail.next); } public static void main(String[] args) { createCircularLinkedlist(5); createCircularLinkedlist(8); createCircularLinkedlist(9); displayCircularLinkedlist(); } }
package net.sduhsd.royr6099.scratch; import java.util.*; public class workystuff { public static void main(String[] args) { matrixMagic(); } public static void printResults(int[] counts, int min, int max) { for (int i = min; i <= max; i++) { System.out.println(i + " was generated " + counts[i - min] + " times."); } } public static int[] generateRandom(int number, int min, int max) { int[] counts = new int[max - min + 1]; Random r = new Random(); for (int i = 0; i < number; i++) { int n = r.nextInt(max + 1) + min; counts[n - min]++; } return counts; } public static int reverse(int number) { int result = 0; while (number >= 1) { result *= 10; result += number % 10; number /= 10; } return result; } public static boolean isPalindrome(int number) { return number == reverse(number); } public static String generatePlate() { String plate = ""; Random rand = new Random(); for (int i = 0; i < 3; i++) { char c = (char) (rand.nextInt(26) + 65); plate += c; } for (int i = 0; i < 4; i++) { char c = (char) (rand.nextInt(10) + 48); plate += c; } return plate; } public static boolean checkSSN(String input) { for (int i = 0; i < 11; i++) { if (i == 3 || i == 6) { if (!isDash(input.substring(i))) { return false; } } else { if (!isDigit(input.substring(i))) { return false; } } } return true; } private static boolean isDigit(String buffer) { char c = buffer.charAt(0); if ((int) c >= 48 && ((int) c <= 57)) { return true; } return false; } private static boolean isDash(String buffer) { char c = buffer.charAt(0); if (c == '-') { return true; } return false; } public static String decimalToBinary(int decimal) { String result = ""; if (decimal > 255) { return "OVERFLOW"; } else if (decimal < 0) { return "UNDERFLOW"; } int powerOf2 = 128; for (int i = 0; i < 8; i++) { if (powerOf2 <= decimal) { result += "1"; decimal -= powerOf2; } else { result += "0"; } powerOf2 /= 2; } return result; } public static int[] eliminateDuplicates(int[] list) { int[] result = new int[0]; for (int element : list) { boolean exists = false; for (int existing : result) { if (existing == element) { exists = true; break; } } if (!exists) { int[] added = new int[result.length + 1]; for (int i = 0; i < result.length; i++) { added[i] = result[i]; } added[result.length] = element; result = added; } } return result; } public static void sort(List<Number> list) { boolean sort_complete = false; while (!sort_complete) { sort_complete = true; for (int i = 0; i < list.size() - 1; i++) { if (list.get(i).doubleValue() > list.get(i + 1).doubleValue()) { sort_complete = false; Number buffer = list.get(i); list.set(i, list.get(i + 1)); list.set(i+1, buffer); } } } } public static void searchRun() { Random r = new Random(); int[] randomList = new int[100]; for (int i = 0; i < 100; i++) { randomList[i] = r.nextInt(101); } int numToFind = r.nextInt(101); System.out.println("Searching for: " + numToFind); long start = System.nanoTime(); int linFound = -1; for (int i = 0; i < 100; i++) { if (randomList[i] == numToFind) { linFound = i; break; } } long end = System.nanoTime(); System.out.println("Linear Search found at index " + linFound); System.out.println("Linear Search took " + (end - start) + " ns."); Arrays.sort(randomList); start = System.nanoTime(); int binFound = Arrays.binarySearch(randomList, numToFind); end = System.nanoTime(); System.out.println("Binary Search found at index " + binFound); System.out.println("Binary Search took " + (end - start) + " ns."); } public static int factorial(int n) { return factorial(n, 1); } public static int factorial(int n, int accum) { if (n > 0) { return factorial(n-1, accum * n); } else { return accum; } } public static int getLargestInteger(int[] array) { return getLargestInteger(array, Integer.MIN_VALUE, 0); } private static int getLargestInteger(int[] array, int max, int i) { if (i == array.length) return max; return getLargestInteger(array, Math.max(max, array[i]), i+1); } public static void matrixMagic() { int[][] mat = new int[6][6]; Random rand = new Random(); for (int r = 0; r < 6; r++) { for (int c = 0; c < 6; c++) { mat[r][c] = rand.nextInt(2); System.out.print(mat[r][c] + " "); } System.out.println(); } System.out.println(); for (int r = 0; r < 6; r++) { int row_sum = 0; for (int c = 0; c < 6; c++) { row_sum += mat[r][c]; } System.out.print("Row " + r + " has an "); if (row_sum % 2 == 0) { System.out.print("even"); } else { System.out.print("odd"); } System.out.println(" number of ones."); } System.out.println(); for (int c = 0; c < 6; c++) { int col_sum = 0; for (int r = 0; r < 6; r++) { col_sum += mat[r][c]; } System.out.print("Column " + c + " has an "); if (col_sum % 2 == 0) { System.out.print("even"); } else { System.out.print("odd"); } System.out.println(" number of ones."); } } }
package controller; import com.alibaba.fastjson.JSON; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpRequest; import org.springframework.http.ResponseEntity; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.util.*; /** * Created by aoineko on 2018/8/8. */ public class BlogControllerTests { private static RestTemplate restTemplate; public static final String baseUrl = "http://127.0.0.1:8090/"; @BeforeClass public static void init() { restTemplate = new RestTemplate(); List<ClientHttpRequestInterceptor> res = restTemplate.getInterceptors(); ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpHeaders httpHeaders =request.getHeaders(); httpHeaders.set("Authorization", "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJhb2luZWtvIiwidXNlck5hbWUiOiJ0ZXN0IiwiZXhwIjoxNTM0NjA5MjQ0LCJpYXQiOjE1MzQxNzcyNDR9.aux4u3Z6U7Z1OqDP0yi2tSi9kbmHC9tpgdzXASmXGqSUS4s1oPIH4Vj6lphUDXFV944N174i9_byptKeAlY_YHLJJdZRLWPGPX9zswz41WdI4696L0-H3aPw5eJKdqEDTDV4VK2WQLlzhu8LLPbDjKeeAcD_R6SC0waaHUDltjERCNuQvqqR4N4EZJv3skj2lNPBCJOGe5UKH6iGWOFcjyfkzLYYF0bXlD3TElPSog8Qy6H2ei2pV6CT2QkQNgnBKlrgRIs0iFq9MHKuB--TPrtaBfkw3YTkH683jW3EuUX0X4TWyqLiISD4wisd5FgeSljfRXhWKvgVQO8apLYZug"); return execution.execute(request, body); } }; res.add(interceptor); restTemplate.setInterceptors(res); } @Test public void testDayList() { Calendar calendar = Calendar.getInstance(); calendar.set(2018,5, 11, 1, 11); Map<String, String> param = new HashMap(); param.put("t", String.valueOf(calendar.getTimeInMillis())); param.put("tz", "8"); ResponseEntity res = restTemplate.getForEntity(baseUrl + "post/day/list?t={t}&tz={tz}", String.class, param); System.out.println(JSON.toJSONString(res.getBody())); } @Test public void testMonthList() { Calendar calendar = Calendar.getInstance(); calendar.set(2018,5, 11, 1, 11); Map<String, String> param = new HashMap(); param.put("t", String.valueOf(calendar.getTimeInMillis())); param.put("tz", "8"); ResponseEntity res = restTemplate.getForEntity(baseUrl + "post/month/list?t={t}&tz={tz}", String.class, param); System.out.println(JSON.toJSONString(res.getBody())); } }
package br.com.tiagoluzs.ulbragastos; import androidx.appcompat.app.AppCompatActivity; import androidx.constraintlayout.widget.ConstraintLayout; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Toast; import java.text.NumberFormat; import java.text.SimpleDateFormat; import br.com.tiagoluzs.ulbragastos.bean.Gasto; import br.com.tiagoluzs.ulbragastos.dao.GastoDao; public class GastoEditActivity extends AppCompatActivity { Button btnCancelar; Button btnSalvar; Button btnExcluir; EditText txtDescricao; EditText txtValor; EditText txtData; RadioButton radEntrada; RadioButton radSaida; RadioGroup radioGroup; Gasto gasto; ConstraintLayout layout; private float getFloatValue(EditText field) throws Exception { NumberFormat nf = NumberFormat.getCurrencyInstance(); String val = field.getText().toString(); return nf.parse(val).floatValue(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gasto_edit); txtValor = findViewById(R.id.txtValor); txtDescricao = findViewById(R.id.txtDescricao); txtData = findViewById(R.id.txtData); radioGroup = findViewById(R.id.radioGroup); radEntrada = findViewById(R.id.radEntrada); radSaida = findViewById(R.id.radSaida); layout = findViewById(R.id.layout); txtValor.addTextChangedListener(new MoneyMask(txtValor)); this.btnCancelar = findViewById(R.id.btnCancelar); this.btnSalvar = findViewById(R.id.btnSalvar); this.btnExcluir = findViewById(R.id.btnExcluir); this.btnExcluir.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { excluir(); } }); this.btnCancelar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); this.btnSalvar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { salvar(); } }); if(getIntent().getParcelableExtra("gasto") != null) { this.gasto = getIntent().getParcelableExtra("gasto"); } else { this.gasto = new Gasto(); } SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); this.txtData.setText(sdf.format(this.gasto.getData())); this.txtDescricao.setText(this.gasto.getDescricao()); this.txtValor.setText(NumberFormat.getCurrencyInstance().format(this.gasto.getValor())); this.radEntrada.setChecked(this.gasto.getTipo() == Gasto.ENTRADA); this.radSaida.setChecked(this.gasto.getTipo() == Gasto.SAIDA); if(this.gasto.id == 0) { this.btnExcluir.setVisibility(View.INVISIBLE); } else { this.btnExcluir.setVisibility(View.VISIBLE); } layout.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { MainActivity.hideKeyboardFrom(getBaseContext(),layout); } }); } void excluir() { GastoDao dao = new GastoDao(getBaseContext()); dao.delete(this.gasto); Toast.makeText(getBaseContext(),getResources().getString(R.string.gasto_excluido),Toast.LENGTH_LONG).show(); finish(); } void salvar() { GastoDao dao = new GastoDao(getBaseContext()); if(this.radSaida.isChecked()) { gasto.setTipo(Gasto.SAIDA); } else if(this.radEntrada.isChecked()) { gasto.setTipo(Gasto.ENTRADA); } if(gasto.getTipo() != Gasto.ENTRADA && gasto.getTipo() != Gasto.SAIDA) { Toast.makeText(getBaseContext(),getResources().getString(R.string.selecione_tipo_gasto),Toast.LENGTH_LONG).show(); return; } gasto.setDescricao(txtDescricao.getText().toString()); if(gasto.getDescricao().length() <= 1) { Toast.makeText(getBaseContext(),getResources().getString(R.string.informe_descricao_gasto),Toast.LENGTH_LONG).show(); return; } SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); String dtTxt = txtData.getText().toString(); try { gasto.setData(sdf.parse(dtTxt)); Log.d("GastoEditActivity","Save() => parse " +dtTxt + " => " + gasto.getData().toString()); } catch(Exception e) { Toast.makeText(getBaseContext(),getResources().getString(R.string.formato_data_invalido),Toast.LENGTH_LONG).show(); return; } try { float valorFloat = getFloatValue(txtValor); Log.d("GastosEdit ","getFloatValue() => " + valorFloat); if(valorFloat <= 0) { Toast.makeText(getBaseContext(),getResources().getString(R.string.informe_valor_gasto),Toast.LENGTH_LONG).show(); return; } gasto.setValor(valorFloat); } catch(Exception e) { Toast.makeText(getBaseContext(),getResources().getString(R.string.informe_valor_gasto),Toast.LENGTH_LONG).show(); return; } long resultado = dao.save(gasto); if(resultado > 0) { Toast.makeText(getBaseContext(),getResources().getString(R.string.gasto_salvo),Toast.LENGTH_LONG).show(); finish(); } else { Toast.makeText(getBaseContext(),getResources().getString(R.string.gasto_salvo_erro),Toast.LENGTH_LONG).show(); } } }
/* * 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 ClasePrincipal; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; /** * * @author gcetzal */ public class Contador { public static void main(String[] args) { String nombreFich=""; File fichero = new File(nombreFich); try { BufferedReader fich = new BufferedReader(new FileReader(nombreFich)); int contadorL = 0; String linea; try{ while((linea=fich.readLine())!=null){ contadorL++; } System.out.println("El número de líneas :" + contadorL); } catch (IOException e){ e.printStackTrace(); } }catch (FileNotFoundException e){ e.printStackTrace(); } } }
package org.rs; import java.net.InetAddress; import java.net.UnknownHostException; import org.springframework.boot.Banner; import org.springframework.boot.ResourceBanner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.system.JavaVersion; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; @SpringBootApplication public class RSApplication { public static void main(String[] args) throws Exception { SpringApplication app = new SpringApplication(RSApplication.class); app.setBannerMode(Banner.Mode.OFF); app.setLogStartupInfo(true); ConfigurableApplicationContext ctx = app.run(args); ConfigurableEnvironment env = ctx.getBean(ConfigurableEnvironment.class); printInfo(env, app.getMainApplicationClass()); } /** * Print Banner */ private static void printInfo(ConfigurableEnvironment env, Class<?> main) throws UnknownHostException { Resource resource = new ClassPathResource("banner.txt"); if (resource.exists()) { String host = InetAddress.getLocalHost().getHostAddress(); Banner banner = new ResourceBanner(resource); env.getSystemProperties().put("host", host); env.getSystemProperties().put("javaVersion", JavaVersion.getJavaVersion().toString()); banner.printBanner(env, main, System.out); } } }
package io.github.ihongs; /** * 通用异常类 * * 与 HongsExemption 不同, 必须 throws * * <h3>取值范围:</h3> * <pre> * 核心: 400~999 * 框架: 1000~9999 * 用户: 10000~99999 * </pre> * * @author Hongs */ public class HongsException extends Exception implements HongsCause { public static final int COMMON = 0; public static final int NOTICE = 1; protected final HongsCurse that; public HongsException(int code, String desc, Throwable fact) { super(fact); that = new HongsCurse(code, desc, this); } public HongsException(String desc, Throwable fact) { this(0x0 , null, fact); } public HongsException(int code, Throwable fact) { this(code, null, fact); } public HongsException(int code, String desc) { this(code, desc, null); } public HongsException(Throwable fact) { this(0x0 , null, fact); } public HongsException(String desc) { this(0x0 , desc, null); } public HongsException(int code) { this(code, null, null); } @Override public int getErrno() { return that.getErrno(); } @Override public String getError() { return that.getError(); } @Override public int getState() { return that.getState(); } @Override public String getStage() { return that.getStage(); } @Override public String toString() { return that.toString(); } @Override public String getMessage() { return that.getMessage(); } @Override public String getLocalizedMessage() { return that.getLocalizedMessage(); } @Override public String getLocalizedContext() { return that.getLocalizedContext(); } @Override public String getLocalizedContent() { return that.getLocalizedContent(); } @Override public String[] getLocalizedOptions() { return that.getLocalizedOptions(); } @Override public HongsException setLocalizedContext(String lang) { that.setLocalizedContext(lang); return this; } @Override public HongsException setLocalizedContent(String term) { that.setLocalizedContent(term); return this; } @Override public HongsException setLocalizedOptions(String... opts) { that.setLocalizedOptions(opts); return this; } @Override public HongsException toException() { return this; } @Override public HongsExemption toExemption() { return new HongsExemption(this.getErrno(), this.getError(), this) .setLocalizedOptions(this.getLocalizedOptions()) .setLocalizedContext(this.getLocalizedContext()); } /** * 常规错误(无需错误代码) * @deprecated 请改用 HongsException(String, Throwable) */ public static final class Common extends HongsException { public Common(String error, Throwable cause) { super(COMMON, error,cause); } public Common(Throwable cause) { super(COMMON, cause); } public Common(String error) { super(COMMON, error); } } /** * 通告错误(无需错误代码) * @deprecated 请改用 HongsException(String, Throwable) */ public static final class Notice extends HongsException { public Notice(String error, Throwable cause) { super(NOTICE, error,cause); } public Notice(Throwable cause) { super(NOTICE, cause); } public Notice(String error) { super(NOTICE, error); } } }
package com.crunchshop.resolver.dataloader; import graphql.GraphQLException; import org.dataloader.BatchLoaderEnvironment; import org.dataloader.BatchLoaderWithContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.task.SyncTaskExecutor; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.support.TransactionTemplate; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletionStage; public abstract class BatchResolver<K, V> implements BatchLoaderWithContext<K, V> { @Autowired PlatformTransactionManager transactionManager; /** * Data loader must return matching results in the correct order that the ids were passed in. * This function should format the results of the batch query */ public abstract List<V> sortResultsInCorrectOrderAsIds(List<K> ids, Iterable matchedResults); /** * Execute the batch query with the input ids */ public abstract List executeBatchQuery(List<K> ids, BatchLoaderEnvironment environment); /** * This function is executed once all of the ids are passed into the data loader */ @Override public CompletionStage<List<V>> load(List<K> ids, BatchLoaderEnvironment environment) { TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager); return CompletableFuture.supplyAsync(() -> { /** * The code in this method executes in a transactional context. * We do this because @Transactional does not work here for some odd reason */ return transactionTemplate.execute(status -> { try { List matchingResults = executeBatchQuery(ids, environment); return sortResultsInCorrectOrderAsIds(ids, matchingResults); } catch (Exception ex) { throw new GraphQLException(ex); } }); /** * supplyAsync() will by default use CommonForkJoin thread pool. So your non-data-loader fetching * will execute on the request thread but the data loader futures will be resolved on different threads. * * This will cause LazyInitializationException when resolving fields in the graphQL schema that are lazy loaded * since the original transaction does not carry over to a different thread. * * If we pass in a new SyncTaskExecutor, the futures will be resolved on the original request thread reusing * the existing connection and running in the same transaction (therefore allowing lazy loading of entities). */ }, new SyncTaskExecutor()); } }
package f.star.iota.milk.ui.gkdgif.gif; import f.star.iota.milk.base.BaseBean; class GifBean extends BaseBean { private String url; public GifBean() { } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
package com.sunny.jvm.classfile; /** * <Description> <br> * * @author Sunny<br> * @version 1.0<br> * @taskId: <br> * @createDate 2018/09/17 15:52 <br> * @see com.sunny.jvm.classfile <br> */ public class TestClass { private int m; public int inc() { return m + 1; } }
package interfaces; /** * @author dylan * */ public interface Watch { // Subject /** * @param p */ public void setPart(Part p); /** * */ public void oilWatch(); /** * */ public void notifyObservers(); }
package com.gxtc.huchuan.ui.mine.visitor; import com.gxtc.commlibrary.BasePresenter; import com.gxtc.commlibrary.BaseUserView; import com.gxtc.commlibrary.data.BaseSource; import com.gxtc.huchuan.bean.VisitorBean; import com.gxtc.huchuan.http.ApiCallBack; import java.util.List; /** * Describe: * Created by ALing on 2017/5/18. */ public interface VisitorContract { interface View extends BaseUserView<Presenter> { void showData(List<VisitorBean> datas); void showRefreshFinish(List<VisitorBean> datas); void showUserBrowserCount(VisitorBean bean); void showLoadMore(List<VisitorBean> datas); void showNoMore(); } interface Presenter extends BasePresenter { void getData(boolean isRefresh); void getUserBrowseCount(); void loadMore(); } interface Source extends BaseSource { void getData(String token,String start, ApiCallBack<List<VisitorBean>> callBack); //获取用户访客数量接口 void getUserBrowseCount(String token,ApiCallBack<VisitorBean> callBack); } }
public class Card { public static final String[] RANK = {"A", "K","Q","J","10","9","8","7","6","5","4","3","2"}; public static final String[] SUIT = {"(Hearts)", "(Clubs)" , "(Spades)" , "(Diamonds)"}; private String rank; private String suit; public Card(String suit , String rank){ this.suit = suit; this.rank = rank; } public Card(){ this.suit = ""; this.rank = ""; } public int compareTo(Object other){ Card otherCard = (Card) other; return this.getRankValue() - otherCard.getRankValue(); } public int getRankValue(){ for (int i = 0; i < RANK.length; i++) { if (rank.equals(RANK[i])){ return 14 - i; } else{ return -1; } } return -1; } public String getSuit(){ return this.suit; } public String getRank(){ return this.rank; } public String toString(){ String result = ""; result += this.rank + this.suit; return result; } public void setRank(String rank){ this.rank = rank; } public void setSuit(String suit) { this.suit = suit; } }
package com.rednovo.ace.core.video; import android.annotation.SuppressLint; import android.content.Context; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioRecord; import android.media.MediaRecorder; import android.media.audiofx.AcousticEchoCanceler; import android.media.audiofx.AudioEffect; import android.os.Process; import com.seu.magicfilter.utils.AudioUtils; import com.seu.magicfilter.utils.Logger; @SuppressLint("NewApi") public class AceAudioRecord { private static final String TAG = "AceAudioRecord"; private static final int CALLBACK_BUFFER_SIZE_MS = 10; private static final int BUFFERS_PER_SECOND = 1000 / CALLBACK_BUFFER_SIZE_MS; // private final int framesPerBuffer; private final int sampleRate; private final AudioManager audioManager; private final Context mContext; private AudioRecord audioRecord = null; private AudioRecordThread audioThread = null; private AcousticEchoCanceler aec = null; private boolean useBuiltInAEC = false; private NovoAVEngine novoAVEngine; private class AudioRecordThread extends Thread { private volatile boolean keepAlive = true; public AudioRecordThread(String name) { super(name); initRecording(sampleRate); enableBuiltInAEC(true); } @Override public void run() { Process.setThreadPriority(Process.THREAD_PRIORITY_URGENT_AUDIO); Logd("AudioRecordThread" + AudioUtils.getThreadInfo()); // 计算20ms的音频采样数 int iSamples = novoAVEngine.GetRequiredAudioSamples();// 1024;//20*frequency/1000; int iBufsize = iSamples * 2; byte[] buffer = new byte[iBufsize]; try { audioRecord.startRecording(); } catch (IllegalStateException e) { Loge("AudioRecord.startRecording failed: " + e.getMessage()); keepAlive = false; } while (keepAlive) { int bytesRead = audioRecord.read(buffer, 0, iBufsize); if (bytesRead == AudioRecord.ERROR_INVALID_OPERATION) { keepAlive = false; // 用户权限被禁掉,会走此处 Loge("read() returned AudioRecord.ERROR_INVALID_OPERATION"); break; } else if (bytesRead == AudioRecord.ERROR_BAD_VALUE) { keepAlive = false; Loge("read() returned AudioRecord.ERROR_BAD_VALUE"); break; } else if (bytesRead == AudioRecord.ERROR_INVALID_OPERATION) { keepAlive = false; Loge("read() returned AudioRecord.ERROR_INVALID_OPERATION"); break; } Logd("encodeAudio before"); try { if (novoAVEngine != null) { byte[] tmpBuf = new byte[bytesRead]; System.arraycopy(buffer, 0, tmpBuf, 0, bytesRead); novoAVEngine.encodeAudio(tmpBuf); Logd("encodeAudio after"); } } catch (Exception ex) { Loge("encodeAudio error"); keepAlive = false; break; } Logd("encodeAudio done"); } try { if (audioRecord != null) { audioRecord.stop(); Logd("audioRecord stop"); } } catch (IllegalStateException e) { Loge("AudioRecord.stop failed: " + e.getMessage()); } Logd("run end"); } public void joinThread() { keepAlive = false; interrupt(); // while (isAlive()) { // try { // join(); // } catch (InterruptedException e) { // // Ignore. // } // } } } public AceAudioRecord(Context context, NovoAVEngine mNovoAVEngine) { this.novoAVEngine = mNovoAVEngine; Logd("ctor" + AudioUtils.getThreadInfo()); this.mContext = context; audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); sampleRate = getNativeSampleRate(); // framesPerBuffer = sampleRate / BUFFERS_PER_SECOND; } private int getNativeSampleRate() { return AudioUtils.getNativeSampleRate(audioManager); } public static boolean builtInAECIsAvailable() { if (!AudioUtils.runningOnJellyBeanOrHigher()) { return false; } return AcousticEchoCanceler.isAvailable(); } private boolean enableBuiltInAEC(boolean enable) { // AcousticEchoCanceler was added in API level 16 (Jelly Bean). if (!AudioUtils.runningOnJellyBeanOrHigher()) { return false; } // Store the AEC state. useBuiltInAEC = enable; // Set AEC state if AEC has already been created. if (aec != null) { int ret = aec.setEnabled(enable); if (ret != AudioEffect.SUCCESS) { Loge("AcousticEchoCanceler.setEnabled failed"); return false; } Logd("AcousticEchoCanceler.getEnabled: " + aec.getEnabled()); } return true; } public void initRecording(int sampleRate) { int minBufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); if (aec != null) { aec.release(); aec = null; } try { if (audioRecord == null) { int recBufSize = minBufferSize * 2; audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, sampleRate, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, recBufSize); } } catch (IllegalArgumentException e) { Logd(e.getMessage()); } assertTrue(audioRecord.getState() == AudioRecord.STATE_INITIALIZED); if (builtInAECIsAvailable()) { // return framesPerBuffer; aec = AcousticEchoCanceler.create(audioRecord.getAudioSessionId()); if (aec != null) { int ret = aec.setEnabled(useBuiltInAEC); if (ret == AudioEffect.SUCCESS) { AudioEffect.Descriptor descriptor = aec.getDescriptor(); Logd("AcousticEchoCanceler " + "name: " + descriptor.name + ", " + "implementor: " + descriptor.implementor + ", " + "uuid: " + descriptor.uuid); Logd("AcousticEchoCanceler.getEnabled: " + aec.getEnabled()); } else { Loge("AcousticEchoCanceler.setEnabled failed"); } } else { Loge("AcousticEchoCanceler.create failed"); } } // return framesPerBuffer; } public boolean startRecording() { Logd("StartRecording"); if (audioThread == null) { audioThread = new AudioRecordThread("AudioRecordJavaThread"); audioThread.start(); return true; } return false; } public boolean stopRecording() { Logd("StopRecording"); if (audioThread != null) { audioThread.joinThread(); audioThread = null; if (aec != null) { aec.release(); aec = null; } audioRecord.release(); audioRecord = null; return true; } return false; } /** * Helper method which throws an exception when an assertion has failed. */ private static void assertTrue(boolean condition) { if (!condition) { throw new AssertionError("Expected condition to be true"); } } private static void Logd(String msg) { Logger.d(TAG, msg); } private static void Loge(String msg) { Logger.e(TAG, msg); } }
package com.myvodafone.android.business.managers; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import com.myvodafone.android.R; import com.myvodafone.android.business.Errors; import com.myvodafone.android.business.SSPTUserStatus; import com.myvodafone.android.front.netperform.NPUtils; import com.myvodafone.android.model.business.VFAccount; import com.myvodafone.android.model.business.VFHomeAccount; import com.myvodafone.android.model.business.VFMobileAccount; import com.myvodafone.android.model.business.VFMobileXGAccount; import com.myvodafone.android.model.service.Login; import com.myvodafone.android.model.service.MyAccount; import com.myvodafone.android.model.service.RegistrationOption; import com.myvodafone.android.model.service.UserTypeSmartResponse; import com.myvodafone.android.model.service.fixed.ConfigurationInfo; import com.myvodafone.android.model.service.fixed.HOLResponse; import com.myvodafone.android.model.service.fixed.SubmitAuthenticationByCookieIdResponse; import com.myvodafone.android.model.service.fixed.SubmitAuthenticationResponse; import com.myvodafone.android.model.service.fixed.SubmitUserConsentResponse; import com.myvodafone.android.model.view.VFModelFXLAccount; import com.myvodafone.android.service.DataHandler; import com.myvodafone.android.service.FXLDataParser; import com.myvodafone.android.service.FXLWLResponseListenerImpl; import com.myvodafone.android.service.WorklightClientManager; import com.myvodafone.android.utils.StaticTools; import com.myvodafone.android.utils.UrbanHelper; import com.myvodafone.android.utils.VFPreferences; import com.worklight.wlclient.api.WLFailResponse; import com.worklight.wlclient.api.WLResponse; import com.worklight.wlclient.api.WLResponseListener; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.concurrent.Executor; /** * Created by kakaso on 10/29/2015. */ public class ProfileManager { private static final String CONSENT_TAG = "VodafoneApp"; public interface ProfileListener { void onSuccessProfile(VFAccount vfAccount); void onConsent(String cookieId, VFAccount model); void onErrorProfile(String message, VFAccount model); void onErrorCredentials(String message, VFAccount model); void onGenericErrorProfile(int errorCode, VFAccount model); void onAuthError(VFAccount model); } public interface RegisterListener { void onSuccessRegisterOptions(); void onErrorRegisterOptions(int errorCode); } public interface UserTypeListener{ void onSuccessUserType(UserTypeSmartResponse userTypeSmartResponse); void onErrorUserType(String message); void onGenericErrorUserType(int errorCode); } static ProfileManager.ProfileListener profileListener; public static void login(final Context ctx, final VFAccount model, final WeakReference<ProfileListener> callback, boolean fromWidget) { if (model.getAccountType() == VFAccount.TYPE_MOBILE) { loginMobile(ctx, model, callback, fromWidget); } else if (model.getAccountType() == VFAccount.TYPE_FIXED_LINE) { if (!WorklightClientManager.isInitialized() || !StaticTools.isWorklightInitSuccees()) { WorklightClientManager.initializeConnection(new WLResponseListener() { @Override public void onSuccess(WLResponse wlResponse) { StaticTools.setIsWorklightInitSuccees(true); if(model instanceof VFHomeAccount) loginFixedLine(ctx, (VFHomeAccount) model, callback); } @Override public void onFailure(WLFailResponse wlFailResponse) { StaticTools.setIsWorklightInitSuccees(false); ProfileListener profileRunnable = callback.get(); if (profileRunnable != null) { profileRunnable.onGenericErrorProfile(Errors.ERROR_NO_INTERNET, model); } StaticTools.Log("WLClient failed to initialize: " + wlFailResponse.getErrorMsg()); } }, ctx); } else { if(model instanceof VFHomeAccount) loginFixedLine(ctx, (VFHomeAccount) model, callback); } } } private static void loginMobile(final Context ctx, final VFAccount model, final WeakReference<ProfileListener> callback, final boolean fromWidget) { final AsyncTask<Void, Void, Void> asyncTask = new AsyncTask<Void, Void, Void>() { Login response = null; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { response = DataHandler.wb_login(model.getUsername(), model.getPassword(), false, ctx); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); ProfileListener profileRunnable = callback.get(); if (response != null) { if (profileRunnable != null) { if (response.getError().contains("not") || response.getErrordescen().toLowerCase().contains("invalid")) { profileRunnable.onErrorCredentials(response.getErrordesc(), model); } else if (response.getAuthenticate().equals("false") || response.getAuthenticate().equals("0")) { profileRunnable.onErrorProfile(response.getErrordesc(), model); } else if (response.getError().equals("-1")) { String error = checkLoginMobileErrors(response); if(!error.equals("")){ profileRunnable.onErrorProfile(error, model); } else{ profileRunnable.onGenericErrorProfile(Errors.ERROR_NO_INTERNET, model); } } else { model.setAccountSegment(getMobileAccountSegment(response.getUserType())); ((VFMobileAccount)model).setMobileAccount(response); //TODO: Phase 2:Proper handle multiple accounts // if(MemoryCacheManager.getSelectedAccount()!=null && MemoryCacheManager.getSelectedAccount().getAccountType() == VFAccount.TYPE_MOBILE) { // MemoryCacheManager.setSelectedAccount(null); // } //Access rights are handled later on // if (StaticTools.isBizAdmin(model)) { // if (!StaticTools.hasPermission(response.getVopRoles(), PaymentsManager.VR_EBPP_ACCESS) // && !StaticTools.hasPermission(response.getVopRoles(), PaymentsManager.VR_ECARE_ACCESS)) { // //TODO: handle this!! // profileRunnable.onErrorProfile("Biz admin with no access rights", model); // return; // } // } if (!fromWidget) { ProfileManager.replaceAccount(model); MemoryCacheManager.storeProfile(); UrbanHelper.updateUrbanMsisdn(ctx, model); } profileRunnable.onSuccessProfile(model); } } } else { if (profileRunnable != null) { profileRunnable.onGenericErrorProfile(Errors.ERROR_NO_INTERNET, model); } } } }; asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } public static int getMobileAccountSegment(String segment){ if(segment.equalsIgnoreCase("POST")){ return VFAccount.TYPE_MOBILE_POSTPAY; } else if(segment.equalsIgnoreCase("PRE")) { return VFAccount.TYPE_MOBILE_PREPAY; } else if(segment.equalsIgnoreCase("BIZ")){ return VFAccount.TYPE_MOBILE_BIZ; } return 0; } private static String checkLoginMobileErrors(Login response){ String error = ""; if (response.getErrordesc().contains("any")) { if(!response.getLogin_errordesc().contains("any")) { error = response.getLogin_errordesc(); } } else{ error = response.getErrordesc(); } return error; } private static void loginFixedLine(final Context ctx, final VFHomeAccount model, final WeakReference<ProfileListener> callback) { final String cookieId = VFPreferences.getCookieId(model.getUsername()); loginFixedUsingCookieId(ctx, model, callback, cookieId); } private static void getFXLConfiguration(Context ctx, final WeakReference<ProfileListener> callback, final VFAccount model) { final FXLWLResponseListenerImpl wlResponseListener = new FXLWLResponseListenerImpl() { @Override public void onSuccess(WLResponse wlResponse) { super.onSuccess(wlResponse); ConfigurationInfo configurationInfo = FXLDataParser.parseConfigurationInfo(wlResponse.getResponseJSON().toString()); ProfileListener profileListener = null; if (callback != null) { profileListener = callback.get(); if (configurationInfo.getIsSuccessful()) { if (configurationInfo.getResultSet() != null) { for (int i = 0; i < configurationInfo.getResultSet().size(); i++) { if (configurationInfo.getResultSet().get(i).getConfiguratioon_Key().equals("eTroubleshooting_Last_Update")) { String configValue = configurationInfo.getResultSet().get(i).getConfiguratioon_Value(); if (!VFPreferences.getTroubleshootingUpdateTimestamp().equals(configValue)) { VFPreferences.setTroubleshootingUpdateTimestamp(configValue); StaticTools.setTroubleshootingDataUpdateFound(true); StaticTools.Log("---> TROUBLESHOOTING DATA UPDATE FOUND!!!! -----"); } else { StaticTools.Log("---> TROUBLESHOOTING DATA NO UPDATE!!!! -----"); } break; } } StaticTools.setHasGotFXLConfig(true); } } else{ StaticTools.setHasGotFXLConfig(false); } if (profileListener != null) { profileListener.onSuccessProfile(model); } } } @Override public void onFailure(WLFailResponse wlFailResponse) { super.onFailure(wlFailResponse); StaticTools.setHasGotFXLConfig(false); ProfileListener profileListener; if (callback != null) { profileListener = callback.get(); if (profileListener != null) { profileListener.onGenericErrorProfile(Errors.ERROR_FIXED_LINE_CONFIG, model); } } } @Override public void onSessionTimeout() { StaticTools.setHasGotFXLConfig(false); ProfileListener profileListener; if (callback != null) { profileListener = callback.get(); if (profileListener != null) { profileListener.onGenericErrorProfile(Errors.ERROR_FIXED_LINE_CONFIG, model); } } } }; WorklightClientManager.getConfigurationInfo(null, (Activity) ctx, wlResponseListener); } private static void loginFixedUsingCookieId(final Context ctx, final VFHomeAccount model, final WeakReference<ProfileListener> callback, final String cookieId) { boolean isCookieInvalid = cookieId == null || "".equals(cookieId); final String finalCookieId = isCookieInvalid ? StaticTools.generateFXLRandomCookieId() : cookieId; FXLWLResponseListenerImpl worklightCookieListener = new FXLWLResponseListenerImpl() { @Override public void onSuccess(final WLResponse response) { super.onSuccess(response); final SubmitAuthenticationByCookieIdResponse result = FXLDataParser.parseSubmitAuthenticationByCookieIdResponse(response.getResponseJSON().toString()); final ProfileListener profileListener = getCallback(callback); if (result != null && profileListener != null) { if (checkCookieExpiration(result)) { handleFxlLogin(result, callback, ctx, model, finalCookieId); } else { handleAuthError(ctx, profileListener, new Runnable() { @Override public void run() { profileListener.onSuccessProfile(model); } }); } } else if (profileListener != null){ profileListener.onGenericErrorProfile(Errors.ERROR_NO_INTERNET, model); } } @Override public void onFailure(WLFailResponse wlFailResponse) { super.onFailure(wlFailResponse); ProfileListener profileRunnable = callback.get(); if (profileRunnable != null) { profileRunnable.onGenericErrorProfile(Errors.ERROR_NO_INTERNET, model); } } @Override public void onSessionTimeout() { ProfileListener profileRunnable = callback.get(); if (profileRunnable != null) { profileRunnable.onGenericErrorProfile(Errors.ERROR_NO_INTERNET, model); } } }; FXLWLResponseListenerImpl worklightListener = new FXLWLResponseListenerImpl() { @Override public void onSuccess(final WLResponse response) { super.onSuccess(response); final SubmitAuthenticationByCookieIdResponse result = FXLDataParser.parseSubmitAuthenticationByCookieIdResponse(response.getResponseJSON().toString()); final ProfileListener profileListener = getCallback(callback); if (result != null && profileListener != null) { handleFxlLogin(result, callback, ctx, model, finalCookieId); } else if (profileListener != null){ profileListener.onGenericErrorProfile(Errors.ERROR_NO_INTERNET, model); } } @Override public void onFailure(WLFailResponse wlFailResponse) { super.onFailure(wlFailResponse); ProfileListener profileRunnable = callback.get(); if (profileRunnable != null) { profileRunnable.onGenericErrorProfile(Errors.ERROR_NO_INTERNET, model); } } @Override public void onSessionTimeout() { ProfileListener profileRunnable = callback.get(); if (profileRunnable != null) { profileRunnable.onGenericErrorProfile(Errors.ERROR_NO_INTERNET, model); } } }; if (isCookieInvalid) { String[] loginParameters = new String[]{model.getUsername(), model.getPassword(), "true", finalCookieId}; WorklightClientManager.submitAuthentication(loginParameters, (Activity) ctx, worklightListener); } else { WorklightClientManager.submitAuthenticationByCookieId(new String[]{model.getUsername(), finalCookieId}, (Activity) ctx, worklightCookieListener); } } private static void handleFxlLogin(SubmitAuthenticationByCookieIdResponse result, WeakReference<ProfileListener> callback, Context ctx, VFHomeAccount model, String cookieId) { ProfileListener profileListener = getCallback(callback); if (result.getErrorMessage() != null && !result.getErrorMessage().equals("")) { handleFXLError(profileListener, result.getErrorMessage(), ctx, model); } else if (result.getIsSuccessful() && !result.isAuthRequired()) { if (!result.getVodafoneAppConsensus()) { MemoryCacheManager.setTempAccount(model); profileListener.onConsent(cookieId, model); } else { handleFixedLineResult(result, model, profileListener, ctx); if (model != null) { VFPreferences.setCookieId(model.getUsername(), cookieId); if (!StaticTools.hasGotFXLConfig()) { getFXLConfiguration(ctx, callback, model); } else { profileListener.onSuccessProfile(model); } } } } } private static void handleFixedLineResult(SubmitAuthenticationByCookieIdResponse result, VFHomeAccount model, ProfileListener profileListener, Context ctx) { if (result.getIsSuccessful() && (!result.isAuthRequired() || result.getAuthorized() || result.isUserAuthenticated())) { model.setHomeAccount(result); //TODO: Phase 2:Proper handle multiple accounts /* if(MemoryCacheManager.getSelectedAccount()!=null && MemoryCacheManager.getSelectedAccount().getAccountType() == VFAccount.TYPE_FIXED_LINE) { MemoryCacheManager.setSelectedAccount(null); } */ ProfileManager.replaceAccount(model); MemoryCacheManager.storeProfile(); } else { handleFXLError(profileListener, result.getErrorMessage(), ctx, model); } } private static void handleFXLError(ProfileListener profileListener, String servMessage, Context ctx, VFAccount model) { String message = ctx.getString(R.string.vf_generic_error); try { message = StaticTools.getStringResourceByName(ctx, servMessage); } catch (Exception e) { StaticTools.Log(e); } if (profileListener != null) { if (StaticTools.equals(servMessage, "ECARE_USER_WRONG_PWD")) { profileListener.onErrorCredentials(message, model); } else { profileListener.onErrorProfile(message, model); } } } public static void replaceAccount(VFAccount account) { int accountType = account.getAccountType(); for (int i = MemoryCacheManager.getProfile().getAccountList().size() - 1; i >= 0; i--) { if (MemoryCacheManager.getProfile().getAccountList().get(i).getAccountType() == accountType) { MemoryCacheManager.getProfile().getAccountList().remove(i); } } MemoryCacheManager.getProfile().getAccountList().add(account); } public static void getRegistrationOptions(final Context context, final WeakReference<RegisterListener> callback) { final AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() { ArrayList<RegistrationOption> response; @Override protected String doInBackground(Void... params) { if (VFPreferences.getRegisterScreen().equals("")) { response = DataHandler.wb_getRegisterScreen(context); return ""; } else { StaticTools.Log("Registration Options: NO UPDATE"); return "no_update"; } } @Override protected void onPostExecute(String result) { super.onPostExecute(result); RegisterListener registerRunnable = callback.get(); if (registerRunnable != null) { if (result.equals("")) { if (response == null) { registerRunnable.onErrorRegisterOptions(Errors.ERROR_NO_INTERNET); } else { registerRunnable.onSuccessRegisterOptions(); } } else { registerRunnable.onSuccessRegisterOptions(); } } } }; asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } public static void submitFXLConsent(final Context context, final VFHomeAccount account, final WeakReference<ProfileListener> callback, final String cookieId){ String[] params = { account.getUsername(), "true", CONSENT_TAG}; WorklightClientManager.submitUserConsent(params, (Activity) context, new FXLWLResponseListenerImpl() { @Override public void onSuccess(WLResponse response) { super.onSuccess(response); SubmitUserConsentResponse result = FXLDataParser.parseSubmitUserConsentResponse(response.getResponseJSON().toString()); if (result.getIsSuccessful()) { VFPreferences.setCookieId(account.getUsername(), cookieId); loginFixedUsingCookieId(context, account, callback, cookieId); } else { if (callback != null) { ProfileListener profileListener = callback.get(); profileListener.onGenericErrorProfile(Errors.ERROR_NO_INTERNET, account); } } } @Override public void onFailure(WLFailResponse wlFailResponse) { super.onFailure(wlFailResponse); if (callback != null) { ProfileListener profileListener = callback.get(); profileListener.onGenericErrorProfile(Errors.ERROR_NO_INTERNET, account); } } @Override public void onSessionTimeout() { if (callback != null) { ProfileListener profileListener = callback.get(); profileListener.onGenericErrorProfile(Errors.ERROR_NO_INTERNET, account); } } }); } public static void getUserType(final Context context, final VFAccount account, final boolean checkSmartType, final boolean fromWidget, final boolean forceWP, final WeakReference<UserTypeListener> callback) { String msisdn = StaticTools.getAccountMsisdn(account); getUserType(context,account,msisdn,checkSmartType,fromWidget,forceWP,callback); } public static void getUserType(final Context context, final VFAccount account,final String msisdn, final boolean checkSmartType, final boolean fromWidget, final boolean forceWP, final WeakReference<UserTypeListener> callback){ getUserType(context,account,msisdn,checkSmartType,fromWidget,forceWP,callback,null); } public static void getUserType(final Context context, final VFAccount account,final String msisdn, final boolean checkSmartType, final boolean fromWidget, final boolean forceWP, final WeakReference<UserTypeListener> callback, Executor executor){ AsyncTask<Void,Void,Void> asyncTask = new AsyncTask<Void, Void, Void>() { UserTypeSmartResponse userTypeSmartResponse; String taxNumber; @Override protected Void doInBackground(Void... params) { if (StaticTools.isBizAdmin(account)) { taxNumber = MemoryCacheManager.getSelectedBizMsisdn(); } else if (account instanceof VFMobileAccount && ((VFMobileAccount) account).getMobileAccount() != null) { taxNumber = ((VFMobileAccount) account).getMobileAccount().getTaxnumber(); } else if (account instanceof VFMobileXGAccount && ((VFMobileXGAccount) account).getMobileAccount() != null) { taxNumber = ((VFMobileXGAccount) account).getMobileAccount().getTaxnumber(); } else { taxNumber = ""; } userTypeSmartResponse = DataHandler.wb_getUserTypeSmart(account.getUsername(), account.getPassword(),msisdn, taxNumber, checkSmartType?"true":"false",context,false, forceWP); //@ADDEDBYNEHALEM// //userTypeSmartResponse.clearSmartInfo(); // userTypeSmartResponse.setSmartInfo("PT"); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); UserTypeListener userTypeRunnable = null; if(callback!=null) { userTypeRunnable = callback.get(); } if(userTypeSmartResponse!=null){ if(userTypeSmartResponse.hasError()){ if(userTypeRunnable!=null) userTypeRunnable.onErrorUserType(userTypeSmartResponse.getLocalError()); } else { if (checkSmartType) { SSPTUserStatus status = new SSPTUserStatus("", userTypeSmartResponse.getSmartInfo(), StaticTools.getDateFormat().format(GregorianCalendar.getInstance().getTime()), StaticTools.isNullOrEmpty(userTypeSmartResponse.getTaxnumber()) ? taxNumber : userTypeSmartResponse.getTaxnumber()); if (userTypeSmartResponse.getMsisdn() != null && userTypeSmartResponse.getMsisdn().length() > 0) { status.setMsisdn3g(userTypeSmartResponse.getMsisdn()); } if (account instanceof VFMobileAccount) { status.setUsername(account.getUsername()); } SSPTUserStatus.addSSPTUserStatus(status); } if (!fromWidget) { MemoryCacheManager.getProfile().clearMobileXGAccounts(); if (!checkMobileXGAccountExists(userTypeSmartResponse.getMsisdn())) { if(account instanceof VFMobileXGAccount) { ((VFMobileXGAccount) account).setMobileAccount(userTypeSmartResponse); account.setAccountType(VFAccount.TYPE_MOBILE_VF3G); account.setAccountSegment(getMobileAccountSegment(userTypeSmartResponse.getUserType())); replaceAccount(account); NPUtils.updateNetPerformLoggedMsisdn(account); UrbanHelper.updateUrbanMsisdn(context, account); } } } if (userTypeRunnable != null) userTypeRunnable.onSuccessUserType(userTypeSmartResponse); } } else{ if(userTypeRunnable!=null) userTypeRunnable.onGenericErrorUserType(Errors.ERROR_NO_INTERNET); } } }; if(executor == null) { asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { asyncTask.executeOnExecutor(executor); } } private static boolean checkMobileXGAccountExists(String msisdn){ for (VFMobileAccount account: MemoryCacheManager.getProfile().getListLoginMobile()){ if(account.getMobileAccount()!=null && account.getMobileAccount().getMsisdn().equals(msisdn)){ return true; } } return false; } protected static void handleAuthError(final Context context, final ProfileListener callback, final Runnable runnable){ profileListener = new ProfileManager.ProfileListener() { @Override public void onSuccessProfile(VFAccount model) { runnable.run(); } @Override public void onConsent(String cookieId, VFAccount model) { if(callback!=null) callback.onAuthError(model); } @Override public void onErrorProfile(String message, VFAccount model) { if(callback!=null) callback.onAuthError(model); } @Override public void onErrorCredentials(String message, VFAccount model) { if(callback!=null) callback.onAuthError(model); } @Override public void onGenericErrorProfile(int errorCode, VFAccount model) { if(callback!=null) callback.onGenericErrorProfile(errorCode, model); } @Override public void onAuthError(VFAccount model) { if(callback!=null) callback.onAuthError(model); } }; final VFHomeAccount model = MemoryCacheManager.getProfile().getActiveLoginHome(); if(model!=null) { VFPreferences.setCookieId(model.getUsername(), ""); StaticTools.setIsWorklightInitSuccees(false); ProfileManager.login(context, model, new WeakReference<ProfileManager.ProfileListener>(profileListener), false); } } protected static boolean checkCookieExpiration(SubmitAuthenticationByCookieIdResponse response) { boolean result = false; if(response.getCustomer() != null && response.getCustomer().getCustomerAccount() != null) { result = true; } else { StaticTools.Log("FXL", "----Authentication Error - ReLogin"); result = false; } return result; } protected static <T> T getCallback(WeakReference<T> reference){ if(reference!=null){ return reference.get(); } else{ return null; } } }
package SocialService; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import Entities.User; import Resources.SpringConfiguration; public class SoapUserGet { public String getUser(Integer userID) { ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfiguration.class); SocialService service = ctx.getBean(SocialService.class); User result = service.getUser(userID); try { JAXBContext context = JAXBContext.newInstance(User.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); m.setProperty(Marshaller.JAXB_ENCODING, "UTF-8"); java.io.StringWriter sw = new StringWriter(); m.marshal(result, sw); ((AnnotationConfigApplicationContext)ctx).close(); return sw.toString(); } catch (JAXBException e) { e.printStackTrace(); ((AnnotationConfigApplicationContext)ctx).close(); return e.getMessage(); } } }
package archive.tool.core; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class FileUtil { /** * * @param is InputStream. * @param os OutputStream. * @throws IOException While read/write */ public static void write(InputStream is, OutputStream os) throws IOException { int len; byte[] buffer = new byte[1024]; while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); } } }
package src; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.regex.Pattern; public class Persona { private String nombre; private String apellidos; private String dni; private List<String> mails = new ArrayList<>(); private List<String> telefonos = new ArrayList<>(); private List<String> errores = new ArrayList<>(); public static final String ERROR_DNI = " Posicion %d: %s no es un DNI"; public static final String ERROR_NO_ES_TELEFONO_NI_EMAIL = "Posicion %d: %s no es ni un teléfono ni un email"; public static final String ERROR_EMAIL_REPETIDO = "Posicion %d: El email %s está repetido"; public static final String ERROR_TELEFONO_REPETIDO = "Posicion %d: El telefono %s está repetido"; private Pattern _dni_expresionRegular = Pattern.compile("[XYxy]?[0-9]{1,9}[A-Za-z]$"); Pattern _telefono_expresionRegular = Pattern.compile("^\\+?[0-9]*(\\([0-9]+\\))*[0-9]+$"); Pattern _email_expresionRegular = Pattern.compile("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}$"); public void leerDatos(String input) { String[] data = input.split(","); if (_dni_expresionRegular.matcher(data[0]).find()) { this.dni = data[0].trim(); } else { errores.add(String.format(ERROR_DNI, 0, data[0])); } this.nombre = data[1].replace("\"", "").trim(); this.apellidos = data[2].replace("\"", "").trim(); for (int i = 3; i < data.length; i++) { String dato = data[i].trim(); if (_email_expresionRegular.matcher(dato).find()) { dato = dato.toLowerCase(); if (mails.contains(dato)) { errores.add(String.format(ERROR_EMAIL_REPETIDO, i, dato)); } else { mails.add(dato); } } else if (_telefono_expresionRegular.matcher(dato).find()) { if (telefonos.contains(dato)) { errores.add(String.format(ERROR_TELEFONO_REPETIDO, i, dato)); } else { telefonos.add(dato); } } else { errores.add(String.format(ERROR_NO_ES_TELEFONO_NI_EMAIL, i, dato)); } } //Ordenar telefono telefonos.sort(new Comparator<String>() { @Override //<0 si arg1 va primero, >0 si arg2 va después public int compare(String arg1, String arg2) { arg1 = arg1.replace("(", "").replace(")", ""); arg2 = arg2.replace("(", "").replace(")", ""); if(arg1.startsWith("+") && !arg2.startsWith("+")){ return 1; //arg 2 va primero, porque es nacional, y arg 1 no } else if(!arg1.startsWith("+") && arg2.startsWith("+")){ return -1; //arg 1 va primero, porque es nacional, y arg 2 no } else { //Comparación inversa, para ordenarlos de mayor a menor return arg2.compareTo(arg1); } } }); } public String getNombre() { return nombre; } public String getApellidos() { return apellidos; } public String getDni() { return dni; } public List<String> getMails() { return mails; } public List<String> getTelefonos() { return telefonos; } public List<String> getErrores() { return errores; } }
package Mymember.vo; public class InterestVO { private String int_no; private String mem_id; private String a_art_no; public InterestVO() {} public InterestVO(String int_no, String mem_id, String a_art_no) { super(); this.int_no = int_no; this.mem_id = mem_id; this.a_art_no = a_art_no; } public String getInt_no() { return int_no; } public void setInt_no(String int_no) { this.int_no = int_no; } public String getMem_id() { return mem_id; } public void setMem_id(String mem_id) { this.mem_id = mem_id; } public String getA_art_no() { return a_art_no; } public void setA_art_no(String a_art_no) { this.a_art_no = a_art_no; } }
package com.zc.pivas.docteradvice.bean; import com.zc.pivas.docteradvice.entity.DoctorAdviceMain; import java.io.Serializable; import java.util.List; /** * * 医嘱主表实体类 * <功能详细描述> * * @author cacabin * @version 0.1 */ public class DoctorAdviceMainBean extends DoctorAdviceMain implements Serializable { /** * 注释内容 */ private static final long serialVersionUID = 1L; /** * 子医嘱列表 */ List<DoctorAdviceMinBean> yzList = null; public List<DoctorAdviceMinBean> getYzList() { return yzList; } public void setYzList(List<DoctorAdviceMinBean> yzList) { this.yzList = yzList; } }
package fr.skytasul.quests.utils.types; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.regex.Pattern; import org.apache.commons.lang.Validate; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Block; import org.bukkit.util.NumberConversions; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import fr.skytasul.quests.api.stages.types.Locatable; import fr.skytasul.quests.api.stages.types.Locatable.LocatedType; public class BQLocation extends Location implements Locatable.Located { private Pattern worldPattern; public BQLocation(Location bukkit) { this(bukkit.getWorld(), bukkit.getX(), bukkit.getY(), bukkit.getZ(), bukkit.getYaw(), bukkit.getPitch()); } public BQLocation(World world, double x, double y, double z) { this(world, x, y, z, 0, 0); } public BQLocation(World world, double x, double y, double z, float yaw, float pitch) { super(world, x, y, z, yaw, pitch); if (world == null) worldPattern = Pattern.compile(".*"); } public BQLocation(String worldPattern, double x, double y, double z) { this(worldPattern, x, y, z, 0, 0); } public BQLocation(String worldPattern, double x, double y, double z, float yaw, float pitch) { super(null, x, y, z, yaw, pitch); this.worldPattern = Pattern.compile(worldPattern); } public Pattern getWorldPattern() { return worldPattern; } public BQLocation setWorldPattern(Pattern worldPattern) { this.worldPattern = worldPattern; if (worldPattern != null) super.setWorld(null); return this; } @Override public void setWorld(World world) { throw new UnsupportedOperationException(); } @Override public Location getLocation() { return new Location(getWorld(), getX(), getY(), getZ()); } @Override public LocatedType getType() { return LocatedType.OTHER; } public boolean isWorld(World world) { Validate.notNull(world); if (super.getWorld() != null) return super.getWorld().equals(world); return worldPattern.matcher(world.getName()).matches(); } public String getWorldName() { return getWorld() == null ? worldPattern.pattern() : getWorld().getName(); } @Nullable public Block getMatchingBlock() { if (super.getWorld() != null) return super.getBlock(); if (worldPattern == null) return null; return Bukkit.getWorlds() .stream() .filter(world -> worldPattern.matcher(world.getName()).matches()) .findFirst() .map(world -> world.getBlockAt(getBlockX(), getBlockY(), getBlockZ())) .orElse(null); } @Override public double distanceSquared(Location o) { Validate.isTrue(isWorld(o.getWorld()), "World does not match"); return NumberConversions.square(getX() - o.getX()) + NumberConversions.square(getY() - o.getY()) + NumberConversions.square(getZ() - o.getZ()); } @Override public boolean equals(Object obj) { if (!(obj instanceof Location)) return false; Location other = (Location) obj; if (Double.doubleToLongBits(this.getX()) != Double.doubleToLongBits(other.getX())) return false; if (Double.doubleToLongBits(this.getY()) != Double.doubleToLongBits(other.getY())) return false; if (Double.doubleToLongBits(this.getZ()) != Double.doubleToLongBits(other.getZ())) return false; if (Float.floatToIntBits(this.getPitch()) != Float.floatToIntBits(other.getPitch())) return false; if (Float.floatToIntBits(this.getYaw()) != Float.floatToIntBits(other.getYaw())) return false; if (obj instanceof BQLocation) { BQLocation otherBQ = (BQLocation) obj; if (worldPattern == null) return otherBQ.worldPattern == null; if (otherBQ.worldPattern == null) return false; return worldPattern.pattern().equals(otherBQ.worldPattern.pattern()); } if (!Objects.equals(other.getWorld(), getWorld())) { if (other.getWorld() == null) return false; if (worldPattern == null) return false; return worldPattern.matcher(other.getWorld().getName()).matches(); } return true; } @Override public int hashCode() { int hash = super.hashCode(); hash = 19 * hash + (worldPattern == null ? 0 : worldPattern.pattern().hashCode()); return hash; } @Override public Map<String, Object> serialize() { Map<String, Object> map = new HashMap<>(); if (getWorld() == null) { map.put("pattern", worldPattern.pattern()); } else { map.put("world", getWorld().getName()); } // we cannot use Location#serialize() to add the following values // because on 1.8 it will throw an NPE if the world is null map.put("x", getX()); map.put("y", getY()); map.put("z", getZ()); map.put("yaw", getYaw()); map.put("pitch", getPitch()); return map; } @NotNull public static BQLocation deserialize(@NotNull Map<String, Object> args) { double x = NumberConversions.toDouble(args.get("x")); double y = NumberConversions.toDouble(args.get("y")); double z = NumberConversions.toDouble(args.get("z")); float yaw = NumberConversions.toFloat(args.get("yaw")); float pitch = NumberConversions.toFloat(args.get("pitch")); World world = null; String worldPattern = null; if (args.containsKey("world")) { String worldName = (String) args.get("world"); world = Bukkit.getWorld(worldName); if (world == null) worldPattern = Pattern.quote(worldName); }else if (args.containsKey("pattern")) { worldPattern = (String) args.get("pattern"); } if (worldPattern != null) return new BQLocation(worldPattern, x, y, z, yaw, pitch); return new BQLocation(world, x, y, z, yaw, pitch); } }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $ACTIVEEON_INITIAL_DEV$ */ package org.ow2.proactive.scheduler.util.classloading; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.Table; import org.hibernate.annotations.AccessType; import org.hibernate.annotations.Proxy; import org.hibernate.annotations.Type; import org.ow2.proactive.db.Condition; import org.ow2.proactive.db.ConditionComparator; import org.ow2.proactive.scheduler.core.db.DatabaseManager; /** * This class stores job classpathes directly in DB through {@link JobClasspathEntry} struct. * No classpath is supposed to retain in memory. */ public class JobClasspathManager { // cache for known CRC private final Set<Long> knownCRC = new HashSet<Long>(); /** * Return a jobclasspath * @param crc the key for this classpath * @return a {@link JobClasspathEntry} for this crc */ public JobClasspathEntry get(long crc) { List<JobClasspathEntry> results = DatabaseManager.getInstance().recover(JobClasspathEntry.class, new Condition("crc", ConditionComparator.EQUALS_TO, crc)); if (results.size() == 1) { this.knownCRC.add(crc); return results.get(0); } else if (results.size() != 0) { throw new IllegalStateException("CRC " + crc + " is replicated in DB. Please consider cleaning DB."); } else { return null; } } /** * Add a new job classpath in the DB * @param crc the key for this classpath * @param classpathContent the classpath content * @param containsJarFiles true if the the classpath contains jar files, false otherwhise */ public void put(long crc, byte[] classpathContent, boolean containsJarFiles) { if (!this.contains(crc)) { DatabaseManager.getInstance().register( new JobClasspathEntry(crc, classpathContent, containsJarFiles)); this.knownCRC.add(crc); } else { throw new IllegalStateException("CRC " + crc + " is replicated in DB. Please consider cleaning DB."); } } /** * Returns true if the jobclasspath identified by crc is stored, false otherwhise * @return true if the jobclasspath identified by crc is stored, false otherwhise */ public boolean contains(long crc) { // loading the classpath entry to know if it exists is costly but // it does not rely on SQL request. return this.knownCRC.contains(crc) ? true : get(crc) != null; } /** * Simple hibernatizable job classpath */ @Entity @Table(name = "JOBCP_ENTRIES") @AccessType("field") @Proxy(lazy = false) public static class JobClasspathEntry { @Id @GeneratedValue @Column(name = "ID") @SuppressWarnings("unused") private long hId; @Column(name = "CRC", unique = true) public long crc; @Column(name = "CP_CONTENT", updatable = false, length = Integer.MAX_VALUE) @Type(type = "org.ow2.proactive.scheduler.core.db.schedulerType.BinaryLargeOBject") @Lob public byte[] classpathContent; @Column(name = "CONTAINS_JAR") public boolean containsJarFiles; /** * TODO * @param crc * @param classpathContent * @param containsJarFiles */ JobClasspathEntry(long crc, byte[] classpathContent, boolean containsJarFiles) { this.crc = crc; this.classpathContent = classpathContent; this.containsJarFiles = containsJarFiles; } // for Hibernate... JobClasspathEntry() { } } }
package com.tpv.storagefiletest.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.tpv.storagefiletest.utils.MyLog; public class StorageMountReceiver extends BroadcastReceiver { StorageStateListener listener; public StorageMountReceiver(StorageStateListener listener) { super(); MyLog.i("new StorageMountReceiver."); this.listener = listener; } @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); MyLog.i("action = " + action); listener.onStorageStateChanged(); } public interface StorageStateListener { void onStorageStateChanged(); } }
package com.ccloud.oa.sms.config; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; /** * @author : breeze * @date : 2020/9/1 * @description : 阿里云短信发送专用枚举类 */ @Getter @ToString @NoArgsConstructor @AllArgsConstructor public enum SmsEnum { SMS_TEMPLATE("dysmsapi.aliyuncs.com", "2017-05-25", "SendSms", "cn-hangzhou", "团子", "SMS_180060107"); private String sysDomain; private String sysVersion; private String sysAction; private String regionId; private String signName; private String templateCode; }
package cz.i.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author jan.hadas@i.cz */ public class MathService { private static final Logger LOG = LoggerFactory.getLogger(MathService.class); public boolean isPrime(final long number) { if (number < 2) { // first prime is 2 LOG.debug("number {} is too small - NOT prime", number); return false; } final long limit = Math.round(Math.sqrt(number)); for (int divider = 2; divider < limit; divider++) { // X modulo divider is 0 (NO divide remainder) -> X is divisible by divider if (number % divider == 0) { LOG.debug("number {} is divisible by {}, NOT prime", number, divider); return false; } } LOG.debug("number {} is probably prime", number); return true; } }
package br.com.mixfiscal.prodspedxnfe.domain.enums; import br.com.mixfiscal.prodspedxnfe.domain.ex.EnumDesconhecidoException; public enum ETipoPagamento { AVista((byte)0), APrazo((byte)1), SemPagamento((byte)2); private final byte tipoPagamento; private ETipoPagamento(byte tipoPagamento) { this.tipoPagamento = tipoPagamento; } public byte getTipoPagamento() { return tipoPagamento; } public static ETipoPagamento deCodigo(String codigo) throws EnumDesconhecidoException { int iCodigo = Integer.parseInt(codigo); return deCodigo(iCodigo); } public static ETipoPagamento deCodigo(int codigo) throws EnumDesconhecidoException { for (ETipoPagamento item : ETipoPagamento.values()) { if (item.getTipoPagamento() == codigo) return item; } throw new EnumDesconhecidoException(); } }
package com.esum.web.monitor.controller; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.commons.collections.MapIterator; import org.apache.commons.collections.OrderedMap; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.esum.appetizer.controller.AbstractController; import com.esum.appetizer.exception.ErrorCode; import com.esum.appetizer.util.DateUtils; import com.esum.appetizer.util.RequestUtils; import com.esum.appetizer.vo.RestResult; import com.esum.framework.core.component.ComponentChannelStatus; import com.esum.framework.core.component.ComponentConstants; import com.esum.framework.core.component.ComponentStatus; import com.esum.framework.core.management.admin.SystemAdmin; import com.esum.framework.core.management.mbean.queue.QueueStatus; import com.esum.framework.core.management.resource.DataSourceControl; import com.esum.framework.core.monitor.MemoryStatus; import com.esum.framework.core.node.table.NodeInfo; import com.esum.web.apps.messagelog.service.MessageLogService; import com.esum.web.apps.nodeinfo.service.NodeInfoService; import com.esum.web.util.ReloadXTrusAdmin; @RestController public class MonitorRestController extends AbstractController { @Autowired private NodeInfoService nodeInfoService; @Autowired private MessageLogService messageLogService; /** * 노드별 채널 모니터링 * 현재 메인 노드별 모든 채널의 메시지 건수를 제공한다. */ @RequestMapping(value = "/rest/monitor/nodeChannelData") public RestResult nodeChannelData(HttpServletRequest request) throws Exception { try { String nodeId = request.getParameter("nodeId"); int interval = RequestUtils.getParamInt(request, "interval", 60); // sec List<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); ReloadXTrusAdmin reload = ReloadXTrusAdmin.getInstance(); List<NodeInfo> nodeInfoList = reload.getMainNodeInfoList(); // 메인 노드만 조회 for (NodeInfo nodeInfo : nodeInfoList) { if (StringUtils.isNotEmpty(nodeId) && !nodeId.equals(nodeInfo.getNodeId())) { continue; } OrderedMap statusMap = reload.getQueueStatusList(nodeInfo.getNodeId()); long messageCount = getTotalMessageCount(statusMap); boolean hasLongElapsedTime = hasLongElapsedTime(nodeInfo.getNodeId(), statusMap, interval); Map<String, Object> node = new HashMap<String, Object>(); node.put("nodeId", nodeInfo.getNodeId()); node.put("messageCount", messageCount); node.put("hasLongElapsedTime", hasLongElapsedTime); data.add(node); } return new RestResult(ErrorCode.SUCCESS, data); } catch (Exception e) { return new RestResult(e); } } // 모든 메시지 수를 구한다. private long getTotalMessageCount(OrderedMap statusMap) { long messageCount = 0; MapIterator iterator = statusMap.mapIterator(); while (iterator.hasNext()) { String statusCompId = (String) iterator.next(); List<QueueStatus> queueStatusList = (List<QueueStatus>) statusMap.get(statusCompId); for (QueueStatus queueStatus : queueStatusList) { messageCount += queueStatus.getMessageCount(); } } return messageCount; } // 처리시간이 interval 보다 오래 걸리는 메시지가 있는지 여부 private boolean hasLongElapsedTime(String nodeId, OrderedMap statusMap, int interval) { Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND, -interval); long compareTime = cal.getTimeInMillis(); MapIterator iterator = statusMap.mapIterator(); while (iterator.hasNext()) { String statusCompId = (String) iterator.next(); List<QueueStatus> queueStatusList = (List<QueueStatus>) statusMap.get(statusCompId); for (QueueStatus queueStatus : queueStatusList) { String channelName = queueStatus.getQueueName(); ComponentStatus cs = queueStatus.getComponentStatus(nodeId); if(cs==null) continue; ComponentChannelStatus channelStatus = cs.getChannelStatusAt(channelName); if (channelStatus == null || StringUtils.isEmpty(channelStatus.getLastProcessingTime()) || !ComponentConstants.MESSAGE_PROCESSING.equals(channelStatus.getCurrentProcessingStatus())) { continue; } Date lastProcessingTime = DateUtils.parse(channelStatus.getLastProcessingTime(), DateUtils.PATTERN_DB_DATETIME); if (lastProcessingTime.getTime() < compareTime) { return true; } } } return false; } /** * 컴포넌트 채널 현황 * 현재 컴포넌트별 메시지 건수를 제공한다. * - 요청 파라미터에 compId 값이 있으면, 해당 컴포넌트의 채널별 메시지 수를 제공한다. */ @RequestMapping(value = "/rest/monitor/componentChannelColumnData") public RestResult componentChannelColumnData(HttpServletRequest request) throws Exception { try { String nodeId = request.getParameter("nodeId"); String compId = request.getParameter("compId"); List<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); OrderedMap statusMap = ReloadXTrusAdmin.getInstance().getQueueStatusList(nodeId); if (StringUtils.isEmpty(compId)) { MapIterator iterator = statusMap.mapIterator(); while (iterator.hasNext()) { String statusCompId = (String)iterator.next(); List<QueueStatus> queueStatusList = (List<QueueStatus>) statusMap.get(statusCompId); int consumerCount = 0; long messageCount = 0; for (QueueStatus queueStatus : queueStatusList) { if (queueStatus.getConsumerCount() == 0) { continue; } consumerCount += queueStatus.getConsumerCount(); messageCount += queueStatus.getMessageCount(); } if (consumerCount == 0) { continue; } Map<String, Object> comp = new HashMap<String, Object>(); comp.put("compId", statusCompId); comp.put("messageCount", messageCount); data.add(comp); } } else { MapIterator iterator = statusMap.mapIterator(); while (iterator.hasNext()) { String statusCompId = (String) iterator.next(); List<QueueStatus> queueStatusList = (List<QueueStatus>) statusMap.get(statusCompId); if (!compId.equals(statusCompId)) { continue; } for (QueueStatus queueStatus : queueStatusList) { if (queueStatus.getConsumerCount() == 0) { continue; } Map<String, Object> comp = new HashMap<String, Object>(); comp.put("channelName", queueStatus.getQueueName()); comp.put("messageCount", queueStatus.getMessageCount()); data.add(comp); } break; } } return new RestResult(ErrorCode.SUCCESS, data); } catch (Exception e) { return new RestResult(e); } } /** * 노드별 DB 연결 모니터링 * 현재 노드별 DataSource 정보를 제공한다. */ @RequestMapping(value = "/rest/monitor/nodeDataSourceData") public RestResult nodeDataSourceData(HttpServletRequest request) throws Exception { try { String nodeId = request.getParameter("nodeId"); List<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); List<NodeInfo> nodeInfoList = nodeInfoService.getNodeInfoList(); for (NodeInfo nodeInfo : nodeInfoList) { if (StringUtils.isNotEmpty(nodeId) && !nodeId.equals(nodeInfo.getNodeId())) { continue; } long activeCount = 0; long idleCount = 0; DataSourceControl control = null; try { control = DataSourceControl.getControl(nodeInfo.getHostName(), nodeInfo.getPort()); activeCount = control.getNumActiveCount(null); idleCount = control.getNumIdleCount(null); } catch (Exception e) { logger.error(e.getMessage(), e); // ignore } finally { if (control != null) control.close(); } Map<String, Object> node = new HashMap<String, Object>(); node.put("nodeId", nodeInfo.getNodeId()); node.put("activeCount", activeCount); node.put("idleCount", idleCount); data.add(node); } return new RestResult(ErrorCode.SUCCESS, data); } catch (Exception e) { return new RestResult(e); } } /** * 노드별 메모리 사용률 * 현재 노드별 메모리 사용 정보를 제공한다. */ @RequestMapping(value = "/rest/monitor/nodeMemoryData") public RestResult nodeMemoryData(HttpServletRequest request) throws Exception { try { String nodeId = request.getParameter("nodeId"); List<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); List<NodeInfo> nodeInfoList = nodeInfoService.getNodeInfoList(); for (NodeInfo nodeInfo : nodeInfoList) { if (StringUtils.isNotEmpty(nodeId) && !nodeId.equals(nodeInfo.getNodeId())) { continue; } MemoryStatus memoryStatus = null; try { SystemAdmin systemAdmin = new SystemAdmin(nodeInfo.getNodeId(), nodeInfo.getHostName(), nodeInfo.getPort()); memoryStatus = systemAdmin.getMemoryStatus(); } catch (Exception e) { logger.error(e.getMessage(), e); memoryStatus = new MemoryStatus(0, 0, 0, 0, 0, 0, 0, 0); } Map<String, Object> node = new HashMap<String, Object>(); node.put("nodeId", nodeInfo.getNodeId()); node.put("memoryUsed", memoryStatus.getHeapUsed()); // 사용량 node.put("memoryMax", memoryStatus.getHeapMax()); // 최대값 data.add(node); } return new RestResult(ErrorCode.SUCCESS, data); } catch (Exception e) { return new RestResult(e); } } }
package com.jalsalabs.ticklemyphonefull; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class AntiTheftBootReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { TML_Library.Debug("Inside On Receive BootReceiver"); Intent intentx = new Intent(context.getApplicationContext(), AntiTheftBootStartActivity.class); intentx.setFlags(268435456); context.startActivity(intentx); } }
package com.yevhenchmykhun.controller; import com.yevhenchmykhun.cart.ShoppingCart; import com.yevhenchmykhun.controller.validate.Validator; import com.yevhenchmykhun.manager.OrderManager; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; @WebServlet("/purchase") public class PurchaseController extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String email = request.getParameter("email"); String phone = request.getParameter("phone"); String address = request.getParameter("address"); String city = request.getParameter("city"); String ccNumber = request.getParameter("credit-card"); String check = new Validator().validatePurchase(name, email, phone, address, city, ccNumber); String url; if (check == null) { HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart) session.getAttribute("cart"); OrderManager manager = new OrderManager(); manager.placeOrder(name, email, phone, address, city, ccNumber, cart); request.setAttribute("email", email); request.setAttribute("phone", phone); request.setAttribute("address", address); request.setAttribute("city", city); url = "/leave"; } else { url = "/WEB-INF/view/error/massagepage.jsp"; request.setAttribute("message", check); } request.getRequestDispatcher(url).forward(request, response); } }
package weily.com.schedule.util; import android.os.AsyncTask; import android.os.Environment; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; /** * Created by peng on 2017/10/11. * a down picture util */ public class DownPicUtil { public static void downPic(String url, DownFinishListener downFinishListener) { //获取存储卡的目录 String filePath = Environment.getExternalStorageDirectory().getPath(); File file = new File(filePath + "/" + "webViewCache"); if (!file.exists()) { file.mkdir(); } loadPic(file.getPath(), url, downFinishListener);//目录路径,url,下载结果 } private static void loadPic(final String filePath, final String url, final DownFinishListener downFinishListener) { new AsyncTask<Void, Void, String>() {//params: 第一个是执行AsynTask时需要传入的参数,第二个是显示进度,第三个是执行结果 String fileName; // 下载文件名称 InputStream in; OutputStream out; @Override protected String doInBackground(Void... params) { // String[] split = url.split("/"); // fileName = split[split.length - 1];//文件名 //创建目标文件 File picFile = new File(filePath + "/" + "login.gif");//目录+/+文件名 boolean result = false; if (picFile.exists()) { result = picFile.delete(); } if (result) { try { picFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } try { URL picUrl = new URL(url); in = picUrl.openStream(); if (in == null) { return null; } out = new FileOutputStream(picFile); byte[] b = new byte[1024]; int end; while ((end = in.read(b)) != -1) { out.write(b, 0, end); } if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (Exception e) { e.printStackTrace(); } return picFile.getPath(); } @Override protected void onPostExecute(String s) {//这里的s是doInBackGround()传过来带来的 super.onPostExecute(s); if (s != null) { downFinishListener.getDownPath(s); } } }.execute(); } /** * Created by peng on 2017/10/11. * this is 回调接口 after download finished */ public interface DownFinishListener {//下载完成的回调接口 void getDownPath(String s); } }
package com.atguigu.jedis; import java.util.ArrayList; import java.util.List; import org.junit.Test; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import redis.clients.jedis.JedisShardInfo; import redis.clients.jedis.ShardedJedis; import redis.clients.jedis.ShardedJedisPool; public class Jedistest1 { @Test public void test1() { // Jedis jedis = new Jedis("192.168.0.103", 6379); // String string = jedis.set("liner", "love"); // String liner = jedis.get("liner"); // System.out.println(liner); System.out.println("v"); System.out.println("a"); } //连接池 @Test public void test2() { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxActive(1000); poolConfig.setMaxIdle(32); poolConfig.setMaxWait(100 * 1000); JedisPool jedisPool = new JedisPool(poolConfig, "192.168.0.103", 6379); Jedis jedis = jedisPool.getResource(); String liner = jedis.get("liner"); System.out.println(liner); jedisPool.returnBrokenResource(jedis); jedisPool.destroy(); } @Test public void test3() { JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxActive(1000); poolConfig.setMaxIdle(32); poolConfig.setMaxWait(100 * 1000); List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>(); shards.add(new JedisShardInfo("192.168.0.103", 6379)); ShardedJedisPool shardedJedisPool = new ShardedJedisPool(poolConfig, shards); ShardedJedis shardedJedis = null; try { shardedJedis = shardedJedisPool.getResource(); String liner = shardedJedis.get("liner"); System.out.println(liner); } catch (Exception e) { // TODO: handle exception } finally { if(shardedJedis != null) { shardedJedisPool.returnResource(shardedJedis); } } shardedJedisPool.destroy(); System.out.println("a"); } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package LooP; /** * * @author rm */ public class program6 { public static void main(String[] args) { for (int ro = 1; ro <= 12; ro++) { System.out.print(" " + ro + " "); } System.out.println(" "); for (int co = 1; co <= 12; co++) { System.out.print(" " + co + " "); } System.out.println(" "); int resu = 1; for (int row = 2; row <= 12; row++) { for (int coul = 1; coul <= 12; coul++) { resu = row * coul; System.out.print(" " + resu + " "); } System.out.println(" "); } } }
package com.qrokodial.sparkle.components; import java.util.Optional; public interface Component<H extends ComponentHolder> { /** * Called when the component is attached to a holder. * * @param holder */ void onAttached(H holder); /** * Called when the component is detached from a holder. */ void onDetached(); /** * Gets the component holder that this component is bound to. * * @return the component holder */ Optional<H> getHolder(); }
package hu.lamsoft.hms.nutritionist.service; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import hu.lamsoft.hms.common.service.HMSServiceConfiguration; import hu.lamsoft.hms.nutritionist.persistence.NutritionistPersistenceConfiguration; @Configuration @Import({HMSServiceConfiguration.class, NutritionistPersistenceConfiguration.class}) public class NutritionistServiceConfiguration { }
package loecraftpack.ponies.abilities; import java.util.EnumSet; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiChat; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.Tessellator; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import cpw.mods.fml.common.TickType; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class RenderHotBarOverlay { //Reference variables public static RenderHotBarOverlay instance = new RenderHotBarOverlay(); Minecraft mc = Minecraft.getMinecraft(); protected float zLevel = 0.0f; public void renderHotBarOverlay(EnumSet<TickType> type, Object... tickData) { // setup render ScaledResolution res = new ScaledResolution(this.mc.gameSettings, this.mc.displayWidth, this.mc.displayHeight); FontRenderer fontRender = mc.fontRenderer; int width = res.getScaledWidth(); int height = res.getScaledHeight(); mc.entityRenderer.setupOverlayRendering(); this.mc.mcProfiler.startSection("actionBarOverlay"); mc.renderEngine.bindTexture("/loecraftpack/gui/overlay.png"); GL11.glEnable(GL12.GL_RESCALE_NORMAL); RenderHelper.enableGUIStandardItemLighting(); if (this.mc.currentScreen instanceof GuiChat) { GL11.glEnable(GL11.GL_BLEND); GL11.glBlendFunc(GL11.GL_SRC_COLOR, GL11.GL_ONE_MINUS_SRC_COLOR); } GL11.glColor4f(255.0F, 255.0F, 255.0F, 255.0f); if(!this.mc.thePlayer.capabilities.isCreativeMode) renderEnergyBar(width, height); renderChargeBar(width, height); if (this.mc.currentScreen instanceof GuiChat) GL11.glDisable(GL11.GL_BLEND); renderAbilityOverlays(width, height); RenderHelper.disableStandardItemLighting(); GL11.glDisable(GL12.GL_RESCALE_NORMAL); this.mc.mcProfiler.endSection(); } protected void renderChargeBar(int width, int height) { this.mc.mcProfiler.startSection("chargeBar"); short chargeLength = 45; int posX = width / 2 + 92; int posY = height - chargeLength; if (AbilityPlayerData.clientData != null && AbilityPlayerData.clientData.chargeMax> 0) { int progress = (int)(AbilityPlayerData.getClientCastTimeRatio() * (float)(chargeLength)); this.drawTexturedModalRect(posX, posY, 81, 0, 5, chargeLength); if (progress > 0) { this.drawTexturedModalRect(posX, posY + chargeLength - progress, 86, chargeLength - progress, 5, progress); } } this.mc.mcProfiler.endSection(); } protected void renderEnergyBar(int width, int height) { this.mc.mcProfiler.startSection("energyBar"); short energyLength = 81; int posX = width / 2 + 10; int posY = height - 45 - (mc.thePlayer.isInsideOfMaterial(Material.water)? 10: 0); if (AbilityPlayerData.clientData != null && AbilityPlayerData.clientData.energyMax > 0) { int progressAfterImage = (int)(AbilityPlayerData.getClientEnergyAfterImageRatio() * (float)(energyLength)); int progressEffective = (int)(AbilityPlayerData.getClientEffectiveEnergyRatio() * (float)(energyLength)); int progressRegen = (int)(AbilityPlayerData.getClientRegenEnergyRatio() * (float)(energyLength)); int progressDrain = (int)(AbilityPlayerData.getClientDrainEnergyRatio() * (float)(energyLength)); this.drawTexturedModalRect(posX, posY, 0, 0, energyLength, 5); if (progressAfterImage > 0) { this.drawTexturedModalRect(posX + Math.max(energyLength - progressAfterImage, 0), posY, Math.max(energyLength - progressAfterImage, 0), 5, progressAfterImage, 5); } if (progressRegen > 0) { this.drawTexturedModalRect(posX + Math.max(energyLength - progressRegen, 0), posY, Math.max(energyLength - progressRegen, 0), 15, Math.max(progressRegen - progressEffective, 0), 5); } if (progressEffective > 0) { this.drawTexturedModalRect(posX + Math.max(energyLength - progressEffective, 0), posY, Math.max(energyLength - progressEffective, 0), 10, progressEffective, 5); } if (progressDrain > 0) { this.drawTexturedModalRect(posX + Math.max(energyLength - progressEffective , 0), posY, Math.max(energyLength - progressEffective , 0), 20, Math.max(progressEffective - progressDrain, 0), 5); } } this.mc.mcProfiler.endSection(); } protected void renderAbilityOverlays(int width, int height) { for (int i = 0; i < 9; i++) { ItemStack stack = mc.thePlayer.inventory.mainInventory[i]; if (stack != null) { Item item = stack.getItem(); if (item != null && item instanceof ItemActiveAbility) renderAbilityOverlay(width, height, i, ActiveAbility.getCooldown(stack.getItemDamage()), ActiveAbility.isToggled(stack.getItemDamage())); } } } protected void renderAbilityOverlay(int width, int height, int position, float coolDown, boolean isToggled) { int posX = width / 2 - 88 + (20*position); int posY = height - 19; if (isToggled) { drawToggledTexture(posX, posY, 97, 45, 16, 16, coolDown); } else if (coolDown > 0) { drawCoolDownTexture(posX, posY, 81, 45, 16, 16, coolDown); } } /** * extracted from minecraft */ protected void drawTexturedModalRect(int posX, int posY, int uCoord, int vCoord, int width, int height) { float f = 0.00390625F; float f1 = 0.00390625F; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)(posX + 0), (double)(posY + height), (double)this.zLevel, (double)((float)(uCoord + 0) * f), (double)((float)(vCoord + height) * f1)); tessellator.addVertexWithUV((double)(posX + width), (double)(posY + height), (double)this.zLevel, (double)((float)(uCoord + width) * f), (double)((float)(vCoord + height) * f1)); tessellator.addVertexWithUV((double)(posX + width), (double)(posY + 0), (double)this.zLevel, (double)((float)(uCoord + width) * f), (double)((float)(vCoord + 0) * f1)); tessellator.addVertexWithUV((double)(posX + 0), (double)(posY + 0), (double)this.zLevel, (double)((float)(uCoord + 0) * f), (double)((float)(vCoord + 0) * f1)); tessellator.draw(); } protected void drawToggledTexture(int posX, int posY, int uCoord, int vCoord, int width, int height, float progress) { float intensity = (float)(Math.sin(Math.toRadians(progress*360.0f))+1.0f)/6.0f; float f = 0.00390625F; float f1 = 0.00390625F; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)(posX + 0 ), (double)(posY + height), (double)this.zLevel, (double)((float)(uCoord + 0 ) * f), (double)((float)(vCoord + height) * f1)); tessellator.addVertexWithUV((double)(posX + width), (double)(posY + height), (double)this.zLevel, (double)((float)(uCoord + width) * f), (double)((float)(vCoord + height) * f1)); tessellator.addVertexWithUV((double)(posX + width), (double)(posY + 0 ), (double)this.zLevel, (double)((float)(uCoord + width) * f), (double)((float)(vCoord + 0 ) * f1)); tessellator.addVertexWithUV((double)(posX + 0 ), (double)(posY + 0 ), (double)this.zLevel, (double)((float)(uCoord + 0 ) * f), (double)((float)(vCoord + 0 ) * f1)); tessellator.draw(); GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glDisable(GL11.GL_TEXTURE_2D); GL11.glColor4f(1.0F, 1.0F, 1.0F, intensity); tessellator.startDrawingQuads(); tessellator.addVertex((double)(posX + 0 ), (double)(posY + height), 0.0f); tessellator.addVertex((double)(posX + width), (double)(posY + height), 0.0f); tessellator.addVertex((double)(posX + width), (double)(posY + 0 ), 0.0f); tessellator.addVertex((double)(posX + 0 ), (double)(posY + 0 ), 0.0f); tessellator.draw(); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_DEPTH_TEST); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } protected void drawCoolDownTexture(int posX, int posY, int uCoord, int vCoord, int width, int height, float progress) { double angleD = progress*360.0f; double angleR = Math.toRadians(angleD); int stage = (int)angleD/45; float f = 0.00390625F; float f1 = 0.00390625F; Tessellator tessellator = Tessellator.instance; double ratio = 0; switch (stage) { case 0: ratio = 1.0d-Math.tan(angleR); tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)(posX + width/2 ), (double)(posY + height/2), (double)this.zLevel, (double)((float)(uCoord + width/2 ) * f), (double)((float)(vCoord + height/2) * f1)); tessellator.addVertexWithUV((double)(posX + width/2 ), (double)(posY + height/2), (double)this.zLevel, (double)((float)(uCoord + width/2 ) * f), (double)((float)(vCoord + height/2) * f1)); tessellator.addVertexWithUV((double)(posX + width/2 ), (double)(posY + 0 ), (double)this.zLevel, (double)((float)(uCoord + width/2 ) * f), (double)((float)(vCoord + 0 ) * f1)); tessellator.addVertexWithUV((double)(posX + width/2*(ratio)), (double)(posY + 0 ), (double)this.zLevel, (double)((float)(uCoord + (float)width/2.0f*(ratio)) * f), (double)((float)(vCoord + 0 ) * f1)); tessellator.draw(); break; case 1: ratio = 1.0d-1.0d/Math.tan(angleR); tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)(posX + 0 ), (double)(posY + height/2*(ratio)), (double)this.zLevel, (double)((float)(uCoord + 0 ) * f), (double)((float)(vCoord + (float)height/2.0f*(ratio)) * f1)); tessellator.addVertexWithUV((double)(posX + width/2), (double)(posY + height/2 ), (double)this.zLevel, (double)((float)(uCoord + width/2) * f), (double)((float)(vCoord + height/2 ) * f1)); tessellator.addVertexWithUV((double)(posX + width/2), (double)(posY + 0 ), (double)this.zLevel, (double)((float)(uCoord + width/2) * f), (double)((float)(vCoord + 0 ) * f1)); tessellator.addVertexWithUV((double)(posX + 0 ), (double)(posY + 0 ), (double)this.zLevel, (double)((float)(uCoord + 0 ) * f), (double)((float)(vCoord + 0 ) * f1)); tessellator.draw(); break; case 2: ratio = -1.0d/Math.tan(angleR); tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)(posX + 0 ), (double)(posY + height/2+height/2*(ratio)), (double)this.zLevel, (double)((float)(uCoord + 0 ) * f), (double)((float)(vCoord + height/2+(float)height/2.0f*(ratio)) * f1)); tessellator.addVertexWithUV((double)(posX + width/2), (double)(posY + height/2 ), (double)this.zLevel, (double)((float)(uCoord + width/2) * f), (double)((float)(vCoord + height/2 ) * f1)); tessellator.addVertexWithUV((double)(posX + width/2), (double)(posY + height/2 ), (double)this.zLevel, (double)((float)(uCoord + width/2) * f), (double)((float)(vCoord + height/2 ) * f1)); tessellator.addVertexWithUV((double)(posX + 0 ), (double)(posY + height/2 ), (double)this.zLevel, (double)((float)(uCoord + 0 ) * f), (double)((float)(vCoord + height/2 ) * f1)); tessellator.draw(); break; case 3: ratio = 1.0d+Math.tan(angleR); tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)(posX + 0 ), (double)(posY + height ), (double)this.zLevel, (double)((float)(uCoord + 0 ) * f), (double)((float)(vCoord + height ) * f1)); tessellator.addVertexWithUV((double)(posX + width/2*(ratio)), (double)(posY + height ), (double)this.zLevel, (double)((float)(uCoord + (float)width/2.0f*(ratio)) * f), (double)((float)(vCoord + height ) * f1)); tessellator.addVertexWithUV((double)(posX + width/2 ), (double)(posY + height/2), (double)this.zLevel, (double)((float)(uCoord + width/2 ) * f), (double)((float)(vCoord + height/2) * f1)); tessellator.addVertexWithUV((double)(posX + 0 ), (double)(posY + height/2), (double)this.zLevel, (double)((float)(uCoord + 0 ) * f), (double)((float)(vCoord + height/2) * f1)); tessellator.draw(); break; case 4: ratio = Math.tan(angleR); tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)(posX + width/2 ), (double)(posY + height ), (double)this.zLevel, (double)((float)(uCoord + width/2 ) * f), (double)((float)(vCoord + height ) * f1)); tessellator.addVertexWithUV((double)(posX + width/2+width/2*(ratio)), (double)(posY + height ), (double)this.zLevel, (double)((float)(uCoord + width/2+(float)width/2.0f*(ratio)) * f), (double)((float)(vCoord + height ) * f1)); tessellator.addVertexWithUV((double)(posX + width/2 ), (double)(posY + height/2), (double)this.zLevel, (double)((float)(uCoord + width/2 ) * f), (double)((float)(vCoord + height/2) * f1)); tessellator.addVertexWithUV((double)(posX + width/2 ), (double)(posY + height/2), (double)this.zLevel, (double)((float)(uCoord + width/2 ) * f), (double)((float)(vCoord + height/2) * f1)); tessellator.draw(); break; case 5: ratio = 1.0d/Math.tan(angleR); tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)(posX + width/2), (double)(posY + height ), (double)this.zLevel, (double)((float)(uCoord + width/2) * f), (double)((float)(vCoord + height ) * f1)); tessellator.addVertexWithUV((double)(posX + width ), (double)(posY + height ), (double)this.zLevel, (double)((float)(uCoord + width ) * f), (double)((float)(vCoord + height ) * f1)); tessellator.addVertexWithUV((double)(posX + width ), (double)(posY + height/2+height/2*(ratio)), (double)this.zLevel, (double)((float)(uCoord + width ) * f), (double)((float)(vCoord + height/2+(float)height/2.0f*(ratio)) * f1)); tessellator.addVertexWithUV((double)(posX + width/2), (double)(posY + height/2 ), (double)this.zLevel, (double)((float)(uCoord + width/2) * f), (double)((float)(vCoord + height/2 ) * f1)); tessellator.draw(); break; case 6: ratio = 1.0d+1.0d/Math.tan(angleR); tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)(posX + width/2), (double)(posY + height/2 ), (double)this.zLevel, (double)((float)(uCoord + width/2) * f), (double)((float)(vCoord + height/2 ) * f1)); tessellator.addVertexWithUV((double)(posX + width ), (double)(posY + height/2 ), (double)this.zLevel, (double)((float)(uCoord + width ) * f), (double)((float)(vCoord + height/2 ) * f1)); tessellator.addVertexWithUV((double)(posX + width ), (double)(posY + height/2*(ratio)), (double)this.zLevel, (double)((float)(uCoord + width ) * f), (double)((float)(vCoord + (float)height/2.0f*(ratio)) * f1)); tessellator.addVertexWithUV((double)(posX + width/2), (double)(posY + height/2 ), (double)this.zLevel, (double)((float)(uCoord + width/2) * f), (double)((float)(vCoord + height/2 ) * f1)); tessellator.draw(); break; case 7: ratio = -Math.tan(angleR); tessellator.startDrawingQuads(); tessellator.addVertexWithUV((double)(posX + width/2 ), (double)(posY + height/2), (double)this.zLevel, (double)((float)(uCoord + width/2 ) * f), (double)((float)(vCoord + height/2) * f1)); tessellator.addVertexWithUV((double)(posX + width ), (double)(posY + height/2), (double)this.zLevel, (double)((float)(uCoord + width ) * f), (double)((float)(vCoord + height/2) * f1)); tessellator.addVertexWithUV((double)(posX + width ), (double)(posY + 0 ), (double)this.zLevel, (double)((float)(uCoord + width ) * f), (double)((float)(vCoord + 0 ) * f1)); tessellator.addVertexWithUV((double)(posX + width/2+width/2*(ratio)), (double)(posY + 0 ), (double)this.zLevel, (double)((float)(uCoord + width/2+(float)width/2.0f*(ratio)) * f), (double)((float)(vCoord + 0 ) * f1)); tessellator.draw(); break; default: this.drawTexturedModalRect(posX, posY, uCoord, vCoord, width, height); return; } switch (stage) { case 7: case 6: this.drawTexturedModalRect(posX+width/2, posY+height/2, uCoord+width/2, vCoord+height/2, width/2, height/2); case 5: case 4: this.drawTexturedModalRect(posX, posY+height/2, uCoord, vCoord+height/2, width/2, height/2); case 3: case 2: this.drawTexturedModalRect(posX, posY, uCoord, vCoord, width/2, height/2); } } }
/* * Origin of the benchmark: * repo: https://github.com/diffblue/cbmc.git * branch: develop * directory: regression/cbmc-java/Inheritance1 * The benchmark was taken from the repo: 24 January 2018 */ class A1 { int some_member; A1() { some_member=1; } }; class A2 extends A1 { int some_other_member; A2() { some_other_member=2; } }; class A3 extends A2 { int yet_another_member; A3() { yet_another_member=3; } }; class Main { public static void main(String[] args) { A3 a3=new A3(); assert a3.some_member==1; assert a3.some_other_member==2; assert a3.yet_another_member==3; } }