text
stringlengths
10
2.72M
package com.kristofcolpaert.android.androidblurredbackground; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.kristofcolpaert.android.androidblurredbackground.utils.BlurUtil; import butterknife.BindView; import butterknife.ButterKnife; import rx.Subscriber; public class MainActivity extends AppCompatActivity { //region View elements @BindView(R.id.button) protected Button button; @BindView(R.id.container) protected LinearLayout container; @BindView(R.id.background) protected RelativeLayout background; //endregion //region Activity logic @Override protected void onCreate(@Nullable Bundle savedInstanceState) { // Set up View and ButterKnife super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.setDebug(true); ButterKnife.bind(this); // Initiate Button click listener this.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Poll blurred background image and show it BlurUtil.createBlurredBitmap(MainActivity.this, container) .subscribe(new Subscriber<Bitmap>() { @Override public void onCompleted() { // Do nothing } @Override public void onError(final Throwable e) { // Do nothing } @Override public void onNext(final Bitmap bitmap) { // Set new background final Drawable drawable = new BitmapDrawable(bitmap); background.setBackground(drawable); background.setVisibility(View.VISIBLE); // Open new activity Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } }); } }); } @Override protected void onResume() { super.onResume(); // Make blurred background disappear whenever this Activity is resumed this.background.setVisibility(View.GONE); } //endregion }
package mrsl.jdkstudy.designpartten.factory; import mrsl.jdkstudy.designpartten.factory.someClass.Somclass; import mrsl.jdkstudy.designpartten.factory.someClass.SomeClass1; /** * 工厂方法模式创建somclass1的工厂 * @author Administrator * */ public class SomClassFactory1 implements IFactory{ @Override public Somclass crateSomclass() { return new SomeClass1(); } }
package abilities; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Rectangle; import render.BasicRenderer; public class NullAbilityObject extends AbilityObject { private int countDown; public NullAbilityObject( int xPos, int yPos) throws SlickException { this.shape = new Rectangle(xPos,yPos, 10,10); this.renderer = new BasicRenderer(new Image("data/thrusterFlame.png"), shape); this.countDown= 20; this.canCollide = false; } @Override public boolean shouldRemove() { return countDown<0; } @Override public void update() { countDown -=1; } @Override public void onRemoveDo() { // TODO Auto-generated method stub } }
package com.tvm.thread.cyclicBarrier; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * @author Neeraj Kumar * * There are many situations in concurrent programming where threads may * need to wait at a predefined execution point until all other threads * reach that point.CyclicBarrier helps provide such a synchronization * point; see Table 11-3 for the important methods in this class. * CyclicBarrier enables threads to wait at a predefined execution * point. * * * In the main() method you create a CyclicBarrier object. The * constructor takes two arguments: the number of threads to wait for, * and the thread to invoke when all the threads reach the barrier. In * this case, you have four players to wait for, so you create four * threads, with each thread representing a player. The second argument * for the CyclicBarrier constructor is the MixedDoubleTennisGame object * since this thread represents the game, which will start once all four * players are ready. Inside the run() method for each Player thread, * you call the await() method on the CyclicBarrier object. Once the * number of awaiting threads for the CyclicBarrier object reaches four, * the run() method in MixedDoubleTennisGame is called. * * */ public class CyclicBarrierDemo { public static void main(String[] args) { System.out.println("Reserving tennis court \n" + "As soon as four players arrive, game will start"); CyclicBarrier barrier = new CyclicBarrier(4, new MixedDoubleTennis()); new Player(barrier, "Martina"); new Player(barrier, "John"); new Player(barrier, "Saniya"); new Player(barrier, "Paes"); } } class MixedDoubleTennis extends Thread { // The run() method in this thread should be called only when // four players are ready to start the game public void run() { System.out.println("All four players ready,game starts \n love all ..."); } } class Player extends Thread { CyclicBarrier waitPoint; public Player(CyclicBarrier barrier, String name) { this.waitPoint = barrier; this.setName(name); this.start(); } public void run() { System.out.println("Player " + this.getName() + "is ready "); try { waitPoint.await(); } catch (InterruptedException | BrokenBarrierException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package com.dx.visitor2; public class OwnerHumen implements Humen{ @Override public void visit(CatPet catPet) { System.out.println("喂猫吃鱼"); } @Override public void visit(DogPet dogPet) { System.out.println("喂狗吃肉"); } }
package br.com.webexplorer.screen; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.swing.JOptionPane; /** * * @author Erick */ public class ScreenLogin extends javax.swing.JFrame { public ScreenLogin() { initComponents(); } Connection conexao = null; PreparedStatement pst = null; // Instrução sql ResultSet rs = null; // Resultado sql public void Entrar(){ String sql = "Select * from tbuser where login=? and senha=?"; try { pst = conexao.prepareStatement(sql); pst = setString(1, txtLogin.getText()); pst = setString(2, txtSenha.getText()); //pst= setString(3, txtToken.getText()); rs = pst.executeQuery(); if (rs.next()){ ScreenPrincipal principal = new ScreenPrincipal(); principal.setVisible(true); this.dispose(); }else{ JOptionPane.showMessageDialog(null,"Usuário ou senha inválido!"); } } catch (Exception e) { JOptionPane.showMessageDialog(null, e); } if (conexao!= null){ lblStatus.setText("Conectado!"); }else { lblStatus.setText("Não conectado!"); } } // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { lblLogin = new javax.swing.JLabel(); lblSenha = new javax.swing.JLabel(); txtLogin = new javax.swing.JTextField(); lblToken = new javax.swing.JLabel(); txtToken = new javax.swing.JTextField(); txtSenha = new javax.swing.JPasswordField(); btnEntrar = new javax.swing.JButton(); lblStatus = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("WebExplorer - Login"); setResizable(false); lblLogin.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N lblLogin.setText("Login "); lblSenha.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N lblSenha.setText("Senha "); lblToken.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N lblToken.setText("Token"); btnEntrar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N btnEntrar.setText("Entrar"); btnEntrar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEntrarActionPerformed(evt); } }); lblStatus.setText("Status"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(37, 37, 37) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(lblSenha) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtSenha)) .addGroup(layout.createSequentialGroup() .addComponent(lblLogin) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 258, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblStatus) .addComponent(lblToken)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtToken)) .addGroup(layout.createSequentialGroup() .addGap(175, 175, 175) .addComponent(btnEntrar, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(117, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(57, 57, 57) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblLogin) .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(39, 39, 39) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblSenha) .addComponent(txtSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(40, 40, 40) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblToken) .addComponent(txtToken, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 47, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btnEntrar) .addComponent(lblStatus)) .addGap(38, 38, 38)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void btnEntrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEntrarActionPerformed Entrar(); }//GEN-LAST:event_btnEntrarActionPerformed public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ScreenLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ScreenLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ScreenLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ScreenLogin.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { new ScreenLogin().setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnEntrar; private javax.swing.JLabel lblLogin; private javax.swing.JLabel lblSenha; private javax.swing.JLabel lblStatus; private javax.swing.JLabel lblToken; private javax.swing.JTextField txtLogin; private javax.swing.JPasswordField txtSenha; private javax.swing.JTextField txtToken; // End of variables declaration//GEN-END:variables private PreparedStatement setString(int i, String text) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
package com.jd.jarvisdemonim.ui; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import com.jd.jarvisdemonim.R; import com.jd.jarvisdemonim.base.BaseActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.ExcellectViewActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestAidlActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestAnimationActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestApkDlActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestBgaActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestBinderPoolActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestBottomNavigationActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestCalendarAdapterActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestContentProviderActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestExpandActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestGreenDaoActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestIndexStickyActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestJUnitActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestLazyFragmentActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestLoad1Activity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestMDActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestMessengerActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestMultiGreenDaoActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestMvcActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestMvcActivityNet; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestMvpActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestNetWorkActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestNotifcationActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestPageActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestRemoteViewActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestRetrofitActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestRichTextActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestScrollConflictActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestSenserActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestSocketActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestSocketUDPActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestStickyActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestTabReminderActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestToolbarActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestXRecyActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTextActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.NormalTextCarlendarActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.TestCustomView.NormalTestCustomTouchActivity; import com.jd.jarvisdemonim.ui.testadapteractivity.TestCustomView.NormalTestCustomViewActivity; import com.jd.jdkit.elementkit.utils.system.ToastUtils; import com.jd.jdkit.permissionkit.CheckPermissionsForAPI23; import com.jd.jdkit.permissionkit.PermissionsActivity; import com.jd.myadapterlib.RecyCommonAdapter; import com.jd.myadapterlib.delegate.RecyViewHolder; import com.jd.myadapterlib.dinterface.DOnItemChildClickListener; import com.netease.nim.uikit.common.util.log.LogUtil; import java.io.File; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.OnClick; import static com.jd.jarvisdemonim.ui.testadapteractivity.NormalTestApkDlActivity.EXTRA_DEX_PATH; /** * Nim Demo 的使用; */ public class MainActivity extends BaseActivity { @Bind(R.id.recylcer_bottom) RecyclerView mRecy; LinearLayoutManager manager; List<String> mList; private MyAdapter myAdapter; @Override public int getContentViewId() { return R.layout.activity_main; } @Override protected void initView(Bundle savedInstanceState) { mList = new ArrayList<>(); manager = new LinearLayoutManager(mContext); myAdapter = new MyAdapter(mRecy, android.R.layout.simple_list_item_1, mList); } @Override protected void initVariable() { doLoadData(); } private void doLoadData() { mList.add("测试联网和Toasty"); mList.add("测试单布局加载更多"); mList.add("测试fragment的懒加载"); mList.add("测试GreenDao的使用"); mList.add("测试GreenDao多布局的使用"); mList.add("测试Retrofit下载数据"); mList.add("测试MVP模式"); mList.add("测试约束CoordernatorLayout布局及简单MD设计"); mList.add("测试XRecyclerView,好看的刷新和加载UI"); mList.add("测试自定义View的使用"); mList.add("测试事件分发的过程"); mList.add("测试IPC机制:Aidl进程间的通信,一个app启动另一个app"); mList.add("测试IPC机制:Messager进程间的通信,实现不同app间的通信(基本数据类型)"); mList.add("测试IPC机制:ContentProvider的数据共享"); mList.add("测试IPC机制:Socket 的进程间通信 TCP Server"); mList.add("测试IPC机制:Socket 的进程间通信 UDP Server"); mList.add("测试IPC机制AIDL优化:Binder连接池,实现一个service和多个aidl;"); mList.add("测试滑动冲突的优化,事件分发\n(暂未测试);"); mList.add("测试插件化app,打开apk中的类"); mList.add("测试通知栏的消息通知/remoteViews的使用/添加桌面插件/桌面悬浮框"); mList.add("测试RemoteView实现进程间的通信和刷新不同进程的UI\n(暂未测试)"); mList.add("测试优秀自定义控件"); mList.add("测试单元测试(看代码)"); mList.add("测试传感器"); mList.add("测试富文本加载"); } @Override protected void processLogic(Bundle savedInstanceState) { mRecy.setLayoutManager(manager); mRecy.setAdapter(myAdapter); // mRecy.addItemDecoration(new RecyclerView.ItemDecoration() { // @Override // public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { // super.onDraw(c, parent, state); // c.drawColor(Color.BLUE);//需要item的布局设置背景色; // // } // // @Override // public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { // super.getItemOffsets(outRect, view, parent, state); // outRect.set(0, 1, 0, 1); // } // }); myAdapter.setOnItemChildClickListener(new DOnItemChildClickListener() { @Override public void onItemChildClick(View convertView, View view, int pos) { switch (view.getId()) { case android.R.id.text1: switch (pos) { case 0: startActivity(new Intent(mContext, NormalTestNetWorkActivity.class)); break; case 1: startActivity(new Intent(mContext, NormalTestLoad1Activity.class)); break; case 2: startActivity(new Intent(mContext, NormalTestLazyFragmentActivity.class)); break; case 3: startActivity(new Intent(mContext, NormalTestGreenDaoActivity.class)); break; case 4: startActivity(new Intent(mContext, NormalTestMultiGreenDaoActivity.class)); break; case 5: startActivity(new Intent(mContext, NormalTestRetrofitActivity.class)); break; case 6: startActivity(new Intent(mContext, NormalTestMvpActivity.class)); break; case 7: startActivity(new Intent(mContext, NormalTestMDActivity.class)); break; case 8: startActivity(new Intent(mContext, NormalTestXRecyActivity.class)); break; case 9: startActivity(new Intent(mContext, NormalTestCustomViewActivity.class)); break; case 10: startActivity(new Intent(mContext, NormalTestCustomTouchActivity.class)); break; case 11: startActivity(new Intent(mContext, NormalTestAidlActivity.class)); break; case 12: startActivity(new Intent(mContext, NormalTestMessengerActivity.class)); break; case 13: startActivity(new Intent(mContext, NormalTestContentProviderActivity.class)); break; case 14: startActivity(new Intent(mContext, NormalTestSocketActivity.class)); break; case 15: startActivity(new Intent(mContext, NormalTestSocketUDPActivity.class)); break; case 16: startActivity(new Intent(mContext, NormalTestBinderPoolActivity.class)); break; case 17: startActivity(new Intent(mContext, NormalTestScrollConflictActivity.class)); break; case 18: //调用另一个未安装的app的界面; String apkName = "plugin.apk"; Intent intent = new Intent(mContext, NormalTestApkDlActivity.class); intent.putExtra(EXTRA_DEX_PATH, Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + apkName); startActivity(intent); break; case 19: startActivity(new Intent(mContext, NormalTestNotifcationActivity.class)); break; case 20: startActivity(new Intent(mContext, NormalTestRemoteViewActivity.class)); break; case 21://自定义集合展示; startActivity(new Intent(mContext, ExcellectViewActivity.class)); break; case 22: startActivity(new Intent(mContext, NormalTestJUnitActivity.class)); break; case 23: startActivity(new Intent(mContext, NormalTestSenserActivity.class)); break; case 24: startActivity(new Intent(mContext, NormalTestRichTextActivity.class)); break; } break; } } }); } @OnClick({R.id.txt_nim, R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4, R.id.btn5, R.id.btn6, R.id.btn7 , R.id.btn8, R.id.btn9, R.id.btn10, R.id.btn11, R.id.btn12, R.id.btn13, R.id.btn14, R.id.btn15, R.id.btn16}) void onclick(View view) { switch (view.getId()) { case R.id.txt_nim: Intent intent0 = new Intent(this, NimActivity.class); startActivity(intent0); break; case R.id.btn1://baseadapter LogUtil.i("jarvisclick", "button"); Intent intent = new Intent(this, NormalTestActivity.class); startActivity(intent); break; case R.id.btn2://tuozhuai LogUtil.i("jarvisclick", "button"); Intent intent2 = new Intent(this, NormalTestBgaActivity.class); startActivity(intent2); break; case R.id.btn3: LogUtil.i("jarvisclick", "button"); Intent intent3 = new Intent(this, NormalTestPageActivity.class); startActivity(intent3); break; case R.id.btn12: Intent intent12 = new Intent(this, NormalTestIndexStickyActivity.class); startActivity(intent12); break; case R.id.btn4: LogUtil.i("jarvisclick", "button"); Intent intent4 = new Intent(this, NormalTestExpandActivity.class); startActivity(intent4); break; case R.id.btn5: LogUtil.i("jarvisclick", "button"); Intent intent5 = new Intent(this, NormalTestStickyActivity.class); startActivity(intent5); break; case R.id.btn6: LogUtil.i("jarvisclick", "button"); Intent intent6 = new Intent(this, NormalTextActivity.class); startActivity(intent6); break; case R.id.btn7: LogUtil.i("jarvisclick", "button"); Intent intent7 = new Intent(this, NormalTestMvcActivity.class); startActivity(intent7); break; case R.id.btn8: LogUtil.i("jarvisclick", "button"); Intent intent8 = new Intent(this, NormalTestMvcActivityNet.class); startActivity(intent8); break; case R.id.btn9: LogUtil.i("jarvisclick", "button"); Intent intent9 = new Intent(this, NormalTestTabReminderActivity.class); startActivity(intent9); break; case R.id.btn10: LogUtil.i("jarvisclick", "button"); Intent intent10 = new Intent(this, NormalTextCarlendarActivity.class); startActivity(intent10); break; case R.id.btn11: LogUtil.i("jarvisclick", "button"); Intent intent11 = new Intent(this, NormalTestBottomNavigationActivity.class); startActivity(intent11); break; case R.id.btn13: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { new CheckPermissionsForAPI23(this); ToastUtils.showToast("android-23测试权限"); } else { ToastUtils.showToast("android-23 以下没有此功能;"); } break; case R.id.btn14: LogUtil.i("jarvisclick", "button"); Intent intent14 = new Intent(this, NormalTestCalendarAdapterActivity.class); startActivity(intent14); break; case R.id.btn15: Intent intent15 = new Intent(this, NormalTestToolbarActivity.class); startActivity(intent15); break; case R.id.btn16: startActivity(new Intent(this, NormalTestAnimationActivity.class)); break; } } private void checkPermissionsResult(int requestCode, int resultCode) { //sdk23+用 如果用户拒绝赋予你所需要的权限 则直接退出app,if内方法可自行斟酌 if (requestCode == PermissionsActivity.REQUEST_CODE && resultCode == PermissionsActivity.PERMISSIONS_DENIED) { ToastUtils.showToast("拒绝赋予权限"); } else if (requestCode == PermissionsActivity.PERMISSIONS_GRANTED) { ToastUtils.showToast("全部权限已授权"); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) checkPermissionsResult(requestCode, resultCode); } private static class MyAdapter extends RecyCommonAdapter { public MyAdapter(RecyclerView mRecycler, int layoutId, List datas) { super(mRecycler, layoutId, datas); } @Override protected void convert(RecyViewHolder viewHolder, Object item, int position) { if (item instanceof String) { viewHolder.setText(android.R.id.text1, (String) item); viewHolder.setItemChildClickListener(android.R.id.text1); } } } }
package com.openfarmanager.android.dialogs; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.util.Pair; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.ListView; import com.jcraft.jsch.ChannelSftp; import com.openfarmanager.android.App; import com.openfarmanager.android.R; import com.openfarmanager.android.adapters.SelectEncodingAdapter; import com.openfarmanager.android.model.NetworkEnum; import static com.openfarmanager.android.controllers.EditViewController.*; import java.io.File; import java.nio.charset.Charset; /** * author: Vlad Namashko */ public class SelectEncodingDialog extends Dialog { private Handler mHandler; private File mSelectedFile; private NetworkEnum mNetworkType; private View mDialogView; private CheckBox mSaveAsDefault; private boolean mShowSaveOption; public SelectEncodingDialog(Context context, Handler handler, File selectedFile) { this(context, handler, selectedFile, true); } public SelectEncodingDialog(Context context, Handler handler, NetworkEnum networkType, boolean showSaveOption) { this(context, handler, (File) null, showSaveOption); mNetworkType = networkType; } public SelectEncodingDialog(Context context, Handler handler, File selectedFile, boolean showSaveOption) { super(context, R.style.Action_Dialog); mHandler = handler; mSelectedFile = selectedFile; mShowSaveOption = showSaveOption; setCancelable(false); } @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); mDialogView = View.inflate(App.sInstance.getApplicationContext(), R.layout.dialog_select_encoding, null); mSaveAsDefault = (CheckBox) mDialogView.findViewById(R.id.save_as_default); mSaveAsDefault.setVisibility(mShowSaveOption ? View.VISIBLE : View.GONE); ListView encodings = (ListView) mDialogView.findViewById(R.id.encoding_list); SelectEncodingAdapter adapter = new SelectEncodingAdapter(mSelectedFile, getDefaultCharset()); encodings.setAdapter(adapter); encodings.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Charset character = (Charset) view.getTag(); mHandler.sendMessage(mHandler.obtainMessage(MSG_SELECT_ENCODING, new SelectedEncodingInfo(mSaveAsDefault.isChecked(), character, mNetworkType))); dismiss(); } }); encodings.setSelection(adapter.getDefaultItemPosition()); setContentView(mDialogView); } private String getDefaultCharset() { String charset = App.sInstance.getSettings().getDefaultCharset(); return charset != null ? charset : Charset.defaultCharset().name(); } public static class SelectedEncodingInfo { public boolean saveAsDefault; public Charset charset; public NetworkEnum networkType; public SelectedEncodingInfo(boolean saveAsDefault, Charset charset, NetworkEnum networkType) { this.saveAsDefault = saveAsDefault; this.charset = charset; this.networkType = networkType; } } }
// 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.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.cardview.widget.CardView; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.viewbinding.ViewBinding; import com.designurway.idlidosa.R; import java.lang.NullPointerException; import java.lang.Override; import java.lang.String; public final class LayoutFeaturedItemBinding implements ViewBinding { @NonNull private final ConstraintLayout rootView; @NonNull public final TextView menuDescriptionTv; @NonNull public final ImageView menuImgIv; @NonNull public final TextView menuNameTv; @NonNull public final CardView menuOverallLayoutCv; @NonNull public final TextView menuPriceTv; @NonNull public final ProgressBar progressBulk; private LayoutFeaturedItemBinding(@NonNull ConstraintLayout rootView, @NonNull TextView menuDescriptionTv, @NonNull ImageView menuImgIv, @NonNull TextView menuNameTv, @NonNull CardView menuOverallLayoutCv, @NonNull TextView menuPriceTv, @NonNull ProgressBar progressBulk) { this.rootView = rootView; this.menuDescriptionTv = menuDescriptionTv; this.menuImgIv = menuImgIv; this.menuNameTv = menuNameTv; this.menuOverallLayoutCv = menuOverallLayoutCv; this.menuPriceTv = menuPriceTv; this.progressBulk = progressBulk; } @Override @NonNull public ConstraintLayout getRoot() { return rootView; } @NonNull public static LayoutFeaturedItemBinding inflate(@NonNull LayoutInflater inflater) { return inflate(inflater, null, false); } @NonNull public static LayoutFeaturedItemBinding inflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent, boolean attachToParent) { View root = inflater.inflate(R.layout.layout_featured_item, parent, false); if (attachToParent) { parent.addView(root); } return bind(root); } @NonNull public static LayoutFeaturedItemBinding 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.menu_description_tv; TextView menuDescriptionTv = rootView.findViewById(id); if (menuDescriptionTv == null) { break missingId; } id = R.id.menu_img_iv; ImageView menuImgIv = rootView.findViewById(id); if (menuImgIv == null) { break missingId; } id = R.id.menu_name_tv; TextView menuNameTv = rootView.findViewById(id); if (menuNameTv == null) { break missingId; } id = R.id.menu_overall_layout_cv; CardView menuOverallLayoutCv = rootView.findViewById(id); if (menuOverallLayoutCv == null) { break missingId; } id = R.id.menu_price_tv; TextView menuPriceTv = rootView.findViewById(id); if (menuPriceTv == null) { break missingId; } id = R.id.progress_bulk; ProgressBar progressBulk = rootView.findViewById(id); if (progressBulk == null) { break missingId; } return new LayoutFeaturedItemBinding((ConstraintLayout) rootView, menuDescriptionTv, menuImgIv, menuNameTv, menuOverallLayoutCv, menuPriceTv, progressBulk); } String missingId = rootView.getResources().getResourceName(id); throw new NullPointerException("Missing required view with ID: ".concat(missingId)); } }
package walnoot.dodgegame.gameplay; import walnoot.dodgegame.DodgeGame; import walnoot.dodgegame.components.Entity; import walnoot.dodgegame.components.UnitComponent.UnitType; import walnoot.dodgegame.states.GameState; import com.badlogic.gdx.math.MathUtils; public class TestSpawnHandler extends SpawnHandler{ public static final SpawnHandler instance = new TestSpawnHandler(); private int startTime; private float startAngle; private UnitType type; private float speed; public void init(){ startTime = DodgeGame.gameTime; startAngle = MathUtils.random(0f, 2f * MathUtils.PI); // type = MathUtils.randomBoolean() ? UnitType.DIE : UnitType.SCORE; type = UnitType.SCORE; speed = MathUtils.random(1f, 2f); if(MathUtils.randomBoolean()) speed = -speed; } public void spawn(Entity entity, int time){ float rad = (((DodgeGame.gameTime - this.startTime) / (float) getDuration()) * 2 * MathUtils.PI + startAngle) * speed; spawnToCenter(entity, MathUtils.cos(rad) * GameState.MAP_SIZE, MathUtils.sin(rad) * GameState.MAP_SIZE, type); } public int getPauseTicks(int time){ return 6; } public int getDuration(){ return (int) (3 * DodgeGame.UPDATES_PER_SECOND); } }
package com.example.android.navigationaldrawer2.models; /** * Created by Andrițchi Alexei on 9/27/16. */ public class Flower { private int productId; private String name; private double price; private String instructions; private String category; public int getProductId() { return productId; } public String getName() { return name; } public double getPrice() { return price; } public String getInstructions() { return instructions; } public String getCategory() { return category; } }
package com.petpet.c3po.analysis.mapreduce; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.MapReduceCommand; import com.mongodb.MapReduceOutput; import com.petpet.c3po.common.Constants; import com.petpet.c3po.datamodel.Property; import com.petpet.c3po.datamodel.Property.PropertyType; public class HistogramJob extends MapReduceJob { private static final Logger LOG = LoggerFactory.getLogger(HistogramJob.class); private String property; public HistogramJob(String c, String f) { this.setC3poCollection(c); this.property = f; this.setFilterquery(new BasicDBObject("collection", c)); this.setConfig(new HashMap<String, String>()); } public HistogramJob(String c, String f, BasicDBObject query) { this(c, f); this.setFilterquery(query); } public MapReduceOutput execute() { final Property p = this.getPersistence().getCache().getProperty(property); String map; if (p.getType().equals(PropertyType.DATE.toString())) { map = Constants.DATE_HISTOGRAM_MAP.replace("{}", p.getId()); String constraintKey = "metadata." + this.property + ".value"; BasicDBObject constraintValue = new BasicDBObject("$type", 9); BasicDBObject prop = (BasicDBObject) this.getFilterquery().remove("metadata." + this.property + ".value"); if (prop != null) { LOG.info("Old Date Property: " + prop.toString()); List<BasicDBObject> and = new ArrayList<BasicDBObject>(); and.add(new BasicDBObject("metadata." + this.property + ".value", prop)); and.add(new BasicDBObject(constraintKey, constraintValue)); this.getFilterquery().put("$and", and);// for date... } else { this.getFilterquery().append(constraintKey, constraintValue); } LOG.debug("Date Filter Query adjusted: " + this.getFilterquery().toString()); } else if (p.getType().equals(PropertyType.INTEGER.toString()) || p.getType().equals(PropertyType.FLOAT.toString())) { String width = this.getConfig().get("bin_width"); if (width == null) { String val = (String) this.getFilterquery().get("metadata." + this.property + ".value"); width = inferBinWidth(val) + ""; } map = Constants.NUMERIC_HISTOGRAM_MAP.replace("{1}", this.property).replace("{2}", width); } else { map = Constants.HISTOGRAM_MAP.replace("{}", p.getId()); } LOG.debug("Executing histogram map reduce job with following map:\n{}", map); final DBCollection elements = this.getPersistence().getDB().getCollection(Constants.TBL_ELEMENTS); final MapReduceCommand cmd = new MapReduceCommand(elements, map, Constants.HISTOGRAM_REDUCE, this.getOutputCollection(), this.getType(), this.getFilterquery()); return this.getPersistence().mapreduce(Constants.TBL_ELEMENTS, cmd); } @Override public JobResult run() { return new JobResult(this.execute()); } public static int inferBinWidth(String val) { String[] values = val.split(" - "); int low = Integer.parseInt(values[0]); int high = Integer.parseInt(values[1]); int width = high - low + 1; //because of gte/lte LOG.debug("inferred bin width is {}", width); return width; } }
package trees; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static java.util.Arrays.sort; public class BSTFromInorderAndPostorder { private static void correctPostorder(int[] incorrectPostorder, int[] incorrectInorder) { int[] correctInorder = Arrays.copyOf(incorrectInorder, incorrectInorder.length); sort(correctInorder); for (int i = 0; i < incorrectInorder.length; i++) { if (incorrectInorder[i] != correctInorder[i]) { arraySwap(incorrectPostorder, incorrectInorder[i], correctInorder[i]); } } } private static void arraySwap(int[] incorrectPostorder, int first, int second) { // swap first with second for (int i = 0; i < incorrectPostorder.length; i++) { if (incorrectPostorder[i] == first) { //replace with second incorrectPostorder[i] = second; } else if (incorrectPostorder[i] == second) { //replace with second incorrectPostorder[i] = first; } } } private static TreeNode createTree(int[] inorder, int[] postorder, int start, int end) { if (start <= end) { int nextRootIndexInInorder = findRoot(inorder, postorder, start, end); TreeNode root = new TreeNode(inorder[nextRootIndexInInorder]); root.left = createTree(inorder, postorder, start, nextRootIndexInInorder - 1); root.right = createTree(inorder, postorder, nextRootIndexInInorder + 1, end); return root; } return null; } private static int findRoot(int[] inorder, int[] postorder, int start, int end) { int inorderElementIndexInPostorder = Integer.MIN_VALUE; int nextRootIndexInInorder = 0; for (int i = start; i <= end; i++) { for (int j = 0; j < postorder.length; j++) { if (postorder[j] == inorder[i]) { if ( inorderElementIndexInPostorder < j) { inorderElementIndexInPostorder = j; nextRootIndexInInorder = i; } } } } return nextRootIndexInInorder; } private static void printPostorder(TreeNode root) { if (root == null) return; printPostorder(root.left); printPostorder(root.right); System.out.println(root.val); } public static void main(String args[]) { int[] inorder = new int[]{11, 10, 7, 23, 14, 15, 20, 13}; int[] postorder = new int[]{11, 7, 23, 14, 10, 20, 13, 15}; //7,11,14,13,10,20,23,15 correctPostorder(postorder, inorder); Arrays.sort(inorder); TreeNode root = createTree(inorder, postorder, 0, 7); printPostorder(root); } }
package com.baopinghui.bin.mapper.app; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.baopinghui.bin.dto.ResultDto; import com.baopinghui.bin.entity.BookEntity; import com.baopinghui.bin.entity.CourseEntity; import com.baopinghui.bin.util.MyMapper; public interface BookMapper extends MyMapper<BookEntity> { //添加预约 Integer insertBook(BookEntity b); //删除预约 Integer deleteBook(@Param(value="id")int id); //更新预约 Integer updateBook(BookEntity b); //查询预约 List<Map<String,Object>> selectBook(); //更新预约的状态 Integer updatestatu(@Param(value="id")int id); List<Map<String,Object>> selectBook1(@Param(value="id")String id); }
/* * Copyright 2002-2023 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.scripting.groovy; import java.io.IOException; import java.util.Map; import groovy.lang.Binding; import groovy.lang.GroovyRuntimeException; import groovy.lang.GroovyShell; import org.codehaus.groovy.control.CompilerConfiguration; import org.codehaus.groovy.control.customizers.CompilationCustomizer; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.lang.Nullable; import org.springframework.scripting.ScriptCompilationException; import org.springframework.scripting.ScriptEvaluator; import org.springframework.scripting.ScriptSource; import org.springframework.scripting.support.ResourceScriptSource; /** * Groovy-based implementation of Spring's {@link ScriptEvaluator} strategy interface. * * @author Juergen Hoeller * @since 4.0 * @see GroovyShell#evaluate(String, String) */ public class GroovyScriptEvaluator implements ScriptEvaluator, BeanClassLoaderAware { @Nullable private ClassLoader classLoader; private CompilerConfiguration compilerConfiguration = new CompilerConfiguration(); /** * Construct a new GroovyScriptEvaluator. */ public GroovyScriptEvaluator() { } /** * Construct a new GroovyScriptEvaluator. * @param classLoader the ClassLoader to use as a parent for the {@link GroovyShell} */ public GroovyScriptEvaluator(@Nullable ClassLoader classLoader) { this.classLoader = classLoader; } /** * Set a custom compiler configuration for this evaluator. * @since 4.3.3 * @see #setCompilationCustomizers */ public void setCompilerConfiguration(@Nullable CompilerConfiguration compilerConfiguration) { this.compilerConfiguration = (compilerConfiguration != null ? compilerConfiguration : new CompilerConfiguration()); } /** * Return this evaluator's compiler configuration (never {@code null}). * @since 4.3.3 * @see #setCompilerConfiguration */ public CompilerConfiguration getCompilerConfiguration() { return this.compilerConfiguration; } /** * Set one or more customizers to be applied to this evaluator's compiler configuration. * <p>Note that this modifies the shared compiler configuration held by this evaluator. * @since 4.3.3 * @see #setCompilerConfiguration */ public void setCompilationCustomizers(CompilationCustomizer... compilationCustomizers) { this.compilerConfiguration.addCompilationCustomizers(compilationCustomizers); } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } @Override @Nullable public Object evaluate(ScriptSource script) { return evaluate(script, null); } @Override @Nullable public Object evaluate(ScriptSource script, @Nullable Map<String, Object> arguments) { GroovyShell groovyShell = new GroovyShell( this.classLoader, new Binding(arguments), this.compilerConfiguration); try { String filename = (script instanceof ResourceScriptSource resourceScriptSource ? resourceScriptSource.getResource().getFilename() : null); if (filename != null) { return groovyShell.evaluate(script.getScriptAsString(), filename); } else { return groovyShell.evaluate(script.getScriptAsString()); } } catch (IOException ex) { throw new ScriptCompilationException(script, "Cannot access Groovy script", ex); } catch (GroovyRuntimeException ex) { throw new ScriptCompilationException(script, ex); } } }
package com.z2wenfa.common.sort; import com.z2wenfa.common.base.ISortArithmetic; public class SelectionSort extends ISortArithmetic { @Override public void sort() { selectionSort(arrs); } @Override public String getArithmeticName() { return "选择排序"; } private static void selectionSort(int[] arrs) { for (int i = 0; i < arrs.length; i++) { int lowerIndex = i; for (int j = i; j < arrs.length; j++) { if (arrs[j] < arrs[lowerIndex]) { lowerIndex = j; } } if (lowerIndex != i) { int temp = arrs[i]; arrs[i] = arrs[lowerIndex]; arrs[lowerIndex] = temp; } } } }
package com.detroitlabs.comicview.model; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component public class Cart { private List<Object> cart = new ArrayList<>(); @Override public String toString() { return "Cart{" + "cart=" + cart + '}'; } public List<Object> getCart() { return cart; } public void setCart(List<Object> cart) { this.cart = cart; } public void addToCart(Object obj) { cart.add(obj); } }
package com.metaco.api.exceptions; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.core.header.InBoundHeaders; import junit.framework.Assert; import org.junit.Test; import java.io.ByteArrayInputStream; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; public class MetacoErrorResultTest { @Test public void testGetterSetters() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { MetacoErrorResult errorResult = new MetacoErrorResult(); errorResult.setStatus(200); errorResult.setMetaco_error("error"); Assert.assertEquals(errorResult.getMetaco_error(), "error"); errorResult.setLocation("location"); Assert.assertEquals(errorResult.getLocation(), "location"); errorResult.setMessage("message"); Assert.assertEquals(errorResult.getMessage(), "message"); errorResult.setParameter_name("parameter"); Assert.assertEquals(errorResult.getParameter_name(), "parameter"); } }
/* * Copyright 2013 Basho Technologies Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.basho.riak.client.api.cap; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.Arrays; /** * Encapsulates a Riak vector clock. * @author Russel Brown <russelldb at basho dot com> * @since 1.0 */ public class BasicVClock implements VClock { private final byte[] value; /** * Create a BasicVclock. * @param value the vector clock bytes. NOTE: copies the value * @throws IllegalArgumentException if <code>value</code> is null */ public BasicVClock(final byte[] value) { if (value == null) { throw new IllegalArgumentException("VClock value cannot be null"); } this.value = Arrays.copyOf(value, value.length); } /** * Create a BasicVclock from utf8 String. * @param vclock the vector clock. * @throws IllegalArgumentException if {@code vclock} is null */ public BasicVClock(String vclock) { if (vclock == null) { throw new IllegalArgumentException("VClock value cannot be null"); } this.value = vclock.getBytes(Charset.forName("UTF-8")); } @Override public byte[] getBytes() { return Arrays.copyOf(value, value.length); } @Override public String asString() { try { return new String(value, "UTF-8"); } catch (UnsupportedEncodingException ex) { throw new IllegalStateException(ex); } } @Override public boolean equals(Object o) { if (o != null) { if (o instanceof VClock) { VClock other = (VClock)o; return Arrays.equals(other.getBytes(), value); } } return false; } @Override public int hashCode() { int hash = 3; hash = 67 * hash + Arrays.hashCode(this.value); return hash; } }
package controlPanel; import entityPanel.Book; import java.util.ArrayList; public class BookCatalog { ArrayList<Book> books = new ArrayList<>(); public ArrayList<Book> getAllCatalog(){ books.add(new Book("J. K. Rowling", "Philosopher's Stone", 1997, "fantasy", 10 )); books.add(new Book("J. K. Rowling", "Chamber of Secrets", 1998, "fantasy", 9 )); books.add(new Book("J. K. Rowling", "Prisoner of Azkaban", 1999, "fantasy", 10 )); books.add(new Book("J. K. Rowling", "Goblet of Fire", 2000, "fantasy", 11 )); books.add(new Book("J. K. Rowling", "Order of the Phoenix", 2003, "fantasy", 5 )); books.add(new Book("J. K. Rowling", "Half-Blood Prince", 2005, "fantasy", 2 )); books.add(new Book("J. K. Rowling", "Deathly Hallows", 2007, "fantasy", 6 )); books.add(new Book("Agatha Christie", "Murder on the Orient Express", 1934, "detective", 15 )); books.add(new Book("Agatha Christie", "The Boomerang Clue", 1935, "detective", 15 )); books.add(new Book("Agatha Christie", "The A.B.C. Murders", 1936, "detective", 8 )); books.add(new Book("Agatha Christie", "Murder in Three Acts", 1935, "detective", 3 )); return books; } public String addBook(Book newBook) { books.add(newBook); return "\nBook " + newBook.getTitle() + " created successfully"; } }
package nlp; import nlp.preprocess.DocumentProcessor; import nlp.textrank.TextRankSummarizer; import nlp.utils.Score; import nlp.utils.Sentence; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; public class ArticleSummarizer { private static String fileSeparator = System.getProperty("file.separator"); private DocumentProcessor documentProcessor; private TextRankSummarizer textRankSummarizer; public ArticleSummarizer() { documentProcessor = new DocumentProcessor(); textRankSummarizer = new TextRankSummarizer(); } public String summarize(String filePath, int maxWords) { String article = documentProcessor.convertToString(filePath); StringBuilder stringBuilder = new StringBuilder(); List<Sentence> sentences = documentProcessor.retrieveSentencesFromArticle(article); List<Score> finalScores = calculateSentencesScores(sentences, maxWords); finalScores.forEach(score -> stringBuilder.append(sentences.get(score.getSentenceId()).toString().trim()).append("\n")); return stringBuilder.toString(); } private List<Score> calculateSentencesScores(List<Sentence> sentences, int maxWords) { Map<Integer, Score> sentencesScores = new HashMap<>(); List<Sentence> sentencesCopy = new ArrayList<>(sentences); String idfFileName = String.format(".%sresources%sus_presidents.csv", fileSeparator, fileSeparator); List<Score> scores = textRankSummarizer.rankSentences(sentences, documentProcessor, idfFileName); scores.forEach(score -> sentencesScores.put(score.getSentenceId(), score)); List<Score> finalScores = new ArrayList<>(); int currentWordCount = 0; maxWords = Math.max(maxWords, 0); while (!sentencesCopy.isEmpty()) { int sentenceId = getBestSentenceId(sentencesCopy, sentencesScores); if (sentenceId == -1) { break; } Sentence bestSentence = sentences.get(sentenceId); finalScores.add(sentencesScores.get(bestSentence.getSentenceId())); currentWordCount += bestSentence.getWordCount(); sentencesCopy.remove(bestSentence); if (currentWordCount > maxWords) { break; } } return finalScores; } private int getBestSentenceId(List<Sentence> sentences, Map<Integer, Score> sentencesScores) { int bestSentenceId = -1; double bestScore = 0; for (Sentence sentence : sentences) { Score score = sentencesScores.get(sentence.getSentenceId()); if (score != null && score.getScore() > bestScore) { bestSentenceId = score.getSentenceId(); bestScore = score.getScore(); } } return bestSentenceId; } public static void main(String[] args) { Path filesDirectoryPath = Paths.get(String.format(".%sarticles", fileSeparator)); File filesDirectory = new File(filesDirectoryPath.toString()); File[] files = filesDirectory.listFiles(); ArticleSummarizer articleSummarizer = new ArticleSummarizer(); if (files != null) { for (File file : files) { String fileName = file.getName(); Path filePath = Paths.get(String.format("%s%s%s", filesDirectoryPath, fileSeparator, fileName)); Path summaryArticlePath = Paths.get(String.format(".%s%s%s%s", fileSeparator, filesDirectoryPath, fileSeparator, fileName.replace(".txt", "_Summary.txt"))); try { File summaryArticleFile = new File(summaryArticlePath.toString()); if (!summaryArticleFile.exists()) { Files.createFile(summaryArticlePath); } String summary = articleSummarizer.summarize(filePath.toString(), 100); try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(summaryArticleFile))) { bufferedWriter.write(summary); } } catch (IOException e) { Logger.getAnonymousLogger().warning(String.format("Unable to write summary into a file: %s", e.getMessage())); } } } } }
package io.vepo.access.infra; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; import javax.annotation.PostConstruct; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.eclipse.microprofile.config.inject.ConfigProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @ApplicationScoped public class PasswordEncrypter { private static final Logger logger = LoggerFactory.getLogger(PasswordEncrypter.class); private SecretKeySpec secretKey; private byte[] key; @Inject @ConfigProperty(name = "PASSWORD_SECRET_KEY", defaultValue = "MY-SECRET-KEY") private String secretKeyPlain; public PasswordEncrypter() { logger.info("Creating PasswordEncrypter it should be one for all application!!!!"); } @PostConstruct public void setup() { MessageDigest sha = null; try { key = secretKeyPlain.getBytes("UTF-8"); sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key, 16); secretKey = new SecretKeySpec(key, "AES"); } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { logger.error("Error initializing Password Encrypter!", e); } } public String encrypt(String strToEncrypt) { try { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8"))); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) { logger.error("Error encrypting password!", e); throw new RuntimeException(e); } } public String decrypt(String strToDecrypt) { try { Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, secretKey); return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt))); } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) { logger.error("Error deencrypting password!", e); throw new RuntimeException(e); } } }
package riomaissaude.felipe.com.br.riosaude.models; import com.google.android.gms.maps.model.LatLng; import com.google.maps.android.clustering.ClusterItem; /** * Created by felipe on 9/13/15. */ public class Estabelecimento implements ClusterItem { private int id; private String media; private String cnes; private String cnpj; private String razaoSocial; private String nomeFantasia; private String logradouro; private String numero; private String complemento; private String bairro; private String cep; private String telefone; private String fax; private String email; private String latitude; private String longitude; private String dataAtualizacaoCoordenadas; private String codigoEsferaAdministrativa; private String esferaAdministrativa; private String codigoDaAtividade; private String atividadeDestino; private String codigoNaturezaOrganizacao; private String naturezaOrganizacao; private String tipoUnidade; private String tipoEstabelecimento; private String statusEstabelecimento; private String dataAlteracaoStatusEstabelecimento; public Estabelecimento() { } public Estabelecimento(int id, String media, String cnes, String cnpj, String razaoSocial, String nomeFantasia, String logradouro, String numero, String complemento, String bairro, String cep, String telefone, String fax, String email, String latitude, String longitude, String dataAtualizacaoCoordenadas, String codigoEsferaAdministrativa, String esferaAdministrativa, String codigoDaAtividade, String atividadeDestino, String codigoNaturezaOrganizacao, String naturezaOrganizacao, String tipoUnidade, String tipoEstabelecimento, String statusEstabelecimento, String dataAlteracaoStatusEstabelecimento) { this.id = id; this.media = media; this.cnes = cnes; this.cnpj = cnpj; this.razaoSocial = razaoSocial; this.nomeFantasia = nomeFantasia; this.logradouro = logradouro; this.numero = numero; this.complemento = complemento; this.bairro = bairro; this.cep = cep; this.telefone = telefone; this.fax = fax; this.email = email; this.latitude = latitude; this.longitude = longitude; this.dataAtualizacaoCoordenadas = dataAtualizacaoCoordenadas; this.codigoEsferaAdministrativa = codigoEsferaAdministrativa; this.esferaAdministrativa = esferaAdministrativa; this.codigoDaAtividade = codigoDaAtividade; this.atividadeDestino = atividadeDestino; this.codigoNaturezaOrganizacao = codigoNaturezaOrganizacao; this.naturezaOrganizacao = naturezaOrganizacao; this.tipoUnidade = tipoUnidade; this.tipoEstabelecimento = tipoEstabelecimento; this.statusEstabelecimento = statusEstabelecimento; this.dataAlteracaoStatusEstabelecimento = dataAlteracaoStatusEstabelecimento; } public String getCnes() { return cnes; } public void setCnes(String cnes) { this.cnes = cnes; } public String getCnpj() { return cnpj; } public void setCnpj(String cnpj) { this.cnpj = cnpj; } public String getRazaoSocial() { return razaoSocial; } public void setRazaoSocial(String razaoSocial) { this.razaoSocial = razaoSocial; } public String getNomeFantasia() { return nomeFantasia; } public void setNomeFantasia(String nomeFantasia) { this.nomeFantasia = nomeFantasia; } public String getLogradouro() { return logradouro; } public void setLogradouro(String logradouro) { this.logradouro = logradouro; } public String getNumero() { return numero; } public void setNumero(String numero) { this.numero = numero; } public String getComplemento() { return complemento; } public void setComplemento(String complemento) { this.complemento = complemento; } public String getBairro() { return bairro; } public void setBairro(String bairro) { this.bairro = bairro; } public String getCep() { return cep; } public void setCep(String cep) { this.cep = cep; } public String getTelefone() { return telefone; } public void setTelefone(String telefone) { this.telefone = telefone; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getDataAtualizacaoCoordenadas() { return dataAtualizacaoCoordenadas; } public void setDataAtualizacaoCoordenadas(String dataAtualizacaoCoordenadas) { this.dataAtualizacaoCoordenadas = dataAtualizacaoCoordenadas; } public String getCodigoEsferaAdministrativa() { return codigoEsferaAdministrativa; } public void setCodigoEsferaAdministrativa(String codigoEsferaAdministrativa) { this.codigoEsferaAdministrativa = codigoEsferaAdministrativa; } public String getEsferaAdministrativa() { return esferaAdministrativa; } public void setEsferaAdministrativa(String esferaAdministrativa) { this.esferaAdministrativa = esferaAdministrativa; } public String getCodigoDaAtividade() { return codigoDaAtividade; } public void setCodigoDaAtividade(String codigoDaAtividade) { this.codigoDaAtividade = codigoDaAtividade; } public String getAtividadeDestino() { return atividadeDestino; } public void setAtividadeDestino(String atividadeDestino) { this.atividadeDestino = atividadeDestino; } public String getCodigoNaturezaOrganizacao() { return codigoNaturezaOrganizacao; } public void setCodigoNaturezaOrganizacao(String codigoNaturezaOrganizacao) { this.codigoNaturezaOrganizacao = codigoNaturezaOrganizacao; } public String getNaturezaOrganizacao() { return naturezaOrganizacao; } public void setNaturezaOrganizacao(String naturezaOrganizacao) { this.naturezaOrganizacao = naturezaOrganizacao; } public String getTipoUnidade() { return tipoUnidade; } public void setTipoUnidade(String tipoUnidade) { this.tipoUnidade = tipoUnidade; } public String getTipoEstabelecimento() { return tipoEstabelecimento; } public void setTipoEstabelecimento(String tipoEstabelecimento) { this.tipoEstabelecimento = tipoEstabelecimento; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getMedia() { return media; } public void setMedia(String media) { this.media = media; } public String getStatusEstabelecimento() { return statusEstabelecimento; } public void setStatusEstabelecimento(String statusEstabelecimento) { this.statusEstabelecimento = statusEstabelecimento; } public String getDataAlteracaoStatusEstabelecimento() { return dataAlteracaoStatusEstabelecimento; } public void setDataAlteracaoStatusEstabelecimento(String dataAlteracaoStatusEstabelecimento) { this.dataAlteracaoStatusEstabelecimento = dataAlteracaoStatusEstabelecimento; } @Override public String toString() { return "Estabelecimento{" + "id=" + id + ", media='" + media + '\'' + ", cnes='" + cnes + '\'' + ", cnpj='" + cnpj + '\'' + ", razaoSocial='" + razaoSocial + '\'' + ", nomeFantasia='" + nomeFantasia + '\'' + ", logradouro='" + logradouro + '\'' + ", numero='" + numero + '\'' + ", complemento='" + complemento + '\'' + ", bairro='" + bairro + '\'' + ", cep='" + cep + '\'' + ", telefone='" + telefone + '\'' + ", fax='" + fax + '\'' + ", email='" + email + '\'' + ", latitude='" + latitude + '\'' + ", longitude='" + longitude + '\'' + ", dataAtualizacaoCoordenadas='" + dataAtualizacaoCoordenadas + '\'' + ", codigoEsferaAdministrativa='" + codigoEsferaAdministrativa + '\'' + ", esferaAdministrativa='" + esferaAdministrativa + '\'' + ", codigoDaAtividade='" + codigoDaAtividade + '\'' + ", atividadeDestino='" + atividadeDestino + '\'' + ", codigoNaturezaOrganizacao='" + codigoNaturezaOrganizacao + '\'' + ", naturezaOrganizacao='" + naturezaOrganizacao + '\'' + ", tipoUnidade='" + tipoUnidade + '\'' + ", tipoEstabelecimento='" + tipoEstabelecimento + '\'' + ", statusEstabelecimento='" + statusEstabelecimento + '\'' + ", dataAlteracaoStatusEstabelecimento=" + dataAlteracaoStatusEstabelecimento + '}'; } @Override public LatLng getPosition() { return new LatLng(Double.parseDouble(this.latitude), Double.parseDouble(this.longitude)); } }
/** * */ package com.egame.app.adapters; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; import com.egame.R; import com.egame.beans.ContactsBean; /** * 描述:联系人列表数据适配器 * * @author LiuHan * @version 1.0 create date :Sat Dec 31 2011 */ public class ContactsAdapter extends BaseAdapter { /** 上下文 */ private Context mContext; /** 联系人列表 */ private List<ContactsBean> mContactsList = new ArrayList<ContactsBean>(); /** 联系人实体类对象 */ private ContactsBean mContactsBean; /** * 构造函数 */ public ContactsAdapter(Context mContext, List<ContactsBean> mContactsList) { this.mContext = mContext; this.mContactsList = mContactsList; } /* * (non-Javadoc) * * @see android.widget.Adapter#getCount() */ @Override public int getCount() { return mContactsList.size(); } /* * (non-Javadoc) * * @see android.widget.Adapter#getItem(int) */ @Override public ContactsBean getItem(int position) { return mContactsList.get(position); } /* * (non-Javadoc) * * @see android.widget.Adapter#getItemId(int) */ @Override public long getItemId(int position) { return position; } /* * (non-Javadoc) * * @see android.widget.Adapter#getView(int, android.view.View, * android.view.ViewGroup) */ @Override public View getView(int position, View convertView, ViewGroup parent) { mContactsBean = getItem(position); LinearLayout itemView = (LinearLayout) LayoutInflater.from(mContext) .inflate(R.layout.egame_contacts_list_item, null); TextView mContactsName = (TextView) itemView .findViewById(R.id.m_contacts_name); mContactsName.setText(mContactsBean.getmContactsName()); TextView mContactsPhone = (TextView) itemView .findViewById(R.id.m_contacts_phone); mContactsPhone.setText(mContactsBean.getmContactsPhone()); TextView mContactsIcon = (TextView) itemView .findViewById(R.id.m_contacts_icon); if (mContactsBean.ismIsSelect() == false) { mContactsIcon .setBackgroundResource(R.drawable.egame_select_contactsoff); } else { mContactsIcon .setBackgroundResource(R.drawable.egame_lselect_contactson); } return itemView; } }
package com.example.goodjoob.ui; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.example.goodjoob.R; import com.example.goodjoob.TecnicoPerfil; import com.example.goodjoob.db.TecnicoAdapter; import com.example.goodjoob.model.Handle; import com.example.goodjoob.model.Tecnico; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class ListarMainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { //conexao ListView listView; List<Tecnico> tecnicoList; private ArrayAdapter<Tecnico> adapter; private RequestQueue requestQueue; private static final String URL = "http://conect.vitaldata.com.br/tentativa5/listarusuarios2.php"; //private StringRequest request; //conexao @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_listar_main); listView = (ListView) findViewById(R.id.listaTecnicos); tecnicoList = new ArrayList<>(); showList(); } private void showList() { //requestQueue = Volley.newRequestQueue(this); StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); JSONArray array = jsonObject.getJSONArray("ListaTecnicos"); for (int i = 0; i <array.length(); i++){ JSONObject provObj = array.getJSONObject(i); Tecnico t = new Tecnico(provObj.getString("id_usuario"),provObj.getString("nome"),provObj.getString("email"),provObj.getString("telefone"),provObj.getInt("qtd_avaliacao"),provObj.getDouble("avaliacao")); tecnicoList.add(t); } adapter = new TecnicoAdapter(tecnicoList,getApplication()); listView.setAdapter(adapter); listView.setOnItemClickListener(ListarMainActivity.this); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }){ }; //requestQueue.add(request); Handle.getInstance(getApplicationContext()).addToRequestQue(stringRequest); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(ListarMainActivity.this, TecnicoPerfil.class); intent.putExtra("posicao",position); startActivity(intent); } }
package model.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable public class PPCPK implements Serializable{ @Column(name="CD_CURSO",nullable=false) private Integer codigoCurso; @Column(name="NR_VERSAO",nullable=false) private Integer versao; public Integer getCodigoCurso() { return codigoCurso; } public void setCodigoCurso(Integer codigoCurso) { this.codigoCurso = codigoCurso; } public Integer getVersao() { return versao; } public void setVersao(Integer versao) { this.versao = versao; } }
package utils; public class Utils { public static String implode(String[] array, String sep) { if (array.length == 0) return ""; String str = array[0]; for (int i = 1; i < array.length; i++) { str += sep + array[i]; } return str; } }
package collection; import org.junit.Test; import java.util.*; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.assertThat; public class ListTest { @Test public void createASimpleList(){ List<Integer> integers = new ArrayList<>(); integers.add(0); integers.add(0); assertThat(integers.size(),equalTo(2)); } @Test public void aListIsOrdered(){ Iterator<Integer> it = generateListOfIntegers().iterator(); assertThat(it.next(), equalTo(5)); assertThat(it.next(), equalTo(1)); assertThat(it.next(), equalTo(4)); } @Test public void insertingNullInAListIsAllowed(){ List<Integer> integers = new ArrayList<>(); integers.add(null); assertThat(integers.get(0), equalTo(null)); } @Test public void insertElementInAListPushesAllTheOtherFurther(){ List<Integer> integers = generateListOfIntegers(); integers.add(0,0); Iterator<Integer> it = integers.iterator(); assertThat(it.next(), equalTo(0)); assertThat(it.next(), equalTo(5)); assertThat(it.next(), equalTo(1)); assertThat(it.next(), equalTo(4)); } @Test public void addingAllElementsOfAListToAnotherOne(){ List<Integer> srcList = generateListOfIntegers(); List<Integer> dstList = new ArrayList<>(); dstList.addAll(srcList); assertThat(srcList, equalTo(dstList)); } @Test public void findIndexOfFirstOccurence(){ List<Integer> integers = generateListOfIntegersWithRepeats(); assertThat(integers.indexOf(5), equalTo(0)); } @Test public void findIndexOfLastOccurence(){ List<Integer> integers = generateListOfIntegersWithRepeats(); assertThat(integers.lastIndexOf(5), equalTo(3)); } @Test public void clearAList(){ List<Integer> integers = generateListOfIntegers(); integers.clear(); assertThat(integers.isEmpty(), equalTo(true)); } @Test public void retainTheIntersectionOfTwoLists(){ List<Integer> integers = generateListOfIntegers(); List<Integer> integersToKeep = new ArrayList<>(); Collections.addAll(integersToKeep, 4,6); integers.retainAll(integersToKeep); assertThat(integers.size(), equalTo(1)); assertThat(integers.contains(4), equalTo(true)); } @Test public void extractASubListFromAList(){ List<Integer> integers = generateListOfIntegers(); List<Integer> integersSublist = integers.subList(0, 2); List<Integer> expectedSublist = new ArrayList<>(); Collections.addAll(expectedSublist,5,1); assertThat(integersSublist, equalTo(expectedSublist)); } @Test public void convertListToArray(){ List<Integer> integerList = generateListOfIntegers(); Integer[] integerArray = integerList.toArray(new Integer[0]); assertThat(integerArray, equalTo(new int[] {5,1,4})); } @Test public void convertArrayToList(){ Integer[] integerArray = {5,1,4}; List<Integer> expectedList = generateListOfIntegers(); assertThat(Arrays.asList(integerArray), equalTo(expectedList)); } @Test public void sortAList(){ List<Integer> integers = generateListOfIntegers(); List<Integer> expectedSortedIntegers = Arrays.asList(new Integer[] {1,4,5}); Collections.sort(integers); assertThat(integers, equalTo(expectedSortedIntegers)); } @Test public void sortAListWithComparator(){ Comparator<Stone> comparator = new Comparator<Stone>(){ @Override public int compare(Stone s1, Stone s2) { return s1.compareTo(s2); } }; List<Stone> stones = generateListOfPreciousStones(); Collections.sort(stones, comparator); assertThat(stones, equalTo(generateListOfPreciousStonesSorted())); } @Test public void sortAListWithComparatorLambdaStyle(){ Comparator<Stone> comparator = (stone1, stone2) -> stone1.compareTo(stone2); List<Stone> stones = generateListOfPreciousStones(); Collections.sort(stones, comparator); assertThat(stones, equalTo(generateListOfPreciousStonesSorted())); } @Test public void useStreamToGetFirstElement(){ List<Integer> integers = generateListOfIntegers(); Optional<Integer> first = integers.stream().findFirst(); assertThat(first.get(), equalTo(5)); } private List<Integer> generateListOfIntegers(){ List<Integer> integers = new ArrayList<>(); Collections.addAll(integers, 5,1,4); return integers; } private List<Integer> generateListOfIntegersWithRepeats(){ List<Integer> integers = new ArrayList<>(); Collections.addAll(integers, 5,1,4,5,1,4); return integers; } private List<Stone> generateListOfPreciousStones(){ List<Stone> stones = new ArrayList<>(); stones.add(Stone.gold()); stones.add(Stone.copper()); stones.add(Stone.diamond()); return stones; } private List<Stone> generateListOfPreciousStonesSorted(){ List<Stone> stones = new ArrayList<>(); stones.add(Stone.copper()); stones.add(Stone.gold()); stones.add(Stone.diamond()); return stones; } }
package search; import database.DataBase; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableItem; import java.sql.*; public class InspectorSearch { private Table table; private PreparedStatement statement; private Connection connection; private String showInspector = "SELECT fullName, inspectorRank, carID " + "FROM inspector " + "JOIN checkup ON inspector.inspectorID = checkup.inspectorID " + "WHERE checkupDate BETWEEN ? AND ?;"; public InspectorSearch(Table table){ this.table = table; } public void searchInspector (String fromDate, String tillDate) throws SQLException { DataBase db = new DataBase(); connection = db.getOpenedConnection(); statement = connection.prepareStatement(showInspector); statement.setDate(1, Date.valueOf(fromDate)); statement.setDate(2, Date.valueOf(tillDate)); ResultSet resultSet = statement.executeQuery(); while (resultSet.next()) { TableItem item = new TableItem(table, SWT.NONE); item.setText(0, resultSet.getString(1)); item.setText(1, resultSet.getString(2)); item.setText(2, String.valueOf(resultSet.getInt(3))); } resultSet.close(); statement.close(); connection.close(); } }
package com.springboot.web.accountmanagement; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import com.springboot.web.accountmanagement.service.AccountManagementManipulationService; @RestController public class AccountManagementCrudController { @Autowired private AccountManagementManipulationService m_manipulationService; // @PostMapping(value = "/account/account-management/create-account") // public }
// https://www.youtube.com/watch?v=AFtXLUn_TZg class Solution { public List<Integer> pancakeSort(int[] arr) { List<Integer> result = new ArrayList(); for (int i = arr.length - 1; i > 0; i--){ for (int j = 1; j <= i; j++) { if (arr[j] == i + 1){ flip(arr, j); result.add(j + 1); break; } } flip(arr, i); result.add(i + 1); } return result; } private void flip(int[] arr, int idx) { for(int i = 0; i <= idx / 2; i++) { int tmp = arr[i]; arr[i] = arr[idx - i]; arr[idx - i] = tmp; } } }
package com.example.bankingapp; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; public class transfer extends AppCompatActivity { //declare widgets Button transfer; TextView current,savings; Spinner transferoption; EditText transferamount; dbHelper sqliteHelper; Double transfer_amount,currentbalance,savingsbalance,newcurrentbalance,newsavingsbalance; String newcurbal,newsavbal; int spinnerchoice; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.transfer); } }
/** * @(#) Copier.java */ package command; import receiver.Buffer; /** * La commande qui exécute l'action copier() du buffer. */ public class Copier extends Command { public Copier(Buffer buffer) { this.buffer = buffer; } @Override public void execute() { buffer.copier(); } }
package com.madrapps.dagger.test; import com.madrapps.dagger.models.Car; import com.madrapps.dagger.models.Vehicle; import dagger.Binds; import dagger.Lazy; import dagger.Module; import dagger.Provides; import java.util.Set; @Module public abstract class TestingBindsModule { @Binds abstract Vehicle getCar(Car car); }
/* * Using FileOutputStream and FileInputStream to read and writebytes to and from file. * Uisng FileWriter and FileReader to read and write char to and from file. * */ package File; import java.io.BufferedOutputStream; import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; /** * * @author YNZ */ public class BufferedStream { public static void main(String[] args) throws IOException { String content = "Java is verbose!"; try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("my.txt"))) { bos.write(content.getBytes()); bos.flush(); } try (BufferedWriter bw = new BufferedWriter(new FileWriter("my2.txt"))) { bw.write("Java has some improvements"); bw.flush(); } try (BufferedWriter bw = new BufferedWriter(new FileWriter("my2.txt"))) { bw.write("Java has some improvements"); bw.flush(); } } }
package kr.ac.kopo.day09; public class EmployeeMain { public static void main(String[] args) { Employee.printTotalEmployee(); //e.print~~이렇게 하면 여기서 실행안돼. // 하지만 0명이란것도 찍을 수 있어야하니까! 그래서 접근법은 클래스명.static메소드 Employee e = new Employee("홍길동", 3200, "사원"); e.info(); Employee e2 = new Employee("강길동", 4000, "주임"); e2.info(); Employee e3 = new Employee("윤길동", 3600, "사원"); e3.info(); System.out.println(e.getName()); //이제 메인메소드에서는 객체 생성과 메소드 사용 이렇게만 남게 된다. //그럼에도 아직은 e.name 이런식으로 접근은 아직 가능해. //e.name을 못쓰게 하고 싶다? 그럼 접근제한자를 활용하면돼. //public:누구나 다 접근할 수 있어, private:내클래스 내에서만 쓰게할거야. } }
package com.legado.grupo.dao; //librerias import com.legado.grupo.dao.I.Crud; import com.legado.grupo.dao.I.FacultadRepositorio; import com.legado.grupo.dom.Facultad; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; // fin librerias @Repository public class FacultadDAO implements Crud<Facultad> { // atributos globales @Autowired private FacultadRepositorio repositorio; //agrega una facultad public void agregar(Facultad facultad) throws Exception { if (existe(facultad)) {//valida facultades existentes throw new Exception("La facultad " + facultad.getNombre() + " ya existe!"); } repositorio.save(facultad); } // busca facultad por id @Override public Facultad buscarPorID(int id) { return repositorio.findOne(id); } //busca facultad por nombre public Facultad buscarPorNombre(String nombre) { return repositorio.findByNombre(nombre); } //actualiza una facultad @Override public void actualizar(Facultad o) { repositorio.save(o); } //elimina facultad mediante id @Override public void eliminarPorId(int id) { if (existe(id)) { repositorio.delete(id); } } //elimina todas las facultades @Override public void eliminarTodo() { repositorio.deleteAll(); } //obtenemos una lista con todas las facultades @Override public List<Facultad> listar() { return (List<Facultad>) repositorio.findAll(); } //verifica si existe una facultad por id @Override public boolean existe(int id) { return repositorio.exists(id); } //verifica si existe una facultad mediante nombre public boolean existe(Facultad facultad) { if (repositorio.findByNombre(facultad.getNombre()) != null) { return true; } return false; } }
import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Window extends JFrame { private JButton buttonGrid[][]; private Color player; private boolean isSingle; public Window(boolean isSingle) { super("Connect4"); buttonGrid = new JButton[7][7]; player = Color.RED; this.isSingle = isSingle; JPanel gamePanel = new JPanel(); gamePanel.setLayout(new GridLayout(7, 7)); for (int row = 0; row < 7; row++) { for (int col = 0; col < 7; col++) { buttonGrid[row][col] = new JButton(""); if (row == 0) { buttonGrid[row][col].setText("v"); buttonGrid[row][col].setFont(new Font("Arial", Font.PLAIN, 45)); buttonGrid[row][col].addActionListener(buttonListener); buttonGrid[row][col].setFocusPainted(false); } else { buttonGrid[row][col].setEnabled(false); } buttonGrid[row][col].setContentAreaFilled(false); buttonGrid[row][col].setOpaque(true); buttonGrid[row][col].setBackground(Color.WHITE); gamePanel.add(buttonGrid[row][col]); } } setSize(500, 500); setContentPane(gamePanel); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } /** * Listener for executing moves as buttons are pressed */ ActionListener buttonListener = (ActionEvent e) -> { for (int i = 0; i < buttonGrid.length; i++) { if (buttonGrid[0][i].equals(e.getSource())) { for (int j = buttonGrid.length-1; j > 0; j--) { if (buttonGrid[j][i].getBackground().equals(Color.WHITE)) { buttonGrid[j][i].setBackground(player); player = player.equals(Color.RED) ? Color.BLUE : Color.RED; EndState playerWon = isVictory(buttonGrid); if (playerWon != null) { endScreen(); } if (isSingle && playerWon == null) { // ai move int bestMove[] = Minimax.computerMove(buttonGrid); buttonGrid[bestMove[0]][bestMove[1]].setBackground(player); EndState computerWon = isVictory(buttonGrid); if (computerWon != null) { endScreen(); } player = player.equals(Color.RED) ? Color.BLUE : Color.RED; } break; } } break; } } }; public void endScreen() { for (int i = 0; i < buttonGrid.length; i++) { buttonGrid[0][i].setEnabled(false); } } public static EndState isVictory(JButton board[][]) { boolean freespace = false; for (int row = 1; row < board.length; row++) { for (int col = 0; col < board.length; col++) { Color color = board[row][col].getBackground(); if (color.equals(Color.WHITE)) { freespace = true; continue; } // Horizontal if (col + 3 < board.length && board[row][col+1].getBackground().equals(color) && board[row][col+2].getBackground().equals(color) && board[row][col+3].getBackground().equals(color)) { int points[][] = { {row, col}, {row, col+1}, {row, col+2}, {row, col+3} }; return new EndState(color, points); } if (row + 3 < board.length) { // Vertical if (board[row+1][col].getBackground().equals(color) && board[row+2][col].getBackground().equals(color) && board[row+3][col].getBackground().equals(color)) { int points[][] = { {row, col}, {row, col+1}, {row, col+2}, {row, col+3} }; return new EndState(color, points); } // Diagnal right if (col + 3 < board.length && board[row+1][col+1].getBackground().equals(color) && board[row+2][col+2].getBackground().equals(color) && board[row+3][col+3].getBackground().equals(color)) { int points[][] = { {row, col}, {row, col+1}, {row, col+2}, {row, col+3} }; return new EndState(color, points); } // Diagnal left if (col -3 >= 0 && board[row+1][col-1].getBackground().equals(color) && board[row+2][col-2].getBackground().equals(color) && board[row+3][col-3].getBackground().equals(color)) { int points[][] = { {row, col}, {row, col+1}, {row, col+2}, {row, col+3} }; return new EndState(color, points); } } } } if (!freespace) { return new EndState(Color.WHITE); // tie } return null; // unresolved } }
package me.sh4rewith.config.mail; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.Date; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.MimeMessage; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import org.springframework.mail.MailException; import org.springframework.mail.MailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import org.springframework.mail.javamail.MimeMessageHelper; @Configuration @Profile("prod-mail") public class SpringMailJndiConfig { @Bean public MailSender mailSender() throws MailException, MessagingException, NamingException, UnknownHostException { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setSession(jndiMailSession()); mailSender.send(initMessage(mailSender)); return mailSender; } private MimeMessage initMessage(JavaMailSenderImpl mailSender) throws MessagingException, UnknownHostException { final MimeMessage mimeMessage = mailSender.createMimeMessage(); final MimeMessageHelper message = new MimeMessageHelper(mimeMessage); message.setFrom("admin@sh4rewith.me"); message.setTo("admin@sh4rewith.me"); message.setSubject("Sh4rewith.me: Application Bootstrap"); message.setText("Application started: " + new SimpleDateFormat().format(new Date()) + " from " + InetAddress.getLocalHost().getHostName()); return mimeMessage; } @Bean public Session jndiMailSession() throws NamingException { Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); return (Session) envCtx.lookup("mail/Session"); } }
package ninja.pelirrojo.takibat.irc; public class ParsedLine{ protected final String raw; protected ParsedLine(String raw){ this.raw = raw; } protected static ParsedLine parse(String s){ try{ if(s.indexOf(" PRIVMSG ") > 1 || s.indexOf(" NOTICE ") > 1){ String[] sp = s.split(":",3); String[] pr = sp[1].split(" "); User u = User.parse(pr[0]); String dest = pr[2]; if(dest.equals(IRCConnection.instance.myNick) || dest.equals("*")) return new PrivMsg(s,u,sp[2]); // TODO Check this else return new ChanMsg(s,u,pr[2],sp[2]); } if(s.indexOf(" MODE ") > 1){ return new ModeLine(s); } if(s.indexOf(" 372 ") > 1){ // TODO MOTD } if(s.indexOf(" 376 ") > 1){ // TODO End of MOTD } if(s.indexOf(" 332 ") > 1){ // TODO Set Topic on the Channel } if(s.indexOf(" 333 ") > 1){ // TODO Created? } if(s.indexOf(" 353 ") > 1){ // TODO Members } } catch(Exception e){ return new ParsedLine(s); } return new ParsedLine(s); } public String toString(){ return raw; } }
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) package com.pointinside.android.app.util; import android.content.Context; import android.content.res.Resources; import android.text.format.Time; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.GregorianCalendar; public class DateUtils { public DateUtils() { } public static String formatRelativeDate(Context context, long l, long l1) { Time time = new Time(); time.set(l); Time time1 = new Time(); time1.set(l1); int i = Time.getJulianDay(l, time.gmtoff); int j = Math.abs(Time.getJulianDay(l1, time1.gmtoff) - i); boolean flag; Resources resources; if(l1 > l) flag = true; else flag = false; resources = context.getResources(); if(j == 0) return resources.getString(0x7f06005f); if(!flag) { if(j == 1) return resources.getString(0x7f060060); if(j < 7) return android.text.format.DateUtils.formatDateTime(context, l, 2); } return android.text.format.DateUtils.formatDateTime(context, l, 16); } public static String getFormattedTime(String s) { java.util.Date date; try { date = TIME_PARSER.parse(s); } catch(ParseException parseexception) { return s; } return TIME_FORMATTER.format(date); } public static String getLongDate(String s) { java.util.Date date; try { date = DB_FORMATTER.parse(s); } catch(ParseException parseexception) { return s; } return LONG_DATE_FORMATTER.format(date); } public static String getShortDate(String s) { java.util.Date date; try { date = DB_FORMATTER.parse(s); } catch(ParseException parseexception) { return s; } return SHORT_DATE_FORMATTER.format(date); } public static String getTimeFromMinutes(int i) { GregorianCalendar gregoriancalendar = new GregorianCalendar(); gregoriancalendar.set(11, 0); gregoriancalendar.set(12, i); return TIME_FORMATTER.format(gregoriancalendar.getTime()); } public static final SimpleDateFormat DB_FORMATTER = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); public static final SimpleDateFormat DEAL_PARSER = new SimpleDateFormat("yyyyMMdd"); public static final SimpleDateFormat LONG_DATE_FORMATTER = new SimpleDateFormat("M/d/yy h:mm a"); public static final SimpleDateFormat SHORT_DATE_FORMATTER = new SimpleDateFormat("M/d/yy"); public static final SimpleDateFormat TIME_FORMATTER = new SimpleDateFormat("h:mm a"); public static final SimpleDateFormat TIME_PARSER = new SimpleDateFormat("hh:mm:ss"); }
package br.com.fitNet.model; import java.util.Date; import java.util.LinkedHashSet; import java.util.Set; public class Contrato { private int idContrato; private String tipo;// Receberá "Plano ou Mensalista diacordo com a seleção no cadastro do Aluno. private double valor; private Date Vencimento; private int vencimentoEmDias; private double descontoEspecial; public Set<String> listaModAluno = new LinkedHashSet<>(); public Set<String> getListaModAluno() { return listaModAluno; } public Contrato(){}; public Contrato(int idContrato){ this.idContrato = idContrato; } public int getVencimentoEmDias() { return vencimentoEmDias; } public void setVencimentoEmDias(int vencimentoEmDias) { this.vencimentoEmDias = vencimentoEmDias; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } public double getValor() { return valor; } public void setValor(double valor) { this.valor = valor; } public Date getVencimento() { return Vencimento; } public void setVencimento(Date vencimento) { Vencimento = vencimento; } public int getIdContrato() { return idContrato; } public void setIdContrato(int idContrato) { this.idContrato = idContrato; } public double getDescontoEspecial() { return descontoEspecial; } public void setDescontoEspecial(double descontoEspecial) { this.descontoEspecial = descontoEspecial; } public void setListaModAluno(Set<String> listaModAluno) { this.listaModAluno = listaModAluno; } @Override public String toString() { return "Contrato " + listaModAluno + "\n"; } }
package com.ranpeak.ProjectX.activity.lobby.forGuestUsers; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Button; import android.widget.ImageView; import com.ranpeak.ProjectX.R; import com.ranpeak.ProjectX.activity.search.SearchTaskAlertDialog; import com.ranpeak.ProjectX.activity.interfaces.Activity; import com.ranpeak.ProjectX.activity.lobby.forAuthorizedUsers.LobbyActivity; import com.ranpeak.ProjectX.activity.lobby.forGuestUsers.adapter.ViewPagerAdapter; import com.ranpeak.ProjectX.activity.lobby.forGuestUsers.fragments.FragmentResumes; import com.ranpeak.ProjectX.activity.lobby.forGuestUsers.fragments.FragmentTasks; import com.ranpeak.ProjectX.activity.logIn.LogInActivity; import com.ranpeak.ProjectX.settings.SharedPrefManager; public class LobbyForGuestActivity extends AppCompatActivity implements Activity { private final static int LOBBY_FOR_GUEST_ACTIVITY = R.layout.activity_lobby_for_guest; private TabLayout tabLayout; private ViewPager viewPager; private ImageView imageView; private Button floatingLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(LOBBY_FOR_GUEST_ACTIVITY); if (SharedPrefManager.getInstance(this).isLoggedIn()) { finish(); startActivity(new Intent(this, LobbyActivity.class)); Log.d("Start new act", String.valueOf(SharedPrefManager.getInstance(this).isLoggedIn())); } findViewById(); onListener(); setupViewPager(viewPager); tabLayout.setupWithViewPager(viewPager); } @Override public void findViewById() { tabLayout = findViewById(R.id.tabLayout); viewPager = findViewById(R.id.viewPager); imageView = findViewById(R.id.imageView2); floatingLayout = findViewById(R.id.my_rounded_sign_in_button); } @Override public void onListener() { imageView.setOnClickListener(v -> startActivity( new Intent(getApplicationContext(), SearchTaskAlertDialog.class))); floatingLayout.setOnClickListener(v -> startActivity( new Intent(getApplicationContext(), LogInActivity.class))); } private void setupViewPager(ViewPager viewPager) { ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(new FragmentTasks(), "Tasks"); adapter.addFragment(new FragmentResumes(), "Resumes"); viewPager.setAdapter(adapter); } }
package com.revature.exceptions; public class OverdrawnException extends Exception { }
package com.cxxt.mickys.playwithme.utils; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.widget.Toast; /** * ToastUtil * * @author huangyz0918 */ public class ToastUtil { public static void backgroundThreadShortToast(final Context context, final String msg) { if (context != null && msg != null) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } }); } } }
/* Name: Brian Spencer Date: Feb. 24, 2019 Purpose: Program that will merge two sorted singly-linked lists and return it as as a new list. */ package hw4prob2; //node class for queue class QueueNode { int data; QueueNode next; //constructor for a new queuenode public QueueNode(int key) { this.data = key; this.next = null; } } //class to create linked list queue using queuenodes class LLCoolQueue { QueueNode front, rear; int size; public LLCoolQueue() { this.front = this.rear = null; this.size = 0; } //method to add an int to to the queue void enqueueKey(int k) { //create a queue node to put input in QueueNode t = new QueueNode(k); //if the queue is empty, then new queuenode is front and rear both if (this.is_Empty()) { this.front = this.rear = t; this.size++; return; } //add new queuenode at the end of queue and update rear this.rear.next = t; this.rear = t; this.size++; } //method to add a queuenode to to the queue void enqueue(QueueNode k) { //if the queue is empty, then new queuenode is front and rear both if (this.is_Empty()) { this.front = this.rear = k; this.size++; return; } //add new queuenode at the end of queue and update rear this.rear.next = k; this.rear = k; this.size++; } //method to remove head node QueueNode dequeue() { //if the queue is empty, then return null if (this.is_Empty()) { return null; } //put current front in t and advance queue QueueNode t = this.front; this.front = this.front.next; //if queue would become empty, make rear null too if (this.front == null) { this.rear = null; } //decrease size this.size--; //return dequeued node return t; } boolean search(QueueNode q, int key) { //setting currvalue to inputted queuenode QueueNode currvalue = q; //iterating through nodes, searching for .data == key while (currvalue != null) { if (currvalue.data == key) //return true on first match { return true; } currvalue = currvalue.next; } //return false if no matches found return false; } //method to return the front queuenode's data int first() { return this.front.data; } //method to return the linkedlist queue's length int len() { return this.size; } //method to return true if the linkedlist queue is empty boolean is_Empty() { return this.front == null; } //method to print data at each queue node void printList(QueueNode node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } System.out.println(); } } public class Hw4Prob2 { // Merges two sorted lists (they must be sorted or it will not work) static QueueNode splice(QueueNode q1, QueueNode q2) { //merge single node q1 to q2 if it's single if (q1.next == null) { q1.next = q2; return q1; } //swap queuenodes set up with current and next nodes of each list QueueNode currnode1 = q1; QueueNode nextnode1 = q1.next; QueueNode currnode2 = q2; QueueNode nextnode2 = q2.next; while (currnode1 != null && currnode2 != null) { //if current queue node of list 2 lies in between current queue node //of list 1 and next node of list 1, there will be a swap to push //queue nodes into longer list (list1) if ((currnode2.data >= currnode1.data) && (currnode2.data <= nextnode2.data)) { nextnode2 = currnode2.next; currnode1.next = currnode2; currnode2.next = nextnode2; //set queue nodes to point to next queuenode currnode1 = currnode2; currnode2 = nextnode2; } else { //if list 2 runs out before list 1 does, the next queue node of //list gets copied and current queue node of list 1 gets copied //so they can swap as if list 2 didn't run out of queue nodes if (nextnode2.next != null) { nextnode2 = nextnode2.next; currnode1 = currnode1.next; } //otherwise, next queue node of list 2 will point to current //queue node of list 2 and return list 1 else { nextnode2.next = currnode2; return q1; } } } return q1; } //method to splice two lists together static QueueNode merge(QueueNode q1, QueueNode q2) { //if first list is empty, return second list if (q1 == null) { return q2; } //if second list is empty, return first list if (q2 == null) { return q1; } //splice smaller list with larger list if (q1.data < q2.data) { return splice(q1, q2); } else { return splice(q2, q1); } } public static void main(String[] args) { LLCoolQueue q1 = new LLCoolQueue(); LLCoolQueue q2 = new LLCoolQueue(); q1.enqueueKey(1); q1.enqueueKey(1); q1.enqueueKey(7); q2.enqueueKey(0); q2.enqueueKey(3); q2.enqueueKey(4); q2.enqueueKey(5); QueueNode xd = merge(q1.front, q2.front); LLCoolQueue q3 = new LLCoolQueue(); q3.enqueue(xd); q3.printList(q3.front); } }
package com.java.OOP; public class ClassA { public static void main(String[] args) { int value = B.numOne; System.out.println(value); String s = B.str; System.out.println(s); } } class B{ static int numOne = 10; static String str = "Test"; }
package com.serotonin.modbus4j; import com.serotonin.io.messaging.DefaultExceptionListener; import com.serotonin.io.messaging.MessagingConnectionListener; /** * Base level for masters and slaves/listeners * * TODO: * - handle echoing in RS485 * * @author mlohbihler */ public class Modbus { private MessagingConnectionListener exceptionListener = new DefaultExceptionListener(); public void setExceptionListener(MessagingConnectionListener exceptionListener) { if (exceptionListener == null) this.exceptionListener = new DefaultExceptionListener(); else this.exceptionListener = exceptionListener; } public MessagingConnectionListener getExceptionListener() { return exceptionListener; } }
package com.acewill.ordermachine.adapter; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.acewill.ordermachine.R; import com.acewill.ordermachine.eventbus.PayMethodEvent; import com.acewill.ordermachine.model.PaymentInfo; import org.greenrobot.eventbus.EventBus; import java.util.List; /** * Author:Anch * Date:2017/12/29 17:53 * Desc: */ public class PayMethodAdapter extends MyAdapter { private TextView paymethod_name; public PayMethodAdapter(Context context, List dataList) { super(context, dataList); } @Override protected View getItemView(int position, View convertView, ViewGroup parent) { final PaymentInfo pInfo = (PaymentInfo) dataList.get(position); View view = null; if (pInfo.id == -8 || pInfo.id == 1 || pInfo.id == 2) { view = View.inflate(mContext, R.layout.item_paymethod2, null); paymethod_name = (TextView) view.findViewById(R.id.paymethod_name); } else { view = View.inflate(mContext, R.layout.item_paymethod, null); paymethod_name = (TextView) view.findViewById(R.id.paymethod_name); paymethod_name.setText(pInfo.name); } if (pInfo.status == 0 || pInfo.id == 4 || pInfo.id == 5 || pInfo.id == -33) view.setVisibility(View.GONE); else view.setVisibility(View.VISIBLE); view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { PayMethodEvent event = new PayMethodEvent(pInfo.id, pInfo.name, pInfo.cashbox); EventBus.getDefault().post(event); } }); return view; } }
package spring.boot.com.redisson; import org.redisson.Redisson; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.redisson.config.Config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import spring.boot.com.mySpike.MyJedis; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * @author: yiqq * @date: 2019/4/19 * @description: 通过Redisson实现基于redis的分布式锁,最成功的!!!! * https://blog.csdn.net/yuruixin_china/article/details/78531309 */ public class RedissonSuccess { private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private static Jedis jedis = MyJedis.getJedisObject(); private static String KEY = "num_all"; private static int threadCount = 1009; private static Logger logger = LoggerFactory.getLogger(RedissonSuccess.class); public static void main(String[] args) { jedis.set(KEY, "1000"); //Redisson连接配置文件 Config config = new Config(); config. useSingleServer().setAddress("192.168.18.23:6379").setPassword("123456").setDatabase(0); RedissonClient redisson = Redisson.create(config); RLock yuxinLock = redisson.getLock("yuxinLock"); // 1.获得锁对象实例 new RedissonSuccess().testM(yuxinLock); } public void testM(RLock yuxinLock){ ExecutorService fixedThreadPool = Executors.newFixedThreadPool(threadCount); for(int i = 0; i < threadCount; i++){ fixedThreadPool.execute(new Task("woker_" + i,yuxinLock)); } } class Task implements Runnable{ private String name; private RLock yuxinLock; public Task(String name,RLock yuxinLock){ this.name = name; this.yuxinLock=yuxinLock; System.out.println(name); } public void run() { boolean res=false; try{ //1.不支持过期自动解锁,不会超时 //yuxinLock.lock(); // 2. 支持过期解锁功能,10秒钟以后自动解锁, 无需调用unlock方法手动解锁 //lock.lock(10, TimeUnit.SECONDS); // 3. 尝试加锁,最多等待20秒,上锁以后10秒自动解锁(实际项目中推荐这种,以防出现死锁) res = yuxinLock.tryLock(20, 10, TimeUnit.SECONDS); if(res){ int num = Integer.valueOf(jedis.get(KEY)); if (num > 0) { jedis.decr(KEY); } else { logger.info(sdf.format(new Date()) + ">>>>>>>>>>已售罄"); } }else{ System.out.println(name+"---------------->>>>>等待超时"); } } catch (InterruptedException e) { e.printStackTrace(); } finally{ if(res){ yuxinLock.unlock(); } } } } }
//program to show use of lebel break with code block import java.util.*; class code_block { public static void main (String[] args) { Scanner x=new Scanner(System.in); System.out.print("Enter a positive no:-"); int num=x.nextInt(); a1:{ if(num<=0) System.out.print("Invalied no found plz enter Positive number"); break a1;} System.out.print("positive number"+num+ "Entered"); a2:{ if(num%2==0) System.out.print(" is even number"); else System.out.print(" is odd number"); break a2; } } }
package za.co.bonginkosilukhele.servicebiz.fragments; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.Spinner; import android.widget.Toast; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.storage.FirebaseStorage; import com.google.firebase.storage.StorageReference; import com.google.firebase.storage.UploadTask; import com.squareup.picasso.Picasso; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.BindViews; import butterknife.ButterKnife; import butterknife.OnClick; import za.co.bonginkosilukhele.servicebiz.R; import za.co.bonginkosilukhele.servicebiz.activities.MainActivity; import za.co.bonginkosilukhele.servicebiz.model.Address; import za.co.bonginkosilukhele.servicebiz.model.Client; import za.co.bonginkosilukhele.servicebiz.model.ContactDetails; import za.co.bonginkosilukhele.servicebiz.model.Service; import za.co.bonginkosilukhele.servicebiz.model.ServiceProvider; import static android.app.Activity.RESULT_OK; /** * Created by Admin on 2017-02-01. */ public class ProvideServiceFrag extends Fragment implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener, View.OnTouchListener{ //--------- declaration of variables and initialisation of Views and widgets ---------// SharedPreferences pref; SharedPreferences.Editor editor; private StorageReference mStorageReference; View focus; private Uri imageUri; private String image; private View rootView; private Intent passIntent; SQLiteDatabase db; ServiceProvider sp = new ServiceProvider(); ContactDetails cd = new ContactDetails(); Service serviceModel = new Service(); Address ad = new Address(); Client client = new Client(); long theId; boolean aBoolean; FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser(); private DatabaseReference mDatabase; // ... // The user's ID, unique to the Firebase project. Do NOT use this value to // authenticate with your backend server, if you have one. Use // FirebaseUser.getToken() instead. String uid; //- declaring all the string to be used in the String typeOfRegistrationString, string_name, string_surname, string_registrationNo, string_email, string_website, string_telephone, string_person, string_cellphone, string_service, string_street, string_suburb, string_town, string_postalCode, string_province, string_serviceProviderType, string_message, string_error; String string_null = "not applicable"; String string_title; String string_titleBar = " " + string_title + " ".toUpperCase(); //= //-Butterknife Bindings //initialisation of the tablerows that will hide //buttons @BindView(R.id.btn_submit) Button buttonSubmit; @BindView(R.id.button_add_service) Button buttonAddService; //initialisation of the editext @BindViews({R.id.editext_name, R.id.editext_reg_no, R.id.editext_email, R.id.editext_website, R.id.editext_telephone, R.id.editext_person, R.id.editext_contact_number, R.id.editext_street_address, R.id.editext_suburb, R.id.editext_town, R.id.editext_postal_code}) List<EditText> editTexts; @BindView(R.id.editext_service) EditText editext_service; //initialisation of the spinner @BindView(R.id.spinner_province) Spinner spinnerProvince; //declaring a listview to show services during capturing @BindView(R.id.listview_services) ListView listView; //for control int intName = 0; int intRegNo = 1; int intEmail = 2; int intWebsite = 3; int intTel = 4; int intPerson = 5; int intCell = 6; int intStreet = 7; int intSuburb = 8; int intTown = 9; int intPostal = 10; private static final int GALLERY_INTENT = 1; //==Butterknife bindings //create the arraylist services create an arrayAdapter // to use them ArrayList<String> arrayList_services = new ArrayList<>(); ArrayAdapter<String> arrayAdapter; ArrayList<String> arrayListProvinces = new ArrayList<>(); Spinner spinner; ImageView ivLogo; String key; //==================== declaration ends here =================================// //------------------ onCreate starts here --------------------------------// @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View rootView = inflater.inflate(R.layout.provide_service, container, false); uid = user.getUid(); key = uid; mStorageReference = FirebaseStorage.getInstance().getReference(); ivLogo = (ImageView) rootView.findViewById(R.id.provider_logo); ivLogo.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT); galleryIntent.setType("image/*"); passIntent = galleryIntent; startActivityForResult(galleryIntent, GALLERY_INTENT ); } }); mDatabase = FirebaseDatabase.getInstance().getReference().child("Users"); if (user != null) { // Name, email address, and profile photo Url string_name = user.getDisplayName().substring(1); string_email = user.getEmail(); } //--------------- dialog to select type of user ---------------------// //==================== dialog ends here =============================// spinner = (Spinner) rootView.findViewById(R.id.spinner_province); arrayListProvinces.add("-Select Province-"); arrayListProvinces.add("Eastern Cape"); arrayListProvinces.add("Free State"); arrayListProvinces.add("Gauteng"); arrayListProvinces.add("KwaZulu Natal"); arrayListProvinces.add("Limpopo"); arrayListProvinces.add("Mpumalanga"); arrayListProvinces.add("Northern Cape"); arrayListProvinces.add("North West"); arrayListProvinces.add("Western Cape"); arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, arrayListProvinces); arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(arrayAdapter); spinner.setOnItemSelectedListener(this); ButterKnife.bind(this, rootView); ButterKnife.apply(editTexts, DISABLE); ButterKnife.apply(editTexts, ENABLED, false); ImageView image_profile; editTexts.get(intName).setText(string_name); editTexts.get(intEmail).setText(string_email); return rootView; } //================== onCreate ends here =================================// private void writeNewUser() { loadSetters(); mDatabase.child(key).child("ServiceProvider").setValue(sp); mDatabase.child(key).child("contact").setValue(cd); mDatabase.child(key).child("Address").setValue(ad); } //------------------ the add service editext starts here -----------------// @OnClick(R.id.button_add_service) public void addService() { string_service = editext_service.getText().toString(); System.out.println("The service is captured as: " + string_service); if(TextUtils.isEmpty(editext_service.getText().toString())){ Toast.makeText(getContext(), "please enter a valid service you provide", Toast.LENGTH_SHORT).show(); return;} else { arrayList_services.add(string_service); } //view entered services the service provider will provide arrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, arrayList_services); arrayAdapter.setDropDownViewResource(android.R.layout.simple_list_item_1); listView.setAdapter(arrayAdapter); listView.setOnItemClickListener(this); listView.setOnTouchListener(this); editext_service.setText(null); } //================ add service editext ends here ======================// //----------------- initialise for freelancer registration ---------------------// public void initialiseForFreelancer() { } //===================== initialise for freelance ends here =====================// //---------- @OnClick(R.id.provider_select) public void getImage(){ Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT); galleryIntent.setType("image/*"); // passIntent = galleryIntent; startActivityForResult(galleryIntent, GALLERY_INTENT ); } //========== // public void addAnItem() { StorageReference filePath = mStorageReference.child("Provider").child(key).child(imageUri.getLastPathSegment()); filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() { @Override public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) { Uri downloadUri = taskSnapshot.getDownloadUrl(); image = downloadUri.toString(); } }); } //-------------------- client registration starts here --------------------------// public void initialiseForNewClient() { } //====================== client registration ends here ========================// @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); System.out.println("=======|||||||||||||||||||||||||===============: "+imageUri); if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK) { imageUri = data.getData(); Toast.makeText(getActivity(),imageUri.toString(),Toast.LENGTH_SHORT).show(); System.out.println("==============================: "+imageUri); Picasso.with(getActivity().getBaseContext()).load(imageUri).into(ivLogo); // buttonLogo. } } //------------------- a method to load data to objects ------------------// public void assignEditextToStrings() { if(TextUtils.isEmpty( editTexts.get(intName).getText().toString()) || TextUtils.isEmpty(editTexts.get(intRegNo).getText().toString()) || TextUtils.isEmpty( editTexts.get(intWebsite).getText().toString()) || TextUtils.isEmpty( editTexts.get(intTel).getText().toString()) || TextUtils.isEmpty( editTexts.get(intPerson).getText().toString()) || TextUtils.isEmpty( editTexts.get(intCell).getText().toString()) || TextUtils.isEmpty( editTexts.get(intStreet).getText().toString()) || TextUtils.isEmpty( editTexts.get(intSuburb).getText().toString()) || TextUtils.isEmpty( editTexts.get(intTown).getText().toString()) || TextUtils.isEmpty( editTexts.get(intPostal).getText().toString())){ Toast.makeText(getContext(), "please provide all required information", Toast.LENGTH_SHORT).show(); return;} else { string_name = editTexts.get(intName).getText().toString(); string_registrationNo = editTexts.get(intRegNo).getText().toString(); string_website = editTexts.get(intWebsite).getText().toString(); string_telephone = editTexts.get(intTel).getText().toString(); string_person = editTexts.get(intPerson).getText().toString(); string_cellphone = editTexts.get(intCell).getText().toString(); string_street = editTexts.get(intStreet).getText().toString(); string_suburb = editTexts.get(intSuburb).getText().toString(); string_town = editTexts.get(intTown).getText().toString(); string_postalCode = editTexts.get(intPostal).getText().toString(); } } //=================== loading data to objects ends here ======================// //------------------- a editext to add data to database -----------------------// @OnClick(R.id.btn_submit) public void submitRegistration() { // assignEditextToStrings(); // loadSetters(); addAnItem(); // writeNewUser(); string_title = "adding service provider"; showMessage( string_titleBar, "service provider added"); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(3000); startActivity(new Intent(getContext(), MainActivity.class)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } //================== data addidtion ends here =============================// // // //================= province selection ends here ============================// //--------------- the show message method starts here --------------------// public void showMessage(String title, String message) { AlertDialog.Builder dialog = new AlertDialog.Builder(getContext()/*, R.style.AppThemeNoActionBar*/); // dialog.setIcon(R.mipmap.ic_launcher); dialog.setTitle(title.toUpperCase()); dialog.setMessage(message); dialog.show(); dialog.setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //the user clicked on Cancel } }); } //===================== show message ends here ===========================// //------------------ method to load setters starts here --------------------// public void loadSetters() { int counter = arrayList_services.size(); if (counter >= 1) { string_service = arrayList_services.get(0); System.out.println("how many services do you offer: " + counter); for (int i = 1; i < counter; i++) { string_service = string_service + ", " + arrayList_services.get(i); } } else { string_service = string_null; } sp.setName(string_name); sp.setSurname(string_surname); sp.setRegistration(string_registrationNo); sp.setProviderId(user.getUid()); sp.setServiceOffered(string_service); sp.setServiceProviderType(string_serviceProviderType); cd.setCellphone(string_cellphone); cd.setEmail(string_email); cd.setTelephone(string_telephone); cd.setWebsite(string_website); cd.setPerson(string_person); ad.setLine1(string_street); ad.setLine2(string_suburb); ad.setTown(string_town); ad.setProvince(string_province); ad.setPostalCode(Integer.parseInt(string_postalCode)); ad.setAddressType("provider"); } //====================== loading setters end here ==============================// private boolean isEmailValid(String email) { //TODO: Replace this with your own logic return email.contains("@"); } //---------------------- ------------------------// // Action and Setter interfaces allow specifying simple behavior. static final ButterKnife.Action<EditText> DISABLE = new ButterKnife.Action<EditText>() { @Override public void apply(@NonNull EditText view, int index) { view.setText(null); } }; static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() { @Override public void set(View view, Boolean value, int index) { view.setEnabled(true); } }; @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { System.out.println("The selected service is: " + arrayList_services.get(i)); editext_service.setText(arrayList_services.get(i)); arrayList_services.remove(i); } @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { string_province = adapterView.getItemAtPosition(i).toString(); System.out.println("the selected province is: " + string_province); } @Override public void onNothingSelected(AdapterView<?> adapterView) { if (TextUtils.isEmpty(string_province)) { focus = spinner; string_title = "select province"; string_message = "this field is important"; showMessage(string_title, string_message); } } @Override public boolean onTouch(View view, MotionEvent motionEvent) { view.getParent().requestDisallowInterceptTouchEvent(true); return false; } //========================= ======================// }
package benchmark.java.metrics.jnative; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import benchmark.java.Config; import benchmark.java.entities.PersonCollection; import benchmark.java.metrics.AMetric; import benchmark.java.metrics.Info; public class JavaSerializationMetric extends AMetric { private final Info info = new Info(Config.Format.NATIVE, "Java Serialization", "https://docs.oracle.com/javase/tutorial/jndi/objects/serial.html"); @Override public Info getInfo() { return info; } @Override public boolean serialize(Object data, OutputStream output) throws Exception { ObjectOutputStream objectOutputStream = new ObjectOutputStream(output); objectOutputStream.writeObject(data); return true; } @Override public Object deserialize(InputStream input, byte[] bytes) throws Exception { ObjectInputStream inputStream = new ObjectInputStream(input); PersonCollection personCollection = (PersonCollection) inputStream.readObject(); return personCollection; } }
package com.cninnovatel.ev.type; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.log4j.Logger; import android.content.Context; import com.cninnovatel.ev.RuntimeData; import com.cninnovatel.ev.db.DaoMaster; import com.cninnovatel.ev.db.DaoSession; import com.cninnovatel.ev.db.DaoMaster.DevOpenHelper; public class DatabaseHelper { private static Logger log = Logger.getLogger(DatabaseHelper.class); public enum DatabaseType { CONFERENCE_LIST, CONTACT_LIST, CALLRECORD_LIST, CALLROW_LIST } private static Map<DatabaseType, DevOpenHelper> map_type_helper = new ConcurrentHashMap<DatabaseType, DevOpenHelper>(); private static Map<DatabaseType, DaoSession> map_type_session = new ConcurrentHashMap<DatabaseType, DaoSession>(); public static DaoSession getSession(Context context, DatabaseType type) { if (map_type_session.get(type) == null) { DaoSession daoSession = new DaoMaster(getInstance(context, type).getWritableDatabase()).newSession(); map_type_session.put(type, daoSession); } return map_type_session.get(type); } private static DevOpenHelper getInstance(Context context, DatabaseType type) { log.info("get database helper: " + type.toString()); if (map_type_helper.get(type) == null) { DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, getDatabaseName(type), null); map_type_helper.put(type, helper); } return map_type_helper.get(type); } private static String getDatabaseName(DatabaseType type) { String logUserName = RuntimeData.getLogUser() != null ? RuntimeData.getLogUser().getName() : ""; return type.toString() + "_" + RuntimeData.getUcmServer() + "_" + logUserName; } public static void close() { log.info("close all database helpers and sessions"); for (DevOpenHelper helper : map_type_helper.values()) { helper.close(); } for (DaoSession session : map_type_session.values()) { session.clear(); } map_type_helper.clear(); map_type_session.clear(); } }
package edu.neu.madcourse.numad17s_emmaliu.wordGame; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import edu.neu.madcourse.numad17s_emmaliu.*; import edu.neu.madcourse.numad17s_emmaliu.realtimedatabase.models.User; public class LeaderboardActivity extends AppCompatActivity { private ListView listView; private Button buttonSortByTotalScore; private Button buttonSortBySingleWord; private Button buttonChat; private ArrayAdapter adapter; private ArrayList<String> contents = new ArrayList<>(); private int num1 = 0; private int num2 = 0; private ArrayList<User> users = new ArrayList<>(); public ArrayList<User> displayedUsers = new ArrayList<>(); DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference mUsersRef = mRootRef.child("users"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_leaderboard); listView = (ListView) findViewById(R.id.leadboardList); adapter = new ArrayAdapter<>(LeaderboardActivity.this, R.layout.mylist_leaderboard, contents); listView.setAdapter(adapter); buttonSortByTotalScore = (Button) findViewById(R.id.buttonSortTotoalScore); buttonSortBySingleWord = (Button) findViewById(R.id.buttonSortWordScore); buttonChat = (Button) findViewById(R.id.buttonSendMessage); buttonSortByTotalScore.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sortByTotalScore(num1); num1++; adapter.notifyDataSetChanged(); } }); buttonSortBySingleWord.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sortByLongestWord(num2); num2++; adapter.notifyDataSetChanged(); } }); buttonChat.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(LeaderboardActivity.this, ChatActivity.class); startActivity(intent); } }); } @Override protected void onStart() { super.onStart(); mUsersRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot ds : dataSnapshot.getChildren()) { User user = ds.getValue(User.class); users.add(user); } displayedUsers = getFirst10Users(users); GameStatus.clearDisplayedUser(); GameStatus.setDisplayedUser(displayedUsers); for (User u : displayedUsers) { String string = convertUser(u); contents.add(string); } adapter.notifyDataSetChanged(); } @Override public void onCancelled(DatabaseError databaseError) { } }); } private ArrayList<User> getFirst10Users(ArrayList<User> users) { ArrayList<User> result = new ArrayList<>(); Collections.sort(users, new Comparator<User>() { @Override public int compare(User o1, User o2) { return o2.score - o1.score; } }); if (users.size() <= 10) { result = users; } else { for (int i = 0; i < 10; i++) { result.add(users.get(i)); } } return result; } private void sortByTotalScore(final int num) { Collections.sort(displayedUsers, new Comparator<User>() { @Override public int compare(User o1, User o2) { if ((num & 1) == 0) { return o1.score - o2.score; } else { return o2.score - o1.score; } } }); contents.clear(); for (User u : displayedUsers) { String string = convertUser(u); contents.add(string); } adapter.notifyDataSetChanged(); } private void sortByLongestWord(final int num) { Collections.sort(displayedUsers, new Comparator<User>() { @Override public int compare(User o1, User o2) { if ((num & 1) == 0) { return o1.longestWordScore - o2.longestWordScore; } else { return o2.longestWordScore - o1.longestWordScore; } } }); contents.clear(); for (User u : displayedUsers) { String string = convertUser(u); contents.add(string); } adapter.notifyDataSetChanged(); } private String convertUser (User user) { String result; result = "username: " + user.username + "\n" + "TotalScore: " + user.score + "\n" + "dataPlayer: " + user.datePlayed + "\n" + "longestWord: " + user.longestWord + "\n" + "longestWordScore: " + user.longestWordScore + "\n"; return result; } }
/** * Writer * package provides complete set of tools for writing * @author michailremmele */ package it.sevenbits.codecorrector.writer;
package sg.edu.rp.c346.id20046765.holidayhomework; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { Button btnViewMe; Button btnNext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnViewMe = findViewById(R.id.btnVistMe); btnNext = findViewById(R.id.btnNext); btnViewMe.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ Intent intentCall = new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/HockLeongWee")); startActivity(intentCall); } }); btnNext.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view){ Intent intent = new Intent(MainActivity.this, ItemListActivity.class); startActivity(intent); } }); } }
package com.codingdojo.EventFree.models; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; import javax.persistence.Transient; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import org.springframework.format.annotation.DateTimeFormat; @Entity @Table(name="users") public class User { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @Size(min=2,max=20,message="FIRST LETTER MUST BE CAPITALIZED!") private String firstName; @Size(min=2,max=20,message="FIRST LETTER MUST BE CAPITALIZED!") private String lastName; // private Date birthday; @Email(message = "EMAIL FORMATS PLEASE") @NotBlank(message = "Please Enter A Valid Email") private String email; @Size(min = 8, message = "PW Needs to be 8 Char. Min.") private String password; @Transient private boolean duplicate; @NotBlank(message = "Please Confirm Password") @Transient private String passwordConfirmation; @Column(updatable=false) @DateTimeFormat(pattern="yyyy-MM-dd") private Date createdAt; @Column(updatable=true) @DateTimeFormat(pattern="yyyy-MM-dd") private Date updatedAt; @OneToMany(mappedBy="creator", fetch = FetchType.LAZY) private List<Event> created_events; @ManyToMany(fetch = FetchType.LAZY) @JoinTable( name = "events_attendees", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "event_id") ) private List<Event> events_attending; @ManyToMany(fetch = FetchType.LAZY) @JoinTable( name = "friendships", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "friend_id") ) private List<User> friends; @ManyToMany(fetch = FetchType.LAZY) @JoinTable( name = "friendships", joinColumns = @JoinColumn(name = "friend_id"), inverseJoinColumns = @JoinColumn(name = "user_id") ) private List<User> userFriends; public User() { } public User(@Size(min = 2, max = 20, message = "FIRST LETTER MUST BE CAPITALIZED!") String firstName, String lastName, @Size(min = 2, max = 20) String email, String password, boolean duplicate, String passwordConfirmation) { super(); this.firstName = firstName; this.lastName = lastName; // this.birthday = birthday; this.email = email; this.password = password; this.duplicate = duplicate; this.passwordConfirmation = passwordConfirmation; } public List<Event> getEvents_attending() { return events_attending; } public void setEvents_attending(List<Event> events_attending) { this.events_attending = events_attending; } public List<User> getFriends() { return friends; } public void setFriends(List<User> friends) { this.friends = friends; } public List<User> getUserFriends() { return userFriends; } public void setUserFriends(List<User> userFriends) { this.userFriends = userFriends; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } // // public Date getBirthday() { // return birthday; // } // // public void setBirthday(Date birthday) { // this.birthday = birthday; // } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public boolean isDuplicate() { return duplicate; } public void setDuplicate(boolean duplicate) { this.duplicate = duplicate; } public String getPasswordConfirmation() { return passwordConfirmation; } public void setPasswordConfirmation(String passwordConfirmation) { this.passwordConfirmation = passwordConfirmation; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } public List<Event> getCreated_events() { return created_events; } public void setCreated_events(List<Event> created_events) { this.created_events = created_events; } // other getters and setters removed for brevity @PrePersist protected void onCreate(){ this.createdAt = new Date(); } @PreUpdate protected void onUpdate(){ this.updatedAt = new Date(); } }
package com.unimelb.comp90015.Util; import javax.swing.*; import java.io.*; import java.net.URL; import static com.unimelb.comp90015.Util.Constant.*; /** * Xulin Yang, 904904 * * @create 2020-03-26 22:23 * description: some helper functions **/ public class Util { /** * @param errorCode the index of the error * @param errorContent the description of the error * @return formatted error message */ public static String getError(String errorCode, String errorContent) { return "Error(" + errorCode + "): " + errorContent; } /** * @param vipPriority the vip level * @return true if vipPriority is in 1-10; false otherwise */ public static boolean checkWrongVipPriority(int vipPriority) { return vipPriority < 0 || vipPriority > 10; } /** * @param serverPort the port number * @return true if port number is in 49152-65535; false otherwise */ public static boolean checkWrongServerPort(int serverPort) { return serverPort < 49152 || serverPort > 65535; } /** * invoke dialog for port number error */ public static void serverPortError() { popupErrorDialog(ERROR_INVALID_PORT_NUMBER_CODE, ERROR_INVALID_PORT_NUMBER_CONTENT); } /** * @param code the index of the error * @param content the description of the error * invoke dialog for error */ public static void popupErrorDialog(String code, String content) { JOptionPane.showConfirmDialog( null, getError(code, content), "Error", JOptionPane.OK_CANCEL_OPTION ); System.exit(1); } /** * @param size the thread pool size * @return true if thread pool size is in 1-Integer.MAX_VALUE; false otherwise */ public static boolean checkWrongThreadPoolSize(int size) { return size <= 0 || size >= Integer.MAX_VALUE; } /** * invoke dialog for thread pool size error */ public static void threadPoolSizeError() { popupErrorDialog(ERROR_INVALID_THREAD_POOL_SIZE_CODE, ERROR_INVALID_THREAD_POOL_SIZE_CONTENT); } /** * @param second inactive thread waiting time * @return true if time is between 1-1000 second; false otherwise */ public static boolean checkWrongInactiveTime(int second) { return second < 1 || second > 1000; } public static boolean checkWrongThreadPoolQueueLimit(int threadPoolQueueLimit, int threadPoolSize) { return threadPoolQueueLimit < threadPoolSize || threadPoolQueueLimit >= Integer.MAX_VALUE; } /** * invoke dialog for thread pool queue limit error */ public static void threadPoolQueueLimitError() { popupErrorDialog(ERROR_INVALID_THREAD_POOL_QUEUE_LIMIT_CODE, ERROR_INVALID_THREAD_POOL_QUEUE_LIMIT_CONTENT); } /** * invoke dialog for inactive time error */ public static void inactiveTimeError() { popupErrorDialog(ERROR_INVALID_INACTIVE_TIME_CODE, ERROR_INVALID_INACTIVE_TIME_CONTENT); } /** * @param string input string to be tested * @return true if a string is made up of alphabet or number. */ public static boolean stringIsAlnum(String string) { for (String str: string.split("\n")) { if (!str.matches(".*[a-zA-Z]+.*")) { return false; } } return true; } /** * @param string input string to be tested * @return true if a string is made up of alphabet. */ public static boolean stringIsAlpha(String string) { return string.matches("[a-zA-Z]+"); } /** * load a file in jar file to a temp file and return the path of the temp file * @param res resource path * @param input input stream * @return the path to temp read file * code modify https://stackoverflow.com/a/14612564 */ public static File loadFileFromJar(URL res, InputStream input) { File file = null; if (res.getProtocol().equals("jar")) { try { file = File.createTempFile("tempfile", ".tmp"); OutputStream out = new FileOutputStream(file); int read; byte[] bytes = new byte[1024]; while ((read = input.read(bytes)) != -1) { out.write(bytes, 0, read); } out.close(); file.deleteOnExit(); } catch (IOException ex) { ex.printStackTrace(); } } else { //this will probably work in your IDE, but not from a JAR file = new File(res.getFile()); } if (file != null && !file.exists()) { throw new RuntimeException("Error: File " + file + " not found!"); } return file; } }
package nl.theepicblock.polypuck; import net.minecraft.util.Identifier; public class PolyPuck { public final static Identifier CHANNEL_ID = new Identifier("polypuck","enabled"); }
package main; import model.Celebrity; import model.Citizen; import model.Museum; public class APL { public final static int NR_OF_CELEBRITIES = 5; public final static int NR_OF_CITIZENS = 20; private static Thread[] celebrities; private static Thread[] citizens; public static void main(String[] args) { celebrities = new Thread[NR_OF_CELEBRITIES]; citizens = new Thread[NR_OF_CITIZENS]; Museum museum = new Museum(); for (int i = 0; i < NR_OF_CELEBRITIES; i++) { celebrities[i] = new Celebrity(museum); celebrities[i].start(); } for (int i = 0; i < NR_OF_CITIZENS; i++) { citizens[i] = new Citizen(museum); citizens[i].start(); } } }
package com.ravi.travel.budget_travel.domain; public class Paragraph { public Paragraph() { } public Paragraph(String paragraph) { this.paragraph = paragraph; } public Paragraph(String paragraph, String imageUrl,String imageDestination) { this.paragraph = paragraph; this.imageUrl = imageUrl; this.imageDestination = imageDestination; } private String paragraph; private String imageUrl; private String imageDestination; public String getParagraph() { return paragraph; } public void setParagraph(String paragraph) { this.paragraph = paragraph; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getImageDestination() { return imageDestination; } public void setImageDestination(String imageDestination) { this.imageDestination = imageDestination; } @Override public String toString() { return "Paragraph{" + "paragraph='" + paragraph + '\'' + ", imageUrl='" + imageUrl + '\'' + ", imageDestination='" + imageDestination + '\'' + '}'; } }
package com.gaoshin.mail; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; public class MailParser { public static MailRecord parse(String mail) { MailRecord mr = new MailRecord(); BufferedReader br = new BufferedReader(new StringReader(mail)); StringBuilder sb = new StringBuilder(); boolean bodyFound = false; while (true) { String line = null; try { line = br.readLine(); } catch (IOException e) { } if (line == null) { break; } if (bodyFound) { sb.append(line).append("\n"); continue; } if (line.toLowerCase().startsWith("from:")) { String from = line.substring(5).trim(); if (from.length() > 0) { mr.setReceipts(trim(from)); } } else if (line.toLowerCase().startsWith("to:")) { String to = line.substring(3).trim(); mr.setReceipts(to); } else if (line.toLowerCase().startsWith("subject:")) { String subject = line.substring(8).trim(); if (subject.length() > 0) { mr.setSubject(trim(subject)); } } else if (line.toLowerCase().startsWith("cc:")) { String cc = line.substring(3).trim(); mr.setCc(cc); } else if (line.toLowerCase().startsWith("body:")) { bodyFound = true; sb.append(line.substring(5)).append("\n"); } } mr.setContent(trim(sb.toString())); return mr; } public static String trim(String s) { if (s == null) { return s; } return s.trim(); } }
package com.ramonmr95.app.entities; import java.util.Date; import java.util.UUID; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor") @StaticMetamodel(Brand.class) public class Brand_ { public static volatile SingularAttribute<Brand, UUID> id; public static volatile SingularAttribute<Brand, String> name; public static volatile SingularAttribute<Brand, Date> created_at; public static volatile SingularAttribute<Brand, Date> updated_at; public static final String ID = "id"; public static final String NAME = "name"; public static final String CREATED_AT = "created_at"; public static final String UPDATED_AT = "updated_at"; }
package de.cuuky.varo.gui.admin.config; import java.util.ArrayList; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.inventory.ItemStack; import de.cuuky.varo.Main; import de.cuuky.varo.config.config.ConfigEntry; import de.cuuky.varo.config.config.ConfigSection; import de.cuuky.varo.gui.SuperInventory; import de.cuuky.varo.gui.utils.PageAction; import de.cuuky.varo.gui.utils.chat.ChatHook; import de.cuuky.varo.gui.utils.chat.ChatHookListener; import de.cuuky.varo.item.ItemBuilder; import de.cuuky.varo.utils.Utils; import de.cuuky.varo.version.types.Materials; import de.cuuky.varo.version.types.Sounds; public class ConfigGUI extends SuperInventory { private ConfigSection section; public ConfigGUI(Player opener, ConfigSection section) { super("§a" + section.getName(), opener, 18, false); this.section = section; open(); } private void hookChat(ConfigEntry entry) { new ChatHook(opener, "§7Enter Value for " + Main.getColorCode() + entry.getName() + " §8(§7Current: §a" + entry.getValue() + "§8):", new ChatHookListener() { @Override public void onChat(String message) { try { entry.setValue(Utils.getStringObject(message), true); } catch(Exception e) { opener.sendMessage(Main.getPrefix() + e.getMessage()); hookChat(entry); return; } opener.playSound(opener.getLocation(), Sounds.ANVIL_LAND.bukkitSound(), 1, 1); opener.sendMessage(Main.getPrefix() + "§7'§a" + entry.getName() + "§7' erfolgreich auf '§a" + message + "§7' gesetzt!"); reopenSoon(); } }); } @Override public boolean onOpen() { int i = -1; for(ConfigEntry entry : section.getEntries()) { i++; ArrayList<String> lore = new ArrayList<>(); for(String strin : entry.getDescription()) lore.add(Main.getColorCode() + strin); lore.add(" "); lore.add("Value: " + entry.getValue()); linkItemTo(i, new ItemBuilder().displayname("§7" + entry.getPath()).itemstack(new ItemStack(Materials.SIGN.parseMaterial())).lore(lore).build(), new Runnable() { @Override public void run() { close(false); hookChat(entry); } }); } return true; } @Override public void onClose(InventoryCloseEvent event) {} @Override public void onClick(InventoryClickEvent event) {} @Override public void onInventoryAction(PageAction action) {} @Override public boolean onBackClick() { new ConfigSectionGUI(getOpener()); return true; } }
import java.io.IOException; import java.util.Scanner; public class Main { private static DataWorker dataWorker = new DataWorker(); private static Scanner input = new Scanner(System.in); public static void main(String[] args){ AdditionalThread additionalThread; String firstCur; String secondCur; System.out.println("Enter from currency:"); firstCur = getRightData(); System.out.println("Enter to currency:"); secondCur = getRightData(); additionalThread = new AdditionalThread(firstCur, secondCur); additionalThread.start(); } private static String getRightData(){ String inputStr; inputStr = input.nextLine().toUpperCase(); try { if (!dataWorker.checkData(inputStr)){ System.out.println("Wrong currency. Please try again:"); return getRightData(); } } catch (IOException e) { System.out.println("Error: something went wrong during the checking currency"); System.exit(-1); } return inputStr; } }
package com.example.ips.mapper; import com.example.ips.model.ServerplanIDealNew; 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; @RunWith(SpringRunner.class) @SpringBootTest public class ServerplanIDealNewMapperTest { @Autowired ServerplanIDealNewMapper serverPlanIDealNewMapper; @Test public void selectByApplication() { ServerplanIDealNew s=serverPlanIDealNewMapper.selectByApplication("即时通讯核心"); System.out.println(">>>>>>>>>>>>>"+s.getDev()); } }
package com.pshc.cmg.model; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import lombok.Data; public class LoggedUser extends org.springframework.security.core.userdetails.User{ private static final String ROLE_PREFIX = "ROLE_"; public LoggedUser(User user) { super(user.getUsername(), user.getPassword(), makeGrantedAuthority(user.getRoles())); } private static List<GrantedAuthority> makeGrantedAuthority(Set<Role> roles) { List<GrantedAuthority> list = new ArrayList<GrantedAuthority>(); roles.forEach(role -> list.add(new SimpleGrantedAuthority(ROLE_PREFIX + role.getRole()))); return list; } }
package Udp; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.util.Enumeration; public class WW { public static void main(String[] args) throws Exception { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface networkInterface = interfaces.nextElement(); System.out.println(networkInterface); if (networkInterface.isLoopback() || !networkInterface.isUp()) { continue; // Don't want to broadcast to the loopback interface } for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) { InetAddress broadcast = interfaceAddress.getBroadcast(); if (broadcast == null) { continue; } System.out.println(broadcast); // Send the broadcast package! // try { // DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, broadcast, 8888); // c.send(sendPacket); // } catch (Exception e) { // } // // System.out.println(getClass().getName() + ">>> Request packet sent to: " + broadcast.getHostAddress() + "; Interface: " + networkInterface.getDisplayName()); } } } }
package nju.androidchat.client.component; import android.content.Context; import android.webkit.WebView; import android.widget.LinearLayout; import androidx.annotation.StyleableRes; import java.util.UUID; import lombok.Setter; import nju.androidchat.client.R; public class ItemPictureReceive extends LinearLayout { @StyleableRes int index0 = 0; private WebView webView; private Context context; private UUID messageId; @Setter private OnRecallMessageRequested onRecallMessageRequested; public ItemPictureReceive(Context context, String url, UUID messageId, OnRecallMessageRequested onRecallMessageRequested) { super(context); this.context = context; inflate(context, R.layout.item_picture_receive, this); this.webView = findViewById(R.id.web_picture_receive); this.messageId = messageId; this.onRecallMessageRequested = onRecallMessageRequested; setURL(url); } public String getURL() { return webView.getUrl(); } public void setURL(String url) { webView.loadUrl(url); } }
/** * <h1>Додатковий клас, що створює розширену анкету студента</h1> * Цей клас додає до анкети організацію, членом якої є * або буде студент. * @author Анастасія Пархоменко */ public class StudentWithActivity extends Student{ /** * Конструктор класу, що наслідує суперклас Student. * @param name Ім'я студента. * @param surname Прізвище студента. */ StudentWithActivity(String name, String surname) { super(name, surname); } protected int orgNumber; protected String name; /** * Метод, що визначає організацію, в якій бере участь * або збирається у неї вступити, за номером, введеним * студентом. * @param number Номер огранізації. */ public void chooseOrganization(int number) { orgNumber = number; switch (orgNumber) { case 1 -> { Organizations org = Organizations.TA_MOHYLYANKA_1; name = org.name(); } case 2 -> { Organizations org = Organizations.MASTANDUP_2; name = org.name(); } case 3 -> { Organizations org = Organizations.SPUDEIISKI_VISNYK_3; name = org.name(); } case 4 -> { Organizations org = Organizations.SPUDEIISKE_BRATSTVO_NAUKMA_4; name = org.name(); } case 5 -> { Organizations org = Organizations.BUDDY_NAUKMA_5; name = org.name(); } case 6 -> { Organizations org = Organizations.POLITOLOGY_STUDENTS_ASSOCIATION_6; name = org.name(); } case 7 -> { Organizations org = Organizations.DEBATE_CLUB_7; name = org.name(); } case 8 -> { Organizations org = Organizations.ECOCLUB_GREENWAVE_8; name = org.name(); } case 9 -> { Organizations org = Organizations.ANCIENT_DANCE_CLUB_9; name = org.name(); } case 10 -> { Organizations org = Organizations.FIDO_10; name = org.name(); } case 11 -> { Organizations org = Organizations.SQUAD21_11; name = org.name(); } case 12 -> { Organizations org = Organizations.THEATRICAL_STUDIO_4THSTUDIO_12; name = org.name(); } case 13 -> { Organizations org = Organizations.KMA_LEGAL_HACKERS_13; name = org.name(); } case 14 -> { Organizations org = Organizations.none_14; name = org.name(); } } } /** * Цей метод формує заповнену анкету студента з * додатковим рядком "організації". * @return рядок, який містить всю введену студентом інформацію. */ public String toString() { String res = "Full name: " + firstName + " " + lastName + ";"; res += "\nAge: " + age() + " years old;"; res += "\nHometown: " + hometown + ";"; res += "\nUniversity: " + Student.uni + ";"; res += "\nFaculty: " + relevantFaculty + ";"; res += "\nSpeciality: " + relevantSpeciality + ";"; res += "\nCourse: " + (course + (course == 1? "st" : (course == 2? "nd" : (course == 3? "rd" : "th")))) + ";"; res += "\nOrganization: " + name + ";"; res += "\nPersonal ID: " + personalID() + "."; return res; } }
package com.lenovohit.ssm.treat.manager.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.lenovohit.ssm.payment.model.Order; import com.lenovohit.ssm.payment.model.Settlement; import com.lenovohit.ssm.treat.dao.FrontendRestDao; import com.lenovohit.ssm.treat.manager.HisAppointmentManager; import com.lenovohit.ssm.treat.model.AppointmentTimePeriod; import com.lenovohit.ssm.treat.model.HisDepartment; import com.lenovohit.ssm.treat.model.HisDoctor; import com.lenovohit.ssm.treat.model.Patient; import com.lenovohit.ssm.treat.model.Schedule; public class HisAppointmentManagerImpl implements HisAppointmentManager{ @Autowired private FrontendRestDao frontendRestDao; @Override public void bizAfterPay(Order order, Settlement settle) { // TODO Auto-generated method stub } @Override public List<HisDepartment> getDepartmentList() { return frontendRestDao.getForList("appointment/department/list", HisDepartment.class); } @Override public List<HisDoctor> getDoctorList() { // TODO Auto-generated method stub return null; } @Override public List<Schedule> getSchedules(Schedule param) { return this.frontendRestDao.getForList("appointment/resource/page/0/10", Schedule.class); } @Override public List<AppointmentTimePeriod> getTimePeriod(AppointmentTimePeriod param) { // TODO Auto-generated method stub return null; } @Override public List<AppointmentTimePeriod> getScheduleTimePeriod(String scheduleId) { return this.frontendRestDao.getForList("appointment/timePeriod/list/"+scheduleId, AppointmentTimePeriod.class); } @Override public AppointmentTimePeriod bookTimePeriod(Patient patient, AppointmentTimePeriod param) { // TODO Auto-generated method stub return param; } @Override public List<AppointmentTimePeriod> unsignedList(AppointmentTimePeriod appiont) { // TODO Auto-generated method stub return null; } @Override public List<AppointmentTimePeriod> page(AppointmentTimePeriod appiont) { List<AppointmentTimePeriod> appointmentRecords = frontendRestDao.getForList("appointment/page/1/20", AppointmentTimePeriod.class); return appointmentRecords; } @Override public AppointmentTimePeriod sign(AppointmentTimePeriod appiont) { return this.frontendRestDao.getForEntity("appointment/sign", AppointmentTimePeriod.class); } @Override public AppointmentTimePeriod cancel(AppointmentTimePeriod appiont) { return this.frontendRestDao.getForEntity("appointment/cancel", AppointmentTimePeriod.class); } }
public class Statistics { public static void main(String[] args) { StatCalc calculator = new StatCalc(); for (int i = 1; i <=10; i++) { calculator.enter(i); } System.out.printf("There are %d items in your list.", calculator.getCount()); System.out.println(); System.out.printf("The max of your items is %d.", calculator.getMax()); System.out.println(); System.out.printf("The min of your items is %d.", calculator.getMin()); System.out.println(); System.out.printf("The sum of your items is %d.", calculator.getSum()); System.out.println(); System.out.printf("The mean of your items is %3.2f.", calculator.getMean()); System.out.println(); System.out.printf("The standard deviation of your items is %3.2f.", calculator.getStandardDeviation()); System.out.println(); } }
package ashwiniyer.thebuttongamereturns.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.sql.SQLException; import ashwiniyer.thebuttongamereturns.Scores; /** * Created by Ashwin on 29/10/2015. */ public class HighScoreDataSource { private SQLiteDatabase mDatabase; private HighScoreHelper mHighScoreHelper; private Context mContext; public HighScoreDataSource(Context context) { mContext = context; mHighScoreHelper = new HighScoreHelper(mContext); } //Open a database public void open() throws SQLException { mDatabase = mHighScoreHelper.getWritableDatabase(); } //Close public void close() { mDatabase.close(); } //Insert public void insertHighscore(Scores scores) { ContentValues values = new ContentValues(); values.put(HighScoreHelper.COLUMN_NAME, scores.getName()); values.put(HighScoreHelper.COLUMN_SCORE, scores.getScore()); values.put(HighScoreHelper.COLUMN_MODE, scores.getMode()); mDatabase.insert(HighScoreHelper.TABLE_HIGHSCORES, null, values); } //Select public Cursor selectAllHighScores(int gameMode) { String whereClause = HighScoreHelper.COLUMN_MODE + " = ?"; String gameModeString = "" + gameMode; String order; if(gameMode <5) order =" ASC"; else{ order = "DESC"; } Cursor cursor = mDatabase.query( HighScoreHelper.TABLE_HIGHSCORES,//table new String[]{HighScoreHelper.COLUMN_NAME, HighScoreHelper.COLUMN_SCORE}, //columns whereClause, //where clause new String[]{gameModeString}, //where parameters null, //group by null, //having HighScoreHelper.COLUMN_SCORE + order //order by ); return cursor; } //Update - not necessary for our purposes since we will never need to update a highscore // public int updateScore(double newScore){ //ContentValues values = new ContentValues(); //values.put(HighScoreHelper.COLUMN_SCORE, newScore); //int rowsUpdated = mDatabase.update( //HighScoreHelper.TABLE_HIGHSCORES, //table //values, //values //null, //where clause //null //where parameters //); //return rowsUpdated; //} //Delete - we will call this whenever there are more than 5 scores in a gameMode - we will only be displaying the top 5 scores in our listview for each gameMode public void delete(){ mDatabase.delete( HighScoreHelper.TABLE_HIGHSCORES, null, //where clause null //where params ); } }
package com.favour.dome.entity; import org.junit.*; import javax.persistence.*; import static org.junit.Assert.*; /** * Created by fernando on 03/06/15. */ public class CountryTest { private static EntityManagerFactory emf; private static EntityManager em; private static final String EXISTING_COUNTRY_NAME= "ExistingCountry"; private static final String COUNTRY_TO_UPDATE_NAME= "CountryToUpdate"; private static final String COUNTRY_TO_DELETE_REFERENCED_NAME = "OtherCountry"; private static final String COUNTRY_TO_DELETE_NAME= "CountryToDelete"; private static final int INEXISTENT_COUNTRY_ID = 0; private static final int EXISTING_COUNTRY_ID = 1; private static final int COUNTRY_TO_UPDATE_ID= 2; private static final int COUNTRY_TO_DELETE_REFERENCED_ID= 3; private static final int COUNTRY_TO_DELETE_ID= 4; @BeforeClass public static void initialize() { emf = Persistence.createEntityManagerFactory("favourhub-test"); } @Before public void initializeEntityManager() { em = emf.createEntityManager(); } @Test public void testCountryLookupCountryFound() { EntityTransaction trx = em.getTransaction(); trx.begin(); try { Country testCountry = em.find(Country.class, EXISTING_COUNTRY_ID); assertNotNull(testCountry); assertEquals(EXISTING_COUNTRY_NAME, testCountry.getCountry()); trx.commit(); } catch (Exception e) { trx.rollback(); assertTrue("Unexpected exception " + e,true); } } @Test public void testCountryLookupCountryNotFound() { EntityTransaction trx = em.getTransaction(); trx.begin(); try { Country testCountry = em.find(Country.class, INEXISTENT_COUNTRY_ID); assertNull(testCountry); trx.commit(); } catch (Exception e) { trx.rollback(); assertTrue("Unexpected exception " + e,true); } } @Test public void testCountryCreationOK() { EntityTransaction trx = em.getTransaction(); trx.begin(); try { Country testCountry = new Country(); testCountry.setCountry("NewCountry"); em.persist(testCountry); trx.commit(); assertNotNull(testCountry.getId()); em.detach(testCountry); trx.begin(); Country lookupCountry = em.find(Country.class, testCountry.getId()); trx.commit(); assertEquals(testCountry, lookupCountry); } catch (Exception e) { trx.rollback(); assertTrue("Unexpected exception " + e,true); } } @Test public void testCountryUpdateOk() { EntityTransaction trx = em.getTransaction(); trx.begin(); try { Country testCountry = em.find(Country.class, COUNTRY_TO_UPDATE_ID); assertNotNull(testCountry); assertEquals(COUNTRY_TO_UPDATE_NAME, testCountry.getCountry()); testCountry.setCountry("UpdatedCountry"); trx.commit(); em.detach(testCountry); trx.begin(); Country updatedCountry= em.find(Country.class, COUNTRY_TO_UPDATE_ID); trx.commit(); assertNotNull(testCountry); assertEquals("UpdatedCountry", testCountry.getCountry()); } catch (Exception e) { trx.rollback(); assertTrue("Unexpected exception " + e,true); } } @Test public void testCountryDeleteOk() { EntityTransaction trx = em.getTransaction(); trx.begin(); try { Country testCountry = em.find(Country.class, COUNTRY_TO_DELETE_ID); assertNotNull(testCountry); assertEquals(COUNTRY_TO_DELETE_NAME, testCountry.getCountry()); em.remove(testCountry); trx.commit();; trx.begin(); Country updatedCountry= em.find(Country.class, COUNTRY_TO_DELETE_ID); trx.commit(); assertNull(updatedCountry); } catch (Exception e) { trx.rollback(); assertTrue("Unexpected exception",true); } } @Test public void testCountryDeleteTypeStillReferencedOk() { EntityTransaction tx = em.getTransaction(); tx.begin(); try { Country testCountry = em.find(Country.class,COUNTRY_TO_DELETE_REFERENCED_ID); assertNotNull(testCountry); assertEquals(COUNTRY_TO_DELETE_REFERENCED_NAME,testCountry.getCountry()); em.remove(testCountry); tx.commit(); assertTrue("The delete shouldn't have happened due to existent references to the country", false); } catch (Exception e) { if (!(e instanceof PersistenceException)) { tx.rollback(); assertTrue("Unexpected exception " + e, false); } } } @After public void destroyEntityManager() { em.close(); } @AfterClass public static void tearDown() { emf.close(); } }
package com.j1902.shopping.service; import com.j1902.shopping.pojo.Admin; import com.j1902.shopping.pojo.Item; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; public interface AddItemService { public void addItem(Item item); public void deleteItem(Integer id); public void updateItem(Item item); }
package com.esum.comp.socket.inbound; import java.util.List; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.esum.comp.socket.SocketCode; import com.esum.comp.socket.SocketConfig; import com.esum.comp.socket.SocketException; import com.esum.comp.socket.handler.WaitingChannels; import com.esum.comp.socket.packet.ReaderableMessage; import com.esum.comp.socket.packet.ResponseMessage; import com.esum.comp.socket.table.SocketInfoRecord; import com.esum.framework.core.component.ComponentException; import com.esum.framework.core.component.config.ComponentConfigFactory; import com.esum.framework.core.event.message.EventHeader; import com.esum.framework.core.event.message.MessageEvent; import com.esum.framework.core.exception.SystemException; import com.esum.router.handler.InboundHandlerAdapter; /** * Copyright(c) eSum Technologies, Inc. All rights reserved. */ public class SocketInboundHandler extends InboundHandlerAdapter { private final Logger log = LoggerFactory.getLogger(SocketInboundHandler.class); private SocketConfig config = null; private SocketInfoRecord infoRecord; private ReaderableMessage message; public SocketInboundHandler(String componentId, SocketInfoRecord infoRecord, String messageId, ReaderableMessage message) { super(componentId); super.setLog(log); super.setMessageCtrlId(messageId); super.traceId = "[" + SocketConfig.MODULE_ID+"]["+messageId + "] "; this.infoRecord = infoRecord; this.message = message; } public void onProcess() { log.info(traceId + "Inbound Processing Start... received length : "+message.getRawPacket().length); try { this.config = (SocketConfig) ComponentConfigFactory.getInstance(getComponentId()); initParsingRule(infoRecord.getInterfaceId(), infoRecord.getParsingRule()); List<MessageEvent> respEvents = processMessage(getMessageCtrlId(), message.getRawPacket(), config.getReqMsgInputStatus()); if(preProcessedEvents==null || preProcessedEvents.size()==0) { log.warn(traceId+"Pre-processed MessageEvent not exists. check a log."); return; } MessageEvent preEvent = preProcessedEvents.get(0); log.info(traceId+"Routing path : "+preEvent.getRoutingInfo().getPathFlow()); byte[] responseBytes = null; if(preEvent.getRoutingInfo().getPathSize()==1) { responseBytes = createResponseBytesByRule(preEvent, message); preEvent.getEventHeader().setType(EventHeader.TYPE_ACKNOWLEDGE); preEvent.getMessage().getPayload().setData(responseBytes); respEvents.add(preEvent); } else { if(respEvents!=null && respEvents.size()>0) { log.info(traceId+"ResponseEvent size is "+respEvents.size()); responseBytes = createResponseBytesByRule(respEvents.get(0), message); } } if(responseBytes!=null) { Channel respChannel = WaitingChannels.getInstance().getChannel(getMessageCtrlId()); if(!respChannel.isConnected()) { throw new SocketException(SocketCode.ERROR_CLIENT_CONNECT, "process()", "Could not send response to connected client. client connection closed already."); } if(log.isDebugEnabled()) log.debug(traceId+"Response. length : "+responseBytes.length+", data : ["+new String(responseBytes)+"]"); ChannelBuffer respBuffer = ChannelBuffers.buffer(responseBytes.length); respBuffer.writeBytes(responseBytes); ChannelFuture future = respChannel.write(respBuffer); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { log.info(traceId+"SOCKET Response message sent."); } }); processSyncLogging(respEvents, config.getSyncOutputStatus()); } else { if(log.isDebugEnabled()) log.debug(traceId+"Response Event size is empty. async routing."); } } catch (SocketException e) { log.error(traceId + "process()", e); processError(getMessageCtrlId(), message.getRawPacket(), e); sendToErrorResponse(e); } catch (ComponentException e) { log.error(traceId + "process()", e); processError(getMessageCtrlId(), message.getRawPacket(), e); sendToErrorResponse(new SocketException(e.getErrorCode(), e.getErrorLocation(), e.getErrorMessage())); } catch (Exception e) { log.error(traceId + "process()", e); SocketException ex = new SocketException(SocketCode.ERROR_UNDEFINED, "process()", e.getMessage(), e); processError(getMessageCtrlId(), message.getRawPacket(), ex); sendToErrorResponse(ex); } finally { WaitingChannels.getInstance().removeChannel(getMessageCtrlId()); } } private byte[] createResponseBytesByRule(MessageEvent event, ReaderableMessage message) throws SocketException { byte[] responseBytes = null; ReaderableMessage respMessage = null; try { respMessage = processRule("responseProcess", event, message); if(respMessage==null) throw new SocketException(SocketCode.ERROR_GENERATING_RESP_MESSAGE, "process()", "Response message could not create with a defined parsing rule."); responseBytes = respMessage.unmarshal(); } catch (SocketException e) { throw e; } catch(Exception e) { log.error(traceId + "Error occured in generating Response Message.", e); throw new SocketException(SocketCode.ERROR_GENERATING_RESP_MESSAGE, "process()", "Error occured in generating Response Message. "+e.getMessage()); } return responseBytes; } private void sendToErrorResponse(SocketException exception) { byte[] respBytes = null; try { ResponseMessage rm = new ResponseMessage(); rm.setCode(exception.getErrorCode()); rm.setMessage(exception.getErrorMessage()); respBytes = rm.unmarshal(); } catch (SocketException e) { log.error(traceId+"Socket response message(error) creationg error.", e); return; } Channel respChannel = WaitingChannels.getInstance().getChannel(getMessageCtrlId()); if(respChannel!=null && respChannel.isConnected()) { ChannelBuffer respBuffer = ChannelBuffers.buffer(respBytes.length); respBuffer.writeBytes(respBytes); ChannelFuture future = respChannel.write(respBuffer); future.addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { log.info(traceId+"Error Response message sent."); } }); WaitingChannels.getInstance().removeChannel(getMessageCtrlId()); } else { log.error(traceId+"Channel could not found."); } } public MessageEvent onPreProcess(MessageEvent messageEvent) throws SystemException { try { return preProcess(messageEvent, message, infoRecord.getServerDesc()); } catch (SystemException e) { SocketException ex = new SocketException(e.getErrorCode(), e.getErrorLocation(), e.getErrorMessage(), e); sendToErrorResponse(ex); throw e; } catch (Exception e) { SocketException ex = new SocketException(SocketCode.ERROR_UNDEFINED, "onPreProcess()", e.getMessage(), e); sendToErrorResponse(ex); throw ex; } } }
public class findSmallestNumber { int i = 10; String dupa = "wielka"; }
package org.shazhi.businessEnglishMicroCourse.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.experimental.Accessors; import org.hibernate.annotations.DynamicUpdate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.*; import java.util.List; @Entity @EntityListeners(AuditingEntityListener.class) @Table(name = "security", schema = "business_english") @DynamicUpdate @Getter @Setter @NoArgsConstructor @Accessors(chain = true) public class SecurityEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer securityId; private String securityName; private String scope; @ManyToMany(mappedBy = "securities") @JsonIgnore private List<RoleEntity> roleSecurities; public SecurityEntity ignore(){ return new SecurityEntity() .setSecurityId(securityId) .setSecurityName(getSecurityName()) .setScope(scope); } }
package lab7; import java.util.ArrayList; import java.util.Scanner; import lab6.SV; public class menu { SV sv = new SV(); ArrayList<SV> arr = new ArrayList<>(); Scanner scanner = new Scanner(System.in); private int id; private String name; private boolean f = false; public void menu() { do { System.out.println("MENU"); System.out.println("1. Nhap thong tin sinh vien"); System.out.println("-------------------------------------------"); int choose = scanner.nextInt(); switch(choose) { case 1: add(); break; default: break; } }while(true); } private void add() { System.out.println("Nhap id sinh vien: "); this.id= scanner.nextInt(); do { System.out.println("Nhap ten sinh vien: "); this.name= scanner.nextLine(); try { if("".equals(name)) { throw new Exception("Ten Khong Duoc de trong"); } if(name.matches("[A-Z][a-z]") == true) { throw new Exception("Ten chi phai la ki tu chu cai va khoang trang"); } break; }catch(Exception e){ f=true; System.out.println(e.getMessage()); } }while(f == true); } }
/* * 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 ui; import java.awt.event.ActionEvent; import static java.lang.Math.sqrt; import javax.swing.JOptionPane; /** * * @author causticroot ~joints are all */ public class display extends javax.swing.JFrame { /** * Creates new form display */ public display() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") /* * Global var */ double a = 0.0; double b = 0.0; double c = 0.0; // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jTextFieldDelta = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); jTextFieldB = new javax.swing.JTextField(); jLabel11 = new javax.swing.JLabel(); jLabel12 = new javax.swing.JLabel(); jLabel13 = new javax.swing.JLabel(); jTextFieldA = new javax.swing.JTextField(); jLabel14 = new javax.swing.JLabel(); jTextFieldC = new javax.swing.JTextField(); jButtonGo = new javax.swing.JButton(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jTextFieldR1 = new javax.swing.JTextField(); jTextFieldR2 = new javax.swing.JTextField(); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 100, Short.MAX_VALUE) ); jLabel2.setText("jLabel2"); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jLabel1.setText("BHASKARACHAYANATOR 42000"); jLabel4.setText("DELTA"); jTextFieldDelta.setEditable(false); jTextFieldDelta.setEnabled(false); jLabel9.setText("="); jLabel10.setText("B"); jLabel11.setText("2"); jLabel12.setText("-"); jLabel13.setText("4 * A "); jLabel14.setText("* C"); jButtonGo.setText("POKEMON, TEMOS QUE PEGAR !"); jButtonGo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonGoActionPerformed(evt); } }); jLabel5.setText("R':"); jLabel6.setText("R' ':"); jTextFieldR1.setEnabled(false); jTextFieldR2.setEditable(false); jTextFieldR2.setEnabled(false); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldDelta, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel9) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldR2, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addComponent(jTextFieldB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel11, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel13))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldA, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel14) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jTextFieldC, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addComponent(jLabel5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonGo, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldR1, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3)) .addGroup(layout.createSequentialGroup() .addGap(105, 105, 105) .addComponent(jLabel1))) .addGap(25, 25, 25)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(jLabel1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(87, 87, 87) .addComponent(jLabel3) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(jLabel9) .addComponent(jLabel10) .addComponent(jTextFieldB) .addComponent(jTextFieldC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextFieldDelta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(12, 12, 12) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel12) .addComponent(jLabel13) .addComponent(jTextFieldA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel14))) .addComponent(jLabel11)))) .addGap(24, 24, 24) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(jTextFieldR1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel6) .addComponent(jTextFieldR2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(jButtonGo) .addContainerGap()))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonGoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGoActionPerformed readValues(); if(returnDelta() >= 0.0 && a != 0.0) { jTextFieldDelta.setText(String.valueOf(valueOnString(returnDelta()))); jTextFieldR1.setText(String.valueOf(valueOnString(returnRline('+')))); jTextFieldR2.setText(String.valueOf(valueOnString(returnRline('-')))); }else { JOptionPane.showMessageDialog(null, "Cant calculate !"); } }//GEN-LAST:event_jButtonGoActionPerformed /* * program functions */ public void readValues() { a = Double.parseDouble(jTextFieldA.getText()); b = Double.parseDouble(jTextFieldB.getText()); c = Double.parseDouble(jTextFieldC.getText()); } public String valueOnString(Double value) { String result; result = String.format("%.5f", value); return result; } public double getSqrt(double value) { return sqrt(value); } public double returnDelta() { double delta = (b * b) - (4 * a * c); return delta; } public double returnRline(char symbol) { double expr = 0.0; if(symbol == '+') { expr = ((-1 * b) + getSqrt(returnDelta())) / (2*a); }else if(symbol == '-') { expr = ((-1 * b) - getSqrt(returnDelta())) / (2*a); } return expr; } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(display.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(display.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(display.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(display.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { new display().setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonGo; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel12; private javax.swing.JLabel jLabel13; private javax.swing.JLabel jLabel14; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JTextField jTextFieldA; private javax.swing.JTextField jTextFieldB; private javax.swing.JTextField jTextFieldC; private javax.swing.JTextField jTextFieldDelta; private javax.swing.JTextField jTextFieldR1; private javax.swing.JTextField jTextFieldR2; // End of variables declaration//GEN-END:variables }
//import java.util.Map; // //public class Pair implements Map.Entry<Integer, Integer> { // public Integer key; // public Integer value; // // public Pair(Integer key, Integer value) { // this.key = key; // this.value = value; // } // // @Override // public Integer getKey() { // return key; // } // // @Override // public Integer getValue() { // return value; // } // // @Override // public Integer setValue(Integer value) { // return this.value = value; // } // // @Override // public String toString() { // return "Pair{" + // "key=" + key + // ", value=" + value + // '}'; // } //}
import org.apache.kafka.clients.consumer.*; import org.apache.kafka.common.TopicPartition; import java.util.*; public class ManualOffsetSubmit { private static HashMap<TopicPartition, OffsetAndMetadata> currentOffsets; private static KafkaConsumer<String, String> consumer; private static Set<String> topics; public static void main(String[] args) { Properties props = new Properties(); consumer = new KafkaConsumer<String, String>(props); currentOffsets = new HashMap<>(); topics = Collections.singleton("topics"); int count=0; mapSubmit(consumer, currentOffsets, count); reBalanceListener(); } private static void reBalanceListener() { try { consumer.subscribe(topics,new HandleRebalance()); while (true) { ConsumerRecords<String, String> records = consumer.poll(100); for (ConsumerRecord<String, String> record : records) { System.out.println(record); currentOffsets.put(new TopicPartition(record.topic(), record.partition()), new OffsetAndMetadata(record.offset() + 1, "no metadata")); } consumer.commitAsync(currentOffsets,null); } } catch (Exception e) { e.printStackTrace(); } finally { try { consumer.commitSync(); } finally { consumer.close(); } } } /** * 偏移量保存在一个map中 * @param consumer * @param currentOffsets * @param count */ private static void mapSubmit(KafkaConsumer<String, String> consumer, HashMap<TopicPartition, OffsetAndMetadata> currentOffsets, int count) { while (true) { ConsumerRecords<String, String> records = consumer.poll(100); for (ConsumerRecord<String, String> record : records) { System.out.printf("%s,%s,%s,%s,%s", record.topic(), record.offset(), record.partition(), record.key()); currentOffsets.put(new TopicPartition(record.topic(), record.partition()), new OffsetAndMetadata(record.offset() + 1, "no metadata")); if (count % 1000 == 0) { consumer.commitAsync(currentOffsets,null); } count++; } } } private static class HandleRebalance implements ConsumerRebalanceListener { @Override public void onPartitionsRevoked(Collection<TopicPartition> collection) { System.out.println(currentOffsets); consumer.commitSync(currentOffsets); } @Override public void onPartitionsAssigned(Collection<TopicPartition> collection) { } } }
package com.pdd.pop.sdk.http.api.response; import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty; import com.pdd.pop.sdk.http.PopBaseHttpResponse; public class PddMallInfoVerifyApplicationAddResponse extends PopBaseHttpResponse{ /** * response */ @JsonProperty("mall_info_verify_application_add_response") private MallInfoVerifyApplicationAddResponse mallInfoVerifyApplicationAddResponse; public MallInfoVerifyApplicationAddResponse getMallInfoVerifyApplicationAddResponse() { return mallInfoVerifyApplicationAddResponse; } public static class MallInfoVerifyApplicationAddResponse { /** * 是否成功 */ @JsonProperty("is_success") private Boolean isSuccess; public Boolean getIsSuccess() { return isSuccess; } } }
package com.example.ui; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.TextView; import com.utbike.testretrofit.R; /** * Created by zhouyubin on 2017/9/22. */ public class ProgressDialogHandler extends Handler { private Context mContext; private CancelListener mCancelListener = new CancelListener() { @Override public void onCancel() { Log.i("ProgressDialog", "onCancel"); } }; private Dialog mProgressDialog; private boolean mCancelable; private TextView txtMessage; public final static int HANDLER_SHOWDIALOG = 1; public final static int HANDLER_DIMISSDIALOG = 2; public interface CancelListener { void onCancel(); } public ProgressDialogHandler(Context context, CancelListener cancelListener, boolean cancelable) { mContext = context; mCancelListener = cancelListener; mCancelable = cancelable; } private void show(String msg) { if (mProgressDialog == null) { mProgressDialog = new Dialog(mContext); View view = mProgressDialog.getLayoutInflater().inflate(R.layout.dialog_progress, null); txtMessage = view.findViewById(R.id.txt_tip); mProgressDialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE); mProgressDialog.setContentView(view); mProgressDialog.setCancelable(mCancelable); if (mCancelable) { mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { if (mCancelListener != null) mCancelListener.onCancel(); } }); } } if (msg != null) txtMessage.setText(msg); if (!mProgressDialog.isShowing()) { mProgressDialog.show(); } } private void dissmiss() { if (mProgressDialog != null) { mProgressDialog.dismiss(); mProgressDialog = null; } } public void showDialog(String obj){ obtainMessage(HANDLER_SHOWDIALOG,obj).sendToTarget(); } public void hideDialog(){ sendEmptyMessage(HANDLER_DIMISSDIALOG); } @Override public void handleMessage(Message msg) { switch (msg.what) { case HANDLER_SHOWDIALOG: show((String) msg.obj); break; case HANDLER_DIMISSDIALOG: dissmiss(); break; } } }
package undirectedGraphANDdijkstra; import java.util.Iterator; /**<pre> * ******************************************************************************************************************** * LinkedList.java * ******************************************************************************************************************** * * <strong>Description:</strong> This class allows for the instantiation of a single Linked List of generic type. * * For information about other classes and methods used for this project, please refer to their javadocs. * ********************************************************************************************************************* * @author VagnerMachado - QCID 23651127 - Queens College - Spring 2018 ********************************************************************************************************************* * * @param K - a generic type * * *<a href="http://www.facebook.com/vagnermachado84"> Do you like this code? Let me know! </a> *</pre> */ public class LinkedList<K> implements Iterable<K> { //instance data private Entry<K> head; private int size; /** * LinkedMap constructor - Starts a LinkedMap with a null Entry to be the head */ public LinkedList() { head = null; size = 0; } /*** * clear - clears the LinkedMap */ public void clear() { head = null; size = 0; System.gc(); } /** * put - puts an Entry to the front of the linked list * @param data - key to be inserted * @throws GeneralException - if the item to be put is null */ public void put(K k) { if (k == null) throw new GeneralException("\n *** Linked List Exception: " + "A null key cannot be inserted in the Linked list ***\n"); if(size == 0) head = new Entry<K>(k); else { Entry<K> temp = new Entry<K>(k); temp.setNext(head); head = temp; } size++; } /** * remove - removes the item with the key passed as parameter * @param <K> - the key */ @SuppressWarnings({ "unchecked", "rawtypes" }) public void remove(K key) { if ( size == 0) { System.out.println("\n*** The Linked list is empty, you cannot remove an item ***\n"); return; } Entry trav = head; Entry before = head; //V value = null; for(int i = 0; i < size; i ++) { if(trav.getData() == key) { if (i == 0) // first head = head.getNext(); else if (i == size - 1) //last before.setNext(null); else // middle before.setNext(trav.getNext()); size--; return; } else { before = trav; trav = trav.getNext(); } } } /** * isEmpty - let's the user know if the linked list size is zero * @return - true if the size is zero, false otherwise */ public boolean isEmpty() { return size == 0; } /** * getSize - accessor for the size of linked list * @return - the size of the linked list */ public int size() { return size; } /** * contains - let's user know if the linked list contains certain key * @param key - the key being looked for * @return - true if list contains the key, false otherwise. */ public boolean contains(K k) { Entry <K> trav = head; for(int i = 0; i < size; i++) { if(k == (trav.getData())) return true; else trav = trav.getNext(); } return false; } @SuppressWarnings("rawtypes") /** * toString - gives a string to the user containing all the data in it */ public String toString() { String result = ""; Entry trav = head; for(int i = 0; i < size; i++) { result += trav.toString(); trav = trav.getNext(); } return result; } /** * get - accessor for a copy of an Entry needed to expand the Hash list * @param index - the index for the Entry needed * @return - a copy of an Entry at a valid index, avoid manipulation of original data */ public K get(int index) { if (index < 0 || index > size - 1) { System.out.println("Invalid call to get"); } Entry <K> trav = head; int i = 0; while (i++ < index) trav = trav.getNext(); return (K)trav.getData(); } /** * iterator - returns an instance of ListIterator */ public Iterator<K> iterator() { return new ListIterator<K>(); } @SuppressWarnings("hiding") /** * ListIterator - allows for the iteration of a Linked List * @author Vagner Machado * @param <K> - a generic type */ private class ListIterator<K> implements Iterator<K> { @SuppressWarnings("unchecked") //instance data private Entry<K> trav = (Entry<K>) head; /** * hasNext - condition to stop iteration is checked */ public boolean hasNext() { return trav != null; } @Override /** * next - saves the data in a variable, moves the pointer to next and returns data */ public K next() { K data = trav.getData(); trav = trav.getNext(); return data; } } /**<pre>************************************************************************************************************** * Entry.java ********************************************************************************************************************* * * Description: Allows user to create Entry Objects that take generic parameters K. * The class provides getters and setters for the field data in addition to a to String method, these objects * are meant to be used on the Linked list for Project 3. Each Entry object contains a key and a pointer to * the next Entry * * For information about the other classes created for this project, please see their javadocs. * ********************************************************************************************************************* * @author VagnerMachado - ID 23651127 - Queens College - Spring 2018 ********************************************************************************************************************* * * @param <K> - generic for the key for the object *<pre> ***/ @SuppressWarnings("hiding") public class Entry<K> { //instance data private K data; private Entry<K> next; /** * Entry constructor * @param key - the Entry's key * @param value - the Entry's value */ public Entry(K k) { data = k; next = null; } /** * getNext - accessor for the next Entry * @return next - the next Entry */ public Entry<K> getNext() { return next; } /** * setNext r- mutator for the next Entry * @param n - the new next Entry */ public void setNext(Entry<K> n) { next = n; } /** * getKey method - accessor to Entry's key * @return key - the Entry's key */ public K getData() { return data; } /** * setKey method - setter for Entry's Key * @return key - the Entry's key */ public void setData(K k) { data = k; } @Override /** * toString method - prints the key and value for the entry */ public String toString() { return data + " -> "; } } }
package com.trump.auction.trade.api.impl; import com.alibaba.dubbo.config.annotation.Service; import com.cf.common.util.mapping.BeanMapper; import com.trump.auction.trade.api.RobotStubService; import com.trump.auction.trade.domain.RobotInfo; import com.trump.auction.trade.model.RobotInfoModel; import com.trump.auction.trade.service.RobotService; import org.springframework.beans.factory.annotation.Autowired; /** * 机器人 * * @author zhangliyan * @create 2018-01-08 13:46 **/ @Service(version = "1.0.0") public class RobotStubServiceImpl implements RobotStubService { @Autowired private RobotService robotService; @Autowired private BeanMapper beanMapper; /** * 保存新建机器人 * * @param robotInfoModel * @return */ @Override public Integer insertRobot(RobotInfoModel robotInfoModel) { return robotService.insertRobot(beanMapper.map(robotInfoModel, RobotInfo.class)); } /** * 修改机器人 * * @param robotInfoModel * @return */ @Override public int saveUpdateRobot(RobotInfoModel robotInfoModel) { return robotService.saveUpdateRobot(beanMapper.map(robotInfoModel, RobotInfo.class)); } /** * 删除机器人 * * @param ids * @return */ @Override public int deleteRobot(String[] ids) { return robotService.deleteRobot(ids); } }
package com.beadhouse.controller; import com.beadhouse.dao.UserMapper; import com.beadhouse.domen.User; import com.beadhouse.utils.AsyncTask; import com.beadhouse.utils.Constant; import com.beadhouse.utils.FireBaseUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.io.IOException; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Random; @Component @EnableScheduling public class ScheduledController { @Autowired private UserMapper userMapper; @Resource private FireBaseUtil fireBaseUtil; @Resource private AsyncTask asyncTask; @Scheduled(cron = "0 0 9 * * ?") public void pushDataScheduled() { System.out.println("1111111111111111111111111111111111"); List<User> userList = userMapper.selectUserList(); Date now = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(now);// 将时分秒,毫秒域清零 calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); long time = calendar.getTime().getTime(); for (User user : userList) { asyncTask.asyncToSendPush(user, time); } } public static void main(String args[]) { new ScheduledController().pushDataScheduled(); } }
/* * 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 witchinn; import environment.Actor; import environment.Velocity; import images.ResourceTools; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Point; /** * * @author carateresa */ public class Ingredient extends Actor { //<editor-fold defaultstate="collapsed" desc="Static Constants"> public static final String INGREDIENT_VINE = "VINE"; public static final String INGREDIENT_TURTLE = "TURTLE"; public static final String INGREDIENT_TREE = "TREE"; public static final String INGREDIENT_CACTUS = "CACTUS"; public static final String INGREDIENT_BULB = "BULB"; public static final String INGREDIENT_DAGGER = "DAGGER"; public static final String INGREDIENT_EARTH = "EARTH"; public static final String INGREDIENT_EGGSHELLS = "EGGSHELLS"; public static final String INGREDIENT_EYES = "EYES"; public static final String INGREDIENT_GAS = "GAS"; public static final String INGREDIENT_GRASS = "GRASS"; public static final String INGREDIENT_GREENS = "GREENS"; public static final String INGREDIENT_MUSHROOMS = "MUSHROOMS"; public static final String INGREDIENT_PETALS = "PETALS"; public static final String INGREDIENT_PINK = "PINK"; public static final String INGREDIENT_ROSE = "ROSE"; public static final String INGREDIENT_SAGE = "SAGE"; public static final String INGREDIENT_SHELLS = "SHELLS"; public static final String INGREDIENT_SMALLPLANT = "SMALLPLANT"; public static final String INGREDIENT_SUNLIGHT = "SUNLIGHT"; public static final String INGREDIENT_VASE = "VASE"; //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Constructors and Factory Methods"> public static Ingredient getIngredient(String name) { switch (name){ case INGREDIENT_TURTLE: return new Ingredient(name, loadImage("resources/turtle.PNG"), new Point(10, 10)); case INGREDIENT_TREE: return new Ingredient(name, loadImage("resources/tree.PNG"), new Point(10, 10)); case INGREDIENT_CACTUS: return new Ingredient(name, loadImage("resources/cactus.PNG"), new Point(10, 10)); case INGREDIENT_BULB: return new Ingredient(name, loadImage("resources/bulb.PNG"), new Point(10, 10)); case INGREDIENT_DAGGER: return new Ingredient(name, loadImage("resources/dagger.PNG"), new Point(10, 10)); case INGREDIENT_EARTH: return new Ingredient(name, loadImage("resources/earth.PNG"), new Point(10, 10)); case INGREDIENT_EGGSHELLS: return new Ingredient(name, loadImage("resources/eggshells.PNG"), new Point(10, 10)); case INGREDIENT_EYES: return new Ingredient(name, loadImage("resources/eyes.PNG"), new Point(10, 10)); case INGREDIENT_GAS: return new Ingredient(name, loadImage("resources/gas.PNG"), new Point(10, 10)); case INGREDIENT_GRASS: return new Ingredient(name, loadImage("resources/grass.PNG"), new Point(10, 10)); case INGREDIENT_GREENS: return new Ingredient(name, loadImage("resources/greens.PNG"), new Point(10, 10)); case INGREDIENT_MUSHROOMS: return new Ingredient(name, loadImage("resources/mushrooms.PNG"), new Point(10, 10)); case INGREDIENT_PETALS: return new Ingredient(name, loadImage("resources/petals.PNG"), new Point(10, 10)); case INGREDIENT_PINK: // return new Ingredient(name, loadImage("resources/pink.PNG"), new Point(10, 10)); return new Ingredient(name, loadImage("resources/shells.PNG"), new Point(10, 10)); case INGREDIENT_ROSE: return new Ingredient(name, loadImage("resources/rose.PNG"), new Point(10, 10)); case INGREDIENT_SAGE: return new Ingredient(name, loadImage("resources/sage.PNG"), new Point(10, 10)); case INGREDIENT_SHELLS: return new Ingredient(name, loadImage("resources/shells.PNG"), new Point(10, 10)); case INGREDIENT_SMALLPLANT: return new Ingredient(name, loadImage("resources/smallplant.PNG"), new Point(10, 10)); case INGREDIENT_SUNLIGHT: return new Ingredient(name, loadImage("resources/sunlight.PNG"), new Point(10, 10)); case INGREDIENT_VASE: return new Ingredient(name, loadImage("resources/vase.PNG"), new Point(10, 10)); default: case INGREDIENT_VINE: return new Ingredient(name, loadImage("resources/vine.png"), new Point(10, 10)); } } { preferredSize = new Dimension(45, 60); } public Ingredient(Image image, Point position, Velocity velocity) { super(image, position, velocity); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Methods"> public Ingredient(String name, Image image, Point position) { super(image, position, new Velocity(0, 0)); this.name = name; } @Override public void paint(Graphics graphics){ graphics.drawImage(getScaledImage(), getPosition().x, getPosition().y, null); } public static Image loadImage(String path) { return ResourceTools.loadImageFromResource(path); } Image getScaledImage() { return super.getImage().getScaledInstance(preferredSize.width, preferredSize.height, Image.SCALE_FAST); } //</editor-fold> //<editor-fold defaultstate="collapsed" desc="Properties"> private boolean visible = true; private Dimension preferredSize; private String name; /** * @return the visible */ public boolean isVisible() { return visible; } /** * @param visible the visible to set */ public void setVisible(boolean visible) { this.visible = visible; } /** * @return the preferredSize */ public Dimension getPreferredSize() { return preferredSize; } /** * @param preferredSize the preferredSize to set */ public void setPreferredSize(Dimension preferredSize) { this.preferredSize = preferredSize; } /** * @return the name */ @Override public String getName() { return name; } /** * @param name the name to set */ @Override public void setName(String name) { this.name = name; } //</editor-fold> }
package com.azwinckteam.androidmultichoicequiz; import android.media.MediaPlayer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.DisplayMetrics; import com.azwinckteam.androidmultichoicequiz.Adapter.CategoryAdapter; import com.azwinckteam.androidmultichoicequiz.Common.SpaceDecoration; import com.azwinckteam.androidmultichoicequiz.DBHelper.DBHelper; public class MainActivity extends AppCompatActivity { Toolbar toolbar; RecyclerView recyler_category; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar)findViewById(R.id.toolbar); toolbar.setTitle("TOEIC"); setSupportActionBar(toolbar); recyler_category = (RecyclerView)findViewById(R.id.rycyler_category); recyler_category.setHasFixedSize(true); recyler_category.setLayoutManager(new GridLayoutManager(this, 2)); //Get Screen High DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int heigh = displayMetrics.heightPixels / 8; //Max size of item in category CategoryAdapter adapter = new CategoryAdapter(MainActivity.this, DBHelper.getInstance(this).getAllCategories()); int spaceInPixel = 4; recyler_category.addItemDecoration(new SpaceDecoration(spaceInPixel)); recyler_category.setAdapter(adapter); } }
package com.chisw.timofei.booking.accommodation.service.api.dto; import lombok.Builder; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * @author timofei.kasianov 10/2/18 */ @RequiredArgsConstructor @Getter @Builder public class AccommodationDTO { private final String id; private final long ratePerNightInCents; private final String description; private final String hostId; }
package com.njit.card.dao.impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import com.njit.card.dao.StudentDAO; import com.njit.card.entity.Book; import com.njit.card.entity.BookRecord; import com.njit.card.entity.Card; import com.njit.card.entity.FoodItem; import com.njit.card.entity.CostRecord; import com.njit.card.entity.Student; import com.njit.card.utils.DBUtil; public class StudentDAOImpl implements StudentDAO{ public Student findById(long id){ Connection conn=null; Student s=null; try{ conn=DBUtil.getConnection(); String sql="select * from student where studentid=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1, id); ResultSet rst=prep.executeQuery(); while(rst.next()){ s=new Student(); s.setStudentid(id); s.setBanji(rst.getString("banji")); s.setJiguan(rst.getString("jiguan")); s.setNianling(rst.getInt("nianling")); s.setRuxueshijian(rst.getDate("ruxueshijian")); s.setXingbie(rst.getString("xingbie")); s.setXingming(rst.getString("xingming")); s.setXuyuan(rst.getString("xueyuan")); s.setZhuanye(rst.getString("zhuanye")); s.setZhuzhi(rst.getString("zhuzhi")); } }catch(Exception e){ e.printStackTrace(); }finally{ DBUtil.close(conn); } return s; } public List<FoodItem> findFoodItems() throws Exception { Connection conn=null; List<FoodItem>foodItems= new ArrayList<FoodItem>(); FoodItem f=null; try{ conn=DBUtil.getConnection(); String sql="select * from fooditem"; PreparedStatement prep=conn.prepareStatement(sql); ResultSet rst=prep.executeQuery(); while(rst.next()){ f=new FoodItem(); f.setFoodid(rst.getLong("foodid")); f.setFoodname(rst.getString("foodname")); f.setDanjia(rst.getDouble("danjia")); f.setChuangkou(rst.getInt("chuangkou")); foodItems.add(f); } }catch(Exception e){ e.printStackTrace(); }finally{ DBUtil.close(conn); } return foodItems; } public FoodItem findByFoodItemId(long foodid) throws Exception { Connection conn=null; FoodItem f=null; try{ conn=DBUtil.getConnection(); String sql="select * from fooditem where foodid=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1,foodid); ResultSet rst=prep.executeQuery(); while(rst.next()){ f=new FoodItem(); f.setFoodid(rst.getLong("foodid")); f.setFoodname(rst.getString("foodname")); f.setDanjia(rst.getDouble("danjia")); f.setChuangkou(rst.getInt("chuangkou")); } }catch(Exception e){ e.printStackTrace(); }finally{ DBUtil.close(conn); } return f; } public void addCostRecord(CostRecord record) throws Exception { Connection conn=null; conn=DBUtil.getConnection(); String sql="insert into costrecord(cardid,foodid,costtime,costleft)values(?,?,?,?)"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1,record.getCardid()); prep.setLong(2,record.getFoodid()); Date date=new Date(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String costtime=sdf.format(date); prep.setString(3,costtime); Card card=findByCardId(record.getCardid()); System.out.println(); prep.setDouble(4, card.getBalance()); prep.execute(); } public List<FoodItem> findFoodItemsById(long cardid) throws Exception { Connection conn=null; List<FoodItem> foodItems=new ArrayList<FoodItem>(); FoodItem item=null; conn=DBUtil.getConnection(); String sql="select * from costrecord where cardid=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1,cardid); ResultSet rst= prep.executeQuery(); while(rst.next()){ item=findByFoodItemId(rst.getLong("foodid")); foodItems.add(item); } return foodItems; } public List<CostRecord> findCostRecordsById(long cardid) throws Exception { Connection conn=null; List<CostRecord>records=new ArrayList<CostRecord>(); CostRecord record=null; conn=DBUtil.getConnection(); String sql="select * from costrecord where cardid=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1,cardid); ResultSet rst=prep.executeQuery(); while(rst.next()){ record=new CostRecord(); record.setCardid(cardid); record.setCostleft(rst.getDouble("costleft")); record.setCosttime(rst.getDate("costtime")); record.setFoodid(rst.getLong("foodid")); records.add(record); } return records; } public List<Book> findBooks() throws Exception { Connection conn=null; List<Book>booklist=new ArrayList<Book>(); Book book=null; try{ conn=DBUtil.getConnection(); String sql="select * from book"; PreparedStatement prep=conn.prepareStatement(sql); ResultSet rst=prep.executeQuery(); while(rst.next()){ book=new Book(); book.setBookid(rst.getLong("bookid")); book.setBookname(rst.getString("bookname")); book.setBookstate(rst.getInt("bookstate")); book.setChubanshe(rst.getString("chubanshe")); book.setQixian(rst.getString("qixian")); book.setZuozhe(rst.getString("zuozhe")); booklist.add(book); } }catch(Exception e){ e.printStackTrace(); }finally{ DBUtil.close(conn); } return booklist; } public Book findBookById(long bookid) throws Exception { Connection conn=null; Book book=null; try{ conn=DBUtil.getConnection(); String sql="select * from book where bookid=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1,bookid); ResultSet rst=prep.executeQuery(); while(rst.next()){ book=new Book(); book.setBookid(bookid); book.setBookname(rst.getString("bookname")); book.setBookstate(rst.getInt("bookstate")); book.setChubanshe(rst.getString("chubanshe")); book.setQixian(rst.getString("qixian")); book.setZuozhe(rst.getString("zuozhe")); } }catch(Exception e){ DBUtil.close(conn); } return book; } public void addBookRecord(BookRecord bookRecord) throws Exception { Connection conn=null; try{ conn=DBUtil.getConnection(); String sql="insert into bookrecord(cardid,bookid,jieshushijian,huanshushijian)values(?,?,?,?)"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1, bookRecord.getCardid()); prep.setLong(2, bookRecord.getBookid()); Date date=new Date(); SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); sdf.format(date); prep.setString(3,sdf.format(date) ); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, 60); prep.setString(4,sdf.format(cal.getTime())); prep.execute(); Book book=findBookById(bookRecord.getBookid()); updateBookState(book.getBookid(), book.getBookstate()-1); }catch(Exception e){ e.printStackTrace(); }finally{ DBUtil.close(conn); } } public void updateBookState(long bookid,int bookstate) throws Exception { Connection conn=null; try{ conn=DBUtil.getConnection(); String sql="update book set bookstate=? where bookid=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setInt(1,bookstate); prep.setLong(2,bookid); prep.execute(); }catch(Exception e){ e.printStackTrace(); }finally{ DBUtil.close(conn); } } public List<Book> findBookRecordsById(long cardid) throws Exception { Connection conn=null; List<Book>records=new ArrayList<Book>(); BookRecord record=null; conn=DBUtil.getConnection(); String sql="select * from bookrecord where cardid=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1,cardid); ResultSet rst=prep.executeQuery(); while(rst.next()){ record=new BookRecord(); record.setCardid(cardid); record.setBookid(rst.getLong("bookid")); Book book=findBookById(rst.getLong("bookid")); records.add(book); } return records; } public void delBookRecordById(long bookRecordId) throws Exception { Connection conn=null; try{ conn=DBUtil.getConnection(); String sql="delete from bookrecord where bookid=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1,bookRecordId); prep.execute(); int num= findBookById(bookRecordId).getBookstate(); updateBookState(bookRecordId, num+1); }finally{ DBUtil.close(conn); } } public Card findByCardId(long cardid) throws Exception { Connection conn=null; Card card=null; try{ conn=DBUtil.getConnection(); String sql="select * from card where cardid=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1,cardid); ResultSet rst=prep.executeQuery(); while(rst.next()){ card=new Card(); card.setCardid(cardid); card.setBalance(rst.getDouble("balance")); card.setCardstate(rst.getBoolean("cardstate")); card.setMm(rst.getString("mm")); card.setUsername(rst.getString("username")); card.setStudentid(rst.getLong("studentid")); } }finally{ DBUtil.close(conn); } return card; } @Override public boolean findBookById(long studentId, long bookId) throws Exception { // TODO 自动生成的方法存根 Connection conn=null; conn=DBUtil.getConnection(); String sql="select * from bookrecord where cardid=? and bookid=?"; PreparedStatement prep=conn.prepareStatement(sql); prep.setLong(1,studentId); prep.setLong(2,bookId); ResultSet rst=prep.executeQuery(); boolean b = rst.next(); DBUtil.close(conn); System.out.println(b); return b; } }
package com.clouway.task2; import java.util.ArrayList; public class HeterogenTree { protected ArrayList<TreeNode> elements = new ArrayList<TreeNode>(); protected TreeNode currentElement = null; /** * Default constructor. Adds a root element with no data. */ public HeterogenTree(){ TreeNode root = new TreeNode(null); this.elements.add(root); this.currentElement = root; } /** * Constructor setting a data object to the root element * @param data */ public HeterogenTree(Object data){ TreeNode root = new TreeNode(null, data); this.elements.add(root); this.currentElement = root; } /** * Swap two elements of the tree. * @param a * @param b */ protected void swapElements(TreeNode a, TreeNode b){ Object tempData = a.getData(); a.setData(b.getData()); b.setData(tempData); } /** * Add a new element with a unique data object * @param data the data object * @return */ public boolean add(Object data){ if(hasElement(data)){ return false; } int parentInd = (this.elements.size() - 1) / 2; TreeNode parent = this.elements.get(parentInd); TreeNode elem = new TreeNode(parent, data); this.elements.add(elem); parent.addChild(elem); this.currentElement = elem; return true; } /** * Check if a data object is in the tree * @param data the data object * @return */ public boolean hasElement(Object data){ for(TreeNode elem : this.elements){ Object elemData = elem.getData(); if(elemData != null && elemData.equals(data)){ return true; } } return false; } /** * Print all the elements of the tree to the console */ public void printElements(){ for(TreeNode elem : this.elements){ System.out.printf("%s, ", elem.getData()); } } /** * Move the currentElement pointer to the root element * @return */ public boolean seekRoot(){ this.currentElement = this.elements.get(0); if(this.currentElement != null) return true; return false; } /** * Move the currentElement pointer to the parent element, if there is a parent * @return */ public boolean seekParent(){ TreeNode parent = this.currentElement.getParent(); if(parent == null){ return false; } this.currentElement = parent; return true; } /** * Move the currentElement pointer to a direct child element. * @param childInd index of a child * @return */ public boolean seekChild(int childInd){ try{ TreeNode child = this.currentElement.getChildren()[childInd]; if(child == null){ return false; } this.currentElement = child; return true; } catch (ArrayIndexOutOfBoundsException e){ return false; } } /** * Move the currentElement pointer to a deep child element. * @param indices a list of integer arguments * @return */ public boolean seekChildren(int ... indices){ for(int ind : indices){ if(!seekChild(ind)) return false; } return true; } /** * Return the data object of the current element * @return */ public Object getObjectData(){ return this.currentElement.getData(); } }
package net.cnr.studentManagentBackEnd.test; import static org.junit.Assert.assertEquals; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import net.cnr.studentManagentBackEnd.dao.DepartmentDao; import net.cnr.studentManagentBackEnd.dto.Department; public class DepartmentTestCase { private static AnnotationConfigApplicationContext context; @Autowired private static DepartmentDao departmentDao; private Department department; @BeforeClass public static void init(){ context = new AnnotationConfigApplicationContext(); context.scan("net.cnr.studentManagentBackEnd"); context.refresh(); departmentDao = (DepartmentDao) context.getBean("departmentDao"); } /* @Test public void testAddCategory() { department = new Department(); department.setName("Department of Robetics"); department.setExtension("111"); department.setActive(true); department.setName("Department of Business"); department.setExtension("222"); department.setActive(true); assertEquals("Not successfully addes a department inside the table department", true, departmentDao.add(department)); }*/ /* @Test public void testUpdateProduct(){ department = departmentDao.get(3); department.setName("Department Of Computing"); assertEquals("Some thing went wrong while Updating a product",true,departmentDao.update(department)); } */ /* @Test public void testDeleteDepartment(){ department = departmentDao.get(3); assertEquals("Some thing went wrong while Updating a product",true,departmentDao.delete(department)); } */ /*@Test public void testListDepartment(){ assertEquals("Some thing went wrong while Updating a product",4,departmentDao.list().size()); }*/ }
package myGame; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Scanner; public class Decrypt { public void decrypte(String levelName){ int stop = 0; String actualCaractere = "", stringOut=""; int i=0, keyCompt=0; int[] key = {1,4,5,8,2,1,4,5,6,3,5,5,2,1,4,5,7,8,4,5,2,2,1,4,5,2,3,6,5,4,4,7,4,5,8,9,6,5,4,2}; try { if(stop==0){ File file = new File(levelName+".txt"); Scanner input = new Scanner(file); while(input.hasNextLine()) { actualCaractere += input.nextLine()+'\n'; } char[] charArray = actualCaractere.toCharArray(); char[] decrypted = new char[charArray.length+1]; for(i=0; i<charArray.length; i++){ decrypted[i] = (char) (charArray[i]^key[keyCompt]); keyCompt++; if(keyCompt==40)keyCompt=0; } keyCompt=39; for(i=0; i<charArray.length; i++){ decrypted[i] = (char) (decrypted[i]^key[keyCompt]); keyCompt--; if(keyCompt==-1)keyCompt=39; } keyCompt=0; for(i=0; i<charArray.length; i++){ decrypted[i] = (char) (decrypted[i]^key[keyCompt]); keyCompt+=2; if(keyCompt==38)keyCompt=0; } for(i=0; i<charArray.length-1; i++){ stringOut+=decrypted[i]; } FileOutputStream tempFile = new FileOutputStream(levelName+".txt"); tempFile.write(stringOut.getBytes()); stop=1; } } catch (IOException e) { e.printStackTrace(); System.out.println("Can't open level.txt"); } } }
package kickstart.controller; import org.salespointframework.inventory.Inventory; import org.salespointframework.inventory.InventoryItem; import org.salespointframework.order.Order; import org.salespointframework.order.OrderManager; import org.salespointframework.order.OrderStatus; import java.util.Optional; import org.salespointframework.useraccount.Role; import org.salespointframework.useraccount.UserAccount; import org.salespointframework.useraccount.UserAccountIdentifier; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import kickstart.model.CustomerRepository; import org.salespointframework.useraccount.UserAccountManager; import kickstart.model.validation.customerEditForm; import kickstart.model.validation.employeeEditForm; import javax.management.relation.RoleStatus; import javax.validation.Valid; import kickstart.model.Customer; @Controller @PreAuthorize("hasRole('ROLE_BOSS')") class BossController { private final OrderManager<Order> orderManager; private final Inventory<InventoryItem> inventory; private final CustomerRepository customerRepository; private final UserAccountManager userAccountManager; @Autowired public BossController(OrderManager<Order> orderManager, Inventory<InventoryItem> inventory, CustomerRepository customerRepository, UserAccountManager userAccountManager) { this.orderManager = orderManager; this.inventory = inventory; this.customerRepository = customerRepository; this.userAccountManager = userAccountManager; } @RequestMapping("/customers") public String customers(ModelMap modelMap) { modelMap.addAttribute("customerList", customerRepository.findAll()); return "customers"; } @RequestMapping(value = "/customers/delete/{id}", method = RequestMethod.POST) public String removeCustomer(@PathVariable Long id) { customerRepository.delete(id); return "redirect:/customers"; } @RequestMapping(value = "/customers/edit/{id}") public String editCustomer(@PathVariable("id") Long id, Model model, ModelMap modelMap) { modelMap.addAttribute("customerEditForm", new customerEditForm()); Customer customer_found = customerRepository.findOne(id); model.addAttribute("customer", customer_found); return "customers_edit"; } @RequestMapping(value = "/customers/edit/{id}", method = RequestMethod.POST) public String saveCustomer(@PathVariable("id") Long id, Model model, @ModelAttribute("customerEditForm") @Valid customerEditForm customerEditForm, BindingResult result) { Customer customer_found = customerRepository.findOne(id); model.addAttribute("customer", customer_found); if (result.hasErrors()) { return "customers_edit"; } customer_found.setFirstname(customerEditForm.getFirstname()); customer_found.setLastname(customerEditForm.getLastname()); customer_found.setMail(customerEditForm.getMail()); customer_found.setPhone(customerEditForm.getPhone()); customer_found.setAddress(customerEditForm.getAddress()); customerRepository.save(customer_found); if(customerEditForm.getPassword() != "") { userAccountManager.changePassword(customer_found.getUserAccount(), customerEditForm.getPassword()); } return "redirect:/customers"; } @RequestMapping("/employees") public String employees(ModelMap modelMap) { modelMap.addAttribute("employeeList_enabled", userAccountManager.findEnabled()); modelMap.addAttribute("employeeList_disabled", userAccountManager.findDisabled()); return "employees"; } @RequestMapping(value = "/employees/disable/{userAccountIdentifier}", method = RequestMethod.POST) public String disableEmployee(@PathVariable UserAccountIdentifier userAccountIdentifier) { userAccountManager.disable(userAccountIdentifier); return "redirect:/employees"; } @RequestMapping(value = "/employees/enable/{userAccountIdentifier}", method = RequestMethod.POST) public String enableEmployee(@PathVariable UserAccountIdentifier userAccountIdentifier) { userAccountManager.enable(userAccountIdentifier); return "redirect:/employees"; } @RequestMapping(value = "/employees/edit/{userAccountIdentifier}") public String editEmployee(@PathVariable UserAccountIdentifier userAccountIdentifier, Model model, ModelMap modelMap) { modelMap.addAttribute("employeeEditForm", new employeeEditForm()); model.addAttribute("employee", userAccountIdentifier); return "employees_edit"; } @RequestMapping(value = "/employees/edit/{userAccountIdentifier}", method = RequestMethod.POST) public String saveEmployee(@PathVariable UserAccountIdentifier userAccountIdentifier, Model model, @ModelAttribute("employeeEditForm") @Valid employeeEditForm employeeEditForm, BindingResult result) { if(employeeEditForm.getPassword() != "") { // todo //userAccountManager.changePassword(); } return "redirect:/employees"; } }
package com.asynctest.demo.controller; import org.hamcrest.CoreMatchers; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import static org.junit.jupiter.api.Assertions.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*; @AutoConfigureMockMvc @SpringBootTest class HomeControllerTest { @Autowired private MockMvc mockMvc; @Test @DisplayName("测试callable正确执行返回字符串") void callableResult() throws Exception { /* MvcResult result = mockMvc.perform(get("/home/callable")) //执行请求  .andExpect(request().asyncStarted()) //.andExpect(request().asyncResult(CoreMatchers.instanceOf(User.class))) //默认会等10秒超时  .andReturn();  mockMvc.perform(asyncDispatch(result))  .andExpect(status().isOk())  .andExpect(content().contentType(MediaType.APPLICATION_JSON))  .andExpect(jsonPath("$.id").value(1)); */ MvcResult mvcResult = mockMvc.perform(get("/home/callable")) .andExpect(request().asyncStarted()) .andReturn(); mockMvc.perform(asyncDispatch(mvcResult)) .andExpect(status().isOk()) .andExpect(content().string("this is callable")); } @Test @DisplayName("测试callable不正确执行返回字符串") void deferredResult() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/home/callable") .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andReturn(); String content = mvcResult.getResponse().getContentAsString(); assertThat(content, equalTo("")); } @Test @DisplayName("测试async返回字符串") void getAsynHello() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/home/async") .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andReturn(); String content = mvcResult.getResponse().getContentAsString(); assertThat(content, equalTo("this is async")); } @Test @DisplayName("测试sync返回字符串") void getSyncHello() throws Exception { MvcResult mvcResult = mockMvc.perform(get("/home/sync") .contentType(MediaType.APPLICATION_FORM_URLENCODED)) .andReturn(); String content = mvcResult.getResponse().getContentAsString(); assertThat(content, equalTo("this is sync")); } }
package DataStructures.trees; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its zigzag level order traversal as: [ [3], [20,9], [15,7] ] */ public class ZigZagTraversalBT { //my leetcode solution public List<List<Integer>> zigzagLevelOrder(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) return result; List<Integer> list = new ArrayList<>(); Stack<TreeNode> curr = new Stack<>(); Stack<TreeNode> next = new Stack<>(); curr.add(root); int level = 0; while (!curr.isEmpty()) { TreeNode temp = curr.pop(); list.add(temp.val); if (level % 2 == 0) { if (temp.left != null) next.add(temp.left); if (temp.right != null) next.add(temp.right); } else { if (temp.right != null) next.add(temp.right); if (temp.left != null) next.add(temp.left); } if (curr.isEmpty()) { result.add(list); list = new ArrayList<>(); level++; curr = next; next = new Stack<>(); } } return result; } //better runtime than the above public ArrayList<ArrayList<Integer>> zigzagLevelOrder1(TreeNode a) { if (a == null) return null; ArrayList<ArrayList<Integer>> result = new ArrayList<>(); ArrayList<Integer> list = new ArrayList<>(); Stack<TreeNode> s1 = new Stack<>(); Stack<TreeNode> s2 = new Stack<>(); s1.push(a); while (!s1.isEmpty() || !s2.isEmpty()) { while (!s1.isEmpty()) { TreeNode temp = s1.pop(); list.add(temp.val); if (temp.left != null) { s2.push(temp.left); } if (temp.right != null) { s2.push(temp.right); } } if (list.size() != 0) { result.add(list); list = new ArrayList<>(); } while (!s2.isEmpty()) { TreeNode temp = s2.pop(); list.add(temp.val); if (temp.right != null) { s1.push(temp.right); } if (temp.left != null) { s1.push(temp.left); } } if (list.size() != 0) { result.add(list); list = new ArrayList<>(); } } return result; } public static List<List<Integer>> zigzagLevelOrderNOW(TreeNode root) { List<List<Integer>> result = new ArrayList<>(); if (root == null) return result; List<Integer> list = new ArrayList<>(); Stack<TreeNode> st = new Stack<>(); Stack<TreeNode> next = new Stack<>(); st.push(root); boolean traverseLeft = true; while (!st.isEmpty()) { TreeNode temp = st.pop(); list.add(temp.val); if (traverseLeft) { if (temp.left != null) { next.add(temp.left); } if(temp.right != null) { next.add(temp.right); } } else { if(temp.right != null) { next.add(temp.right); } if (temp.left != null) { next.add(temp.left); } } if (st.isEmpty()) { result.add(list); list = new ArrayList<>(); traverseLeft = !traverseLeft; st = next; next = new Stack<>(); } } return result; } public static void main(String a[]){ ZigZagTraversalBT zig = new ZigZagTraversalBT(); TreeNode root = new TreeNode(5, new TreeNode(4, new TreeNode(2, new TreeNode(1, null, null), new TreeNode(3, null, null)), null), new TreeNode(7, new TreeNode(6, null, null), new TreeNode(11, new TreeNode(8, null, null), new TreeNode(12, null, null)))); //zig.zigzagLevelOrder(root); zigzagLevelOrderNOW(root); } }
package com.channing.snailhouse.config; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.jdbc.DataSourceBuilder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Primary; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; import java.beans.ConstructorProperties; @Configuration @MapperScan(basePackages = {"com.channing.snailhouse.model"}, sqlSessionTemplateRef = "snailhouseSqlSessionTemplate") public class SnailhouseSourceConfig { @Bean(name = "snailhouseSource") @ConfigurationProperties(prefix = "datasource") @Primary public DataSource getSnailhouseSource() { return DataSourceBuilder.create().build(); } @Bean(name = "snailhouseSqlSessionFactory") @Primary public SqlSessionFactory adsSqlSessionFactory(@Qualifier("snailhouseSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); return factoryBean.getObject(); } @Bean(name="snailhouseSqlSessionTemplate") @Primary public SqlSessionTemplate adsSqlSessionTemplate(@Qualifier("snailhouseSqlSessionFactory") SqlSessionFactory factory){ return new SqlSessionTemplate(factory); } @Bean(name = "snailhouseJdbcTemplate") @Primary public JdbcTemplate gateWayJdbcTemplate(@Qualifier("snailhouseSource") DataSource dataSource) { return new JdbcTemplate(dataSource); } }
package com.cqut.dao; import java.util.List; import java.util.Map; import org.apache.ibatis.annotations.Param; import com.cqut.dto.LimitShowExtraDTO; import com.cqut.dto.PetrolDTO; import com.cqut.dto.PetrolRecordDTO; import com.cqut.dto.UserProfitDTO; public interface RefuelingCardMapper { List<Map<String, Object>> getRefuelingCard(); List<Map<String, Object>> getUseWay(); Map<String, Object> getBalance(String userId); void updateUserBalance(UserProfitDTO userprofitdto); List<Map<String, Object>> judgeCardLeaveNum(@Param("money")Integer money); void lockCard(String pereolId); void unlockcard(String petrolId); void addCardBuyRecord(PetrolRecordDTO petrolRecorddto); void addPetrolCard(PetrolDTO petroldto); List<Map<String, Object>> judgeIsBuiedCardOrNot( PetrolRecordDTO petrolRecorddto); Map<String, Object> getOneDayCardRecord(PetrolRecordDTO petrolrecorddto); Map<String, Object> judgeIsHaveDriverCardOrNot(String userId); void passDriverCard( @Param("userId") String userId, @Param("path") String path); List<Map<String, Object>> getPetrolList( @Param("status") String status, @Param("startTime") String startTime, @Param("endTime") String endTime, @Param("curPage") int curPage, @Param("startIndex") int startIndex, @Param("endIndex") int endIndex); void updatePetrolCard(PetrolDTO petroldto); int deleteOverdue(); List<Map<String, Object>> getRefuelingCardById(String pereolId); }