text
stringlengths
10
2.72M
package com.willpower.dialog; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.view.WindowManager; import com.willpower.lib.JBasicDialog; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onResume() { super.onResume(); JBasicDialog.create(MainActivity.this).width(0.85f) .height(WindowManager.LayoutParams.WRAP_CONTENT) .content("setContentView(R.layout.activity_main);") .show(); } }
package lab.s6; public abstract class Phone { abstract void insertPhone(String name , String phone); abstract void removePhone(String name); abstract void updatePhone(String name , String newPhone); abstract void searchPhone(String name); abstract void sort(); }
package com.sanskaar.shalini.mentalmaths; import android.content.Intent; import android.os.CountDownTimer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; public class MainActivity extends AppCompatActivity { Button startButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startButton=(Button) findViewById(R.id.startButton); startButton.setEnabled(false); startButton.setAlpha((float) 0.5); //Banner Ad AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder().build(); mAdView.loadAd(adRequest); //Interstitial Ad final InterstitialAd interstitialAd=new InterstitialAd(getApplicationContext()); interstitialAd.setAdUnitId("******************************"); interstitialAd.loadAd(adRequest); interstitialAd.setAdListener(new AdListener(){ @Override public void onAdClosed() { super.onAdClosed(); startButton.setEnabled(true); startButton.setAlpha((float) 1); startButton.setText("Play"); } @Override public void onAdFailedToLoad(int i) { super.onAdFailedToLoad(i); } @Override public void onAdLeftApplication() { super.onAdLeftApplication(); } @Override public void onAdOpened() { super.onAdOpened(); } @Override public void onAdLoaded() { if(!startButton.isEnabled()) { interstitialAd.show(); } super.onAdLoaded(); } @Override public void onAdClicked() { super.onAdClicked(); } @Override public void onAdImpression() { super.onAdImpression(); } }); //In case no ad comes new CountDownTimer(5000, 1000) { public void onTick(long millisUntilFinished) { startButton.setText("Play in "+(millisUntilFinished/1000)+"s"); } public void onFinish() { startButton.setText("Play"); startButton.setEnabled(true); startButton.setAlpha((float) 1); } }.start(); } public void startGame(View view) { Intent i =new Intent(MainActivity.this,Quiz.class); startActivity(i); } }
package com.maspain.snake.game; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.JButton; import javax.swing.SwingConstants; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class Result extends JFrame { private static final long serialVersionUID = 1L; private JPanel contentPane; private JLabel lblScore; private JLabel lblHighScore; private JButton btnNewGame; private JButton btnResetHighScore; private int score; private String speed; private String time; private Record record; public Result(int score, Record record, String speed, String time) { this.score = score; this.speed = speed; this.time = time; this.record = record; createWindow(); setBehaviors(); } public void createWindow() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 300, 412); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblSnake = new JLabel("Snake"); lblSnake.setBounds(5, 6, 289, 16); lblSnake.setHorizontalAlignment(SwingConstants.CENTER); contentPane.add(lblSnake); JLabel lblAuthor = new JLabel("Mark Spain (2013)"); lblAuthor.setBounds(5, 24, 289, 16); lblAuthor.setHorizontalAlignment(SwingConstants.CENTER); contentPane.add(lblAuthor); String scoreText = (record.newHighScore()) ? "New High Score: " + score + "!" : "Score: " + score; lblScore = new JLabel(scoreText); lblScore.setFont(new Font("Lucida Grande", Font.PLAIN, 24)); lblScore.setBounds(5, 52, 289, 44); lblScore.setHorizontalAlignment(SwingConstants.CENTER); contentPane.add(lblScore); btnNewGame = new JButton("New Game"); btnNewGame.setBounds(5, 284, 289, 44); contentPane.add(btnNewGame); JLabel lblTime = new JLabel("Time: " + time); lblTime.setHorizontalAlignment(SwingConstants.CENTER); lblTime.setFont(new Font("Lucida Grande", Font.PLAIN, 24)); lblTime.setBounds(5, 228, 289, 44); contentPane.add(lblTime); JLabel lblSpeed = new JLabel("Speed: " + speed); lblSpeed.setHorizontalAlignment(SwingConstants.CENTER); lblSpeed.setFont(new Font("Lucida Grande", Font.PLAIN, 24)); lblSpeed.setBounds(5, 164, 289, 52); contentPane.add(lblSpeed); btnResetHighScore = new JButton("Reset High Score"); btnResetHighScore.setBounds(5, 342, 289, 44); contentPane.add(btnResetHighScore); lblHighScore = new JLabel("High Score: " + record.getHighScore()); lblHighScore.setHorizontalAlignment(SwingConstants.CENTER); lblHighScore.setFont(new Font("Lucida Grande", Font.PLAIN, 24)); lblHighScore.setBounds(5, 108, 289, 44); contentPane.add(lblHighScore); setLocationRelativeTo(null); setVisible(true); } public void setBehaviors() { btnNewGame.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dispose(); new StartWindow(); } }); btnNewGame.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { dispose(); new StartWindow(); } } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} }); btnResetHighScore.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { record.resetHighScore(); lblHighScore.setText("High Score: 0"); } }); } }
package com.bluesky.admin.api.modules.sys.vo; import lombok.Data; /** * @author Lijinchun * @Package com.bluesky.admin.api.modules.sys.vo * @date 2019/7/30 23:00 */ @Data public class AdminRoleVO { }
package logger; import es.utils.mapper.Mapper; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Slf4j public class Logs { private static final String LOG_PATTERN = "{} log message"; @Test public void testLogs() { log.trace(LOG_PATTERN,"Trace"); log.debug(LOG_PATTERN,"Debug"); log.info( LOG_PATTERN,"Info"); log.warn( LOG_PATTERN,"Warning"); log.error(LOG_PATTERN,"Error"); } }
package utils; public enum TARIFF_TYPE { ALL, FIXED, VARIABLE; }
package Dto; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; public class Main { public static void main(String[] args) { // Step st1 = new Step("Alexey", "12:23:21", 10, 3); // GsonBuilder builder = new GsonBuilder(); // builder.setPrettyPrinting(); // // Gson gson = builder.create(); // String jsonString = gson.toJson(st1); // String formatJsonString= jsonString.replace("\n"," "); // System.out.println("FormatJsonString : "+ formatJsonString); // // Step step2= new Gson().fromJson(formatJsonString,Step.class); // System.out.println(step2); // // System.out.println(jsonString); char a='1',b='2',c='3'; StringBuffer str1= new StringBuffer(); str1.append(a); str1.append(b); str1.append(c); System.out.println(str1.toString()); } }
package com.tencent.mm.plugin.appbrand.wxawidget.console; import android.view.View; import android.view.View.OnClickListener; class ControlBoardPanel$5 implements OnClickListener { final /* synthetic */ ControlBoardPanel gQL; ControlBoardPanel$5(ControlBoardPanel controlBoardPanel) { this.gQL = controlBoardPanel; } public final void onClick(View view) { ControlBoardPanel controlBoardPanel = this.gQL; if (controlBoardPanel.gQK) { controlBoardPanel.gQK = false; controlBoardPanel.gQI.removeViewImmediate(controlBoardPanel); d.b(controlBoardPanel.fxO); if (controlBoardPanel.gQB != null) { controlBoardPanel.gQB.a(controlBoardPanel, false); } } } }
/** * Created by Ankit on 1/17/2017. */ public class Gyroscope { private float pitch; private float roll; private float yaw; public Gyroscope(float pitch, float roll, float yaw) { this.pitch = pitch; this.roll = roll; this.yaw = yaw; } public Gyroscope updateGyro(String inputFile) { String[] gyroscope = inputFile.split(","); this.pitch = Float.valueOf(gyroscope[0]); this.roll = Float.valueOf(gyroscope[1]); this.yaw = Float.valueOf(gyroscope[2]); return this; } }
package iiitb.timesheet.service; import iiitb.timesheet.model.ProjectReport; import iiitb.timesheet.model.Report; import iiitb.timesheet.model.Timesheet; import iiitb.timesheet.util.DB; import java.sql.Connection; import java.sql.ResultSet; import java.util.ArrayList; public class ReportService { public ArrayList<Report> getReports(){ ArrayList<Report> reports=new ArrayList<Report>(); Connection con; ResultSet rs; String query; try { con=DB.getConnection(); /*query="select project_num,task_name,emp_id,work_date"+ ",no_of_hours from timesheet t,approval a where "+ "t.timesheet_id=a.timesheet_id and a.status='pending' ";*/ query="select t.work_date,t.emp_id,a.manager_id,a.status"+ " from timesheet t,approval a where "+ "t.timesheet_id=a.timesheet_id"; rs=DB.readFromDB(query, con); System.out.println("sssssss report"+query); while(rs.next()){ Report report=new Report(); report.setWork_date(rs.getString("work_date")); report.setEmp_name(getEmpName(rs.getString("emp_id"))); report.setApprover(getEmpName(rs.getString("manager_id"))); report.setStatus(rs.getString("status")); reports.add(report); } }catch (Exception e) { // TODO: handle exception } return reports; } public String getEmpName(String emp_id){ String name=""; Connection con; ResultSet rs; String query; try { con=DB.getConnection(); query="select firstname,lastname from employee where emp_id="+"'"+emp_id+"'"; rs=DB.readFromDB(query, con); System.out.println("Get emp name query : "+query); while(rs.next()){ //System.out.println("-- > > > "+rs.getString("project_name")); name=rs.getString("firstname")+" "+rs.getString("lastname"); } }catch (Exception e) { // TODO: handle exception } return name; } public ArrayList<ProjectReport> getProjectReport(int client_id){ ArrayList<ProjectReport> pReport=new ArrayList<ProjectReport>(); Connection con; ResultSet rs; String query; try { con=DB.getConnection(); /*query="select project_num,task_name,emp_id,work_date"+ ",no_of_hours from timesheet t,approval a where "+ "t.timesheet_id=a.timesheet_id and a.status='pending' ";*/ query="select p.project_num,p.project_name,p.description,p.startdate,p.enddate,e.firstname,e.lastname "+ " from project p, employee e,assignment a where p.pid=a.pid and e.emp_id=a.emp_id and p.client_id="+"'"+client_id+"';"; rs=DB.readFromDB(query, con); System.out.println("sssssss report "+query); while(rs.next()){ ProjectReport report=new ProjectReport(); report.setProject_num(rs.getInt("project_num")); System.out.println(rs.getInt("project_num")); report.setProject_name(rs.getString("project_name")); report.setDescription(rs.getString("description")); report.setStartdate(rs.getString("startdate")); report.setEnddate(rs.getString("enddate")); report.setFirstname(rs.getString("firstname")); report.setLastname(rs.getString("lastname")); pReport.add(report); } }catch (Exception e) { // TODO: handle exception } return pReport; } public ArrayList<ProjectReport> getProjectReport1(){ ArrayList<ProjectReport> pReport=new ArrayList<ProjectReport>(); Connection con; ResultSet rs; String query; try { con=DB.getConnection(); /*query="select project_num,task_name,emp_id,work_date"+ ",no_of_hours from timesheet t,approval a where "+ "t.timesheet_id=a.timesheet_id and a.status='pending' ";*/ query="select p.project_num,p.project_name,p.description,p.startdate,p.enddate,e.firstname,e.lastname "+ " from project p, employee e,assignment a where p.pid=a.pid and e.emp_id=a.emp_id "; rs=DB.readFromDB(query, con); System.out.println("sssssss report "+query); while(rs.next()){ ProjectReport report=new ProjectReport(); report.setProject_num(rs.getInt("project_num")); System.out.println(rs.getInt("project_num")); report.setProject_name(rs.getString("project_name")); report.setDescription(rs.getString("description")); report.setStartdate(rs.getString("startdate")); report.setEnddate(rs.getString("enddate")); report.setFirstname(rs.getString("firstname")); report.setLastname(rs.getString("lastname")); pReport.add(report); } }catch (Exception e) { // TODO: handle exception } return pReport; } }
package Management.HumanResources; import Management.HumanResources.Manager.TransportManager; import Presentation.Protocol.IOManager; import Storage.TransportationCan; /** * 运输部门 * * @author 吴英豪 * @since 2021/10/24 09:52 */ public class TransportDepartment extends BaseDepartment { private TransportDepartment() { this.type = DepartmentType.Transport; this.transportManager = new TransportManager(); IOManager.getInstance().print( "新建了一个运输部门", "新建了一個運輸部門", "A new transport department has been created" ); } /** * 运输部门单例模式 */ public static TransportDepartment getInstance() { if (instance == null) { instance = new TransportDepartment(); } return instance; } /** * 运输部门运输罐头 * */ public void transportCans(TransportationCan transportationCan) { IOManager.getInstance().print( "运输部正在准备运输罐头......", "運輸部正在準備運輸罐頭......", "The transportDepartment is preparing to transport the cans......" ); this.transportManager.transport(transportationCan); } // 运输部经理 private final TransportManager transportManager; //采购部门实体 static private TransportDepartment instance; }
package pixel.bus.gui.dialog; import pixel.bus.dao.DaoFactory; import pixel.bus.dao.IPassengerDao; import pixel.bus.gui.renderer.CustomCellRenderer; import pixel.bus.model.Passenger; import pixel.bus.model.gui.PassengerTableModel; import javax.swing.*; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import java.awt.event.*; import java.util.ArrayList; import java.util.List; public class ActionLogDialog extends JDialog { private JPanel contentPane; private JButton buttonRefresh; private JButton buttonClose; private JTable tableAllPassengers; private IPassengerDao passengerDao = DaoFactory.getInstance(IPassengerDao.class); private List<Passenger> passengerList = passengerDao.getAll(); private PassengerTableModel pmodel = new PassengerTableModel(passengerList); public ActionLogDialog() { setContentPane(contentPane); setModal(true); getRootPane().setDefaultButton(buttonRefresh); tableAllPassengers.setModel(pmodel); List<RowSorter.SortKey> sortKeys = new ArrayList<>(25); sortKeys.add(new RowSorter.SortKey(0, SortOrder.DESCENDING)); TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(pmodel); sorter.setSortKeys(sortKeys); tableAllPassengers.setRowSorter(sorter); // tableAllPassengers.setDefaultRenderer(Object.class, new CustomCellRenderer()); tableAllPassengers.setDefaultRenderer(Integer.class, new CustomCellRenderer()); buttonRefresh.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onRefresh(); } }); buttonClose.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { onClose(); } }); // call onClose() when cross is clicked setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { onClose(); } }); // call onClose() on ESCAPE contentPane.registerKeyboardAction(new ActionListener() { public void actionPerformed(ActionEvent e) { onClose(); } }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); } private void onRefresh() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { passengerList.removeAll(passengerList); passengerList.addAll(passengerDao.getAll()); pmodel.fireTableDataChanged(); } }); } private void onClose() { dispose(); } public static void main(String[] args) { ActionLogDialog dialog = new ActionLogDialog(); dialog.pack(); dialog.setVisible(true); System.exit(0); } }
package com.tencent.mm.k; import android.util.SparseArray; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.zero.b.a; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.bl; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.aa; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import org.json.JSONException; import org.json.JSONObject; public final class c { public static final String dgQ = (aa.duN + "configlist/"); public SparseArray<d> dgP = new SparseArray(); public static String fU(int i) { return dgQ + "config_" + i + ".xml"; } public final boolean d(File file, File file2) { Throwable e; boolean z = false; if (!file.exists()) { return false; } if (file.isDirectory()) { if (!file2.exists()) { file2.mkdir(); } File[] listFiles = file.listFiles(); int i = 0; while (true) { boolean z2 = z; if (i >= listFiles.length) { return z2; } File file3 = listFiles[i]; z = d(file3, new File(file2.getPath(), file3.getName())); if (z) { file.delete(); } i++; } } else { InputStream fileInputStream; OutputStream fileOutputStream; try { fileInputStream = new FileInputStream(file); try { fileOutputStream = new FileOutputStream(file2); try { byte[] bArr = new byte[1024]; while (true) { int read = fileInputStream.read(bArr); if (read == -1) { break; } fileOutputStream.write(bArr, 0, read); } fileOutputStream.flush(); file.delete(); try { fileInputStream.close(); } catch (Throwable e2) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e2)); } try { fileOutputStream.close(); } catch (Throwable e22) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e22)); } return true; } catch (Exception e3) { e22 = e3; try { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e22)); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e222) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e222)); } } if (fileOutputStream != null) { return false; } try { fileOutputStream.close(); return false; } catch (Throwable e2222) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e2222)); return false; } } catch (Throwable th) { e2222 = th; if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e4) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e4)); } } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (Throwable e5) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e5)); } } throw e2222; } } } catch (Exception e6) { e2222 = e6; fileOutputStream = null; x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e2222)); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e22222) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e22222)); } } if (fileOutputStream != null) { return false; } try { fileOutputStream.close(); return false; } catch (Throwable e222222) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e222222)); return false; } } catch (Throwable th2) { e222222 = th2; fileOutputStream = null; if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e42) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e42)); } } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (Throwable e52) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e52)); } } throw e222222; } } catch (Exception e7) { e222222 = e7; fileOutputStream = null; fileInputStream = null; x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e222222)); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e2222222) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e2222222)); } } if (fileOutputStream != null) { return false; } try { fileOutputStream.close(); return false; } catch (Throwable e22222222) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e22222222)); return false; } } catch (Throwable th3) { e22222222 = th3; fileOutputStream = null; fileInputStream = null; if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e422) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e422)); } } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (Throwable e522) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e522)); } } throw e22222222; } } } public final void init() { for (int load : d.dgR) { load(load); } } public final void p(int i, String str) { d dVar = new d(i); dVar.dgT = bl.z(str, "ConfigList"); if (dVar.dgT.containsKey(".ConfigList.$version")) { dVar.version = Integer.valueOf((String) dVar.dgT.get(".ConfigList.$version")).intValue(); } int i2 = 0; while (true) { String str2 = ".ConfigList.Config" + (i2 == 0 ? "" : Integer.valueOf(i2)); if (dVar.dgT.get(str2 + ".$name") != null) { String str3 = (String) dVar.dgT.get(str2 + ".$name"); if (!str3.equalsIgnoreCase("JDWebViewMenu")) { int i3 = 0; while (true) { String str4 = str2 + ".Item" + (i3 == 0 ? "" : Integer.valueOf(i3)); String str5 = str2 + ".Item" + (i3 == 0 ? "" : Integer.valueOf(i3)) + ".$key"; String str6 = str2 + ".Item" + (i3 == 0 ? "" : Integer.valueOf(i3)) + ".$lang"; if (!dVar.dgT.containsKey(str4)) { break; } String str7 = (String) dVar.dgT.get(str5); str4 = (String) dVar.dgT.get(str4); str5 = (String) dVar.dgT.get(str6); x.d("MicroMsg.ConfigListInfo", "itemKey " + str7 + " itemValue " + str4 + " itemLang " + str5); if (str5 == null || d.fk(str5)) { if (!dVar.dgS.containsKey(str3)) { dVar.dgS.put(str3, new HashMap()); } ((HashMap) dVar.dgS.get(str3)).put(str7, str4); } i3++; } } i2++; } else { this.dgP.put(Integer.valueOf(i).intValue(), dVar); return; } } } public final String G(String str, String str2) { d AE = AE(); if (AE != null && AE.dgS.containsKey(str)) { return (String) ((HashMap) AE.dgS.get(str)).get(str2); } return null; } public final d AE() { if (this.dgP.get(1) == null) { load(1); } return (d) this.dgP.get(1); } private void load(int i) { Throwable e; InputStream fileInputStream; try { File file = new File(fU(i)); if (file.exists()) { fileInputStream = new FileInputStream(file); try { Reader inputStreamReader = new InputStreamReader(fileInputStream, "utf-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); StringBuffer stringBuffer = new StringBuffer(); while (true) { String readLine = bufferedReader.readLine(); if (readLine == null) { break; } stringBuffer.append(readLine); } p(i, stringBuffer.toString()); inputStreamReader.close(); bufferedReader.close(); } catch (Exception e2) { e = e2; try { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e)); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e3) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e3)); } } } catch (Throwable th) { e3 = th; if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e4) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e4)); } } throw e3; } } } fileInputStream = null; if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e32) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e32)); } } } catch (Exception e5) { e32 = e5; fileInputStream = null; x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e32)); if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e322) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e322)); } } } catch (Throwable th2) { e322 = th2; fileInputStream = null; if (fileInputStream != null) { try { fileInputStream.close(); } catch (Throwable e42) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e42)); } } throw e322; } } public static int AF() { int i; String value = ((a) g.l(a.class)).AT().getValue("VoiceVOIPSwitch"); x.d("MicroMsg.ConfigListDecoder", "voip is " + value); try { i = bi.getInt(value, 0); } catch (Throwable e) { x.e("MicroMsg.ConfigListDecoder", "exception:%s", bi.i(e)); i = 0; } x.d("MicroMsg.ConfigListDecoder", "showVoiceVoipEntrance is " + i); return i; } public final boolean AG() { boolean z = true; if (bi.getInt(G("WebViewConfig", "disableWePkg"), 0) != 1) { z = false; } x.d("MicroMsg.ConfigListDecoder", "disableWePkg : " + z); return z; } public final String AH() { x.d("MicroMsg.ConfigListDecoder", "get check url for free wifi : %s", G("FreeWiFiConfig", "CheckURL")); return G("FreeWiFiConfig", "CheckURL"); } public final boolean AI() { boolean z = true; if (bi.getInt(G("ShowConfig", "showRecvTmpMsgBtn"), 0) != 1) { z = false; } x.d("MicroMsg.ConfigListDecoder", "isShowRecvTmpMsgBtn : " + z); return z; } public final List<String> AJ() { List<String> list = null; String G = G("IBeacon", "Content"); if (!bi.oW(G)) { list = new ArrayList(); try { Iterator keys = new JSONObject(G.replace(",}", "}")).keys(); while (keys.hasNext()) { Object next = keys.next(); if (next != null) { list.add(next.toString()); } } } catch (JSONException e) { x.e("MicroMsg.ConfigListDecoder", "[oneliang] json parse exception: " + e.getMessage()); } } return list; } public final String AK() { return G("MailApp", "MailAppRedirectUrAndroid"); } public final String getMailAppEnterUlAndroid() { return G("MailApp", "MailAppEnterMailAppUrlAndroid"); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.backend.stratosphere.executionengine.pactLayer.expressionOperators; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.stratosphere.executionengine.pactLayer.Result; import org.apache.pig.backend.stratosphere.executionengine.pactLayer.SOStatus; import org.apache.pig.backend.stratosphere.executionengine.pactLayer.plans.PactPlanVisitor; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.impl.plan.NodeIdGenerator; import org.apache.pig.impl.plan.OperatorKey; import org.apache.pig.impl.plan.VisitorException; public class POBinCond extends ExpressionOperator { private static final long serialVersionUID = 1L; ExpressionOperator cond; ExpressionOperator lhs; ExpressionOperator rhs; private transient List<ExpressionOperator> child; public POBinCond(OperatorKey k) { super(k); } public POBinCond(OperatorKey k, int rp) { super(k, rp); } public POBinCond(OperatorKey k, int rp, ExpressionOperator cond, ExpressionOperator lhs, ExpressionOperator rhs) { super(k, rp); this.cond = cond; this.lhs = lhs; this.rhs = rhs; } public Result genericGetNext(Object obj, byte dataType) throws ExecException { List<ExpressionOperator> list = new ArrayList<ExpressionOperator>(); list.add(cond); Result r = accumChild(list, dummyBool); if (r != null) { if (r.returnStatus != SOStatus.STATUS_BATCH_OK) { return r; } list.clear(); list.add(lhs); list.add(rhs); r = accumChild(list, obj, dataType); return r; } Result res = cond.getNext(dummyBool); if (res.result==null || res.returnStatus != SOStatus.STATUS_OK) { return res; } Result result = ((Boolean)res.result) == true ? lhs.getNext(obj, dataType) : rhs.getNext(obj, dataType); illustratorMarkup(null, result.result, ((Boolean)res.result) ? 0 : 1); return result; } @Override public Result getNext(Boolean b) throws ExecException { Result r = accumChild(null, b); if (r != null) { return r; } Result res = cond.getNext(b); if (res.result==null || res.returnStatus != SOStatus.STATUS_OK) { return res; } return ((Boolean)res.result) == true ? lhs.getNext(b) : rhs.getNext(b); } @Override public Result getNext(DataBag db) throws ExecException { return genericGetNext(db, DataType.BAG); } @Override public Result getNext(DataByteArray ba) throws ExecException { return genericGetNext(ba, DataType.BYTEARRAY); } @Override public Result getNext(Double d) throws ExecException { return genericGetNext(d, DataType.DOUBLE); } @Override public Result getNext(Float f) throws ExecException { return genericGetNext(f, DataType.FLOAT); } @Override public Result getNext(Integer i) throws ExecException { return genericGetNext(i, DataType.INTEGER); } @Override public Result getNext(Long l) throws ExecException { return genericGetNext(l, DataType.LONG); } @Override public Result getNext(Map m) throws ExecException { return genericGetNext(m, DataType.MAP); } @Override public Result getNext(String s) throws ExecException { return genericGetNext(s, DataType.CHARARRAY); } @Override public Result getNext(Tuple t) throws ExecException { return genericGetNext(t, DataType.TUPLE); } @Override public void visit(PactPlanVisitor v) throws VisitorException { v.visitBinCond(this); } @Override public String name() { return "POBinCond" + "[" + DataType.findTypeName(resultType) + "]" +" - " + mKey.toString(); } @Override public void attachInput(Tuple t) { cond.attachInput(t); lhs.attachInput(t); rhs.attachInput(t); } public void setCond(ExpressionOperator condOp) { this.cond = condOp; } public void setRhs(ExpressionOperator rhs) { this.rhs = rhs; } public void setLhs(ExpressionOperator lhs) { this.lhs = lhs; } /** * Get condition */ public ExpressionOperator getCond() { return this.cond; } /** * Get right expression */ public ExpressionOperator getRhs() { return this.rhs; } /** * Get left expression */ public ExpressionOperator getLhs() { return this.lhs; } @Override public boolean supportsMultipleInputs() { return true; } @Override public POBinCond clone() throws CloneNotSupportedException { POBinCond clone = new POBinCond(new OperatorKey(mKey.scope, NodeIdGenerator.getGenerator().getNextNodeId(mKey.scope))); clone.cloneHelper(this); clone.cond = cond.clone(); clone.lhs = lhs.clone(); clone.rhs = rhs.clone(); return clone; } /** * Get child expressions of this expression */ @Override public List<ExpressionOperator> getChildExpressions() { if (child == null) { child = new ArrayList<ExpressionOperator>(); child.add(cond); child.add(lhs); child.add(rhs); } return child; } @Override public Tuple illustratorMarkup(Object in, Object out, int eqClassIndex) { if(illustrator != null) { } return null; } }
package com.iiit.db; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Vector; public class HashUnion_bk { int M; int numRecords; String table1; String table2; int n; int pKey; public HashUnion_bk(int m, int numRecords, String table1, String table2, int n) { super(); M = m; this.numRecords = numRecords; this.table1 = table1; this.table2 = table2; this.n = n; pKey=0; } public void union() { performHash(table1); performHash(table2); performUnion(); deleteAllOutputFiles(); } private void performUnion() { // TODO Auto-generated method stub int hashSize=1000; int maxSize = (numRecords*M)/hashSize; HashMap<Integer, String> outFileMap = new HashMap<>(); int i,hashBucket; Vector<Vector<String>> hashMap = new Vector<>(hashSize); for( i = 0;i<hashSize;i++) { hashMap.add(new Vector<>()); } createFile(Constants.OUTPUT); Vector<String> output = new Vector<>(); int cnt=0; try{ for(i=0;i<M-1;i++) { //Read table1 i'th file, Read table2 i'th file,perform hash BufferedReader buff = new BufferedReader(new FileReader(table1+i)); String line; while((line = buff.readLine())!=null) { String tokens[] = line.split(","); int index=Integer.parseInt(tokens[pKey]); hashBucket = index%(hashSize); if(hashMap.get(hashBucket).size()>=1) { int j; for(j=0;j<hashMap.get(hashBucket).size();j++) { if(line.compareTo(hashMap.get(hashBucket).get(j))==0) { // System.out.println("Found same"); // cnt++; break; } } if(j==hashMap.get(hashBucket).size()) //not duplicate { if(outFileMap.containsKey(hashBucket)) { if(!checkForRecord(outFileMap.get(hashBucket),line)) { hashMap.get(hashBucket).add(line); output.add(line); cnt++; } }else { hashMap.get(hashBucket).add(line); output.add(line); cnt++; } } if(hashMap.get(hashBucket).size()==maxSize) { if(outFileMap.containsKey(hashBucket)) { writeToFile(outFileMap.get(hashBucket),hashMap.get(hashBucket)); }else { outFileMap.put(hashBucket,Constants.OUTPUT+hashBucket); writeToFile(outFileMap.get(hashBucket),hashMap.get(hashBucket)); } } }else { hashMap.get(hashBucket).add(line); output.add(line); cnt++; } if(output.size()==numRecords) { writeToFile(Constants.OUTPUT,output); output.removeAllElements(); } } buff.close(); buff = new BufferedReader(new FileReader(table2+i)); while((line = buff.readLine())!=null) { String tokens[] = line.split(","); int index=Integer.parseInt(tokens[pKey]); hashBucket = index%(hashSize); if(hashMap.get(hashBucket).size()>=1) { int j; for(j=0;j<hashMap.get(hashBucket).size();j++) { if(line.compareTo(hashMap.get(hashBucket).get(j))==0) { // System.out.println("Found same"); // cnt++; break; } } if(j==hashMap.get(hashBucket).size()) //not duplicate { if(outFileMap.containsKey(hashBucket)) { if(!checkForRecord(outFileMap.get(hashBucket),line)) { hashMap.get(hashBucket).add(line); output.add(line); cnt++; } }else { hashMap.get(hashBucket).add(line); output.add(line); cnt++; } } if(hashMap.get(hashBucket).size()==maxSize) { if(outFileMap.containsKey(hashBucket)) { writeToFile(outFileMap.get(hashBucket),hashMap.get(hashBucket)); }else { outFileMap.put(hashBucket,Constants.OUTPUT+hashBucket); writeToFile(outFileMap.get(hashBucket),hashMap.get(hashBucket)); } } }else { hashMap.get(hashBucket).add(line); output.add(line); cnt++; } if(output.size()==numRecords) { writeToFile(Constants.OUTPUT,output); output.removeAllElements(); } } buff.close(); } System.out.println("Same count "+cnt); writeToFile(Constants.OUTPUT,output); for(String fileName :outFileMap.values()) { // boolean success = (new File(fileName)).delete(); } }catch(IOException e) { e.printStackTrace(); } } void performHash(String fileName) { int i,hashBucket; Vector<Vector<String>> hashMap = new Vector<>(M-1); for( i = 0;i<M-1;i++) { createFile(fileName+i); hashMap.add(new Vector<>()); } try { BufferedReader buff = new BufferedReader(new FileReader(fileName)); String line; while((line = buff.readLine())!=null) { String tokens[] = line.split(","); int index=Integer.parseInt(tokens[pKey]); hashBucket = index%(M-1); // System.out.println("Hash Bucket : "+hashBucket+" Value: "+index); hashMap.get(hashBucket).add(line); if(hashMap.get(hashBucket).size()==numRecords) { writeToFile(fileName+hashBucket,hashMap.get(hashBucket)); hashMap.get(hashBucket).removeAllElements(); } } buff.close(); for( i = 0;i<M-1;i++) { writeToFile(fileName+i,hashMap.get(i)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void createFile(String fileName) { PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(fileName)); } catch (IOException e) { // TODO Auto-generated catch block Driver.myExit("File not found"); } pw.close(); } public void writeToFile(String fileName,Vector<String> tuples) { PrintWriter pw; try { pw = new PrintWriter(new FileWriter(fileName,true)); for(String tuple:tuples) { //System.out.println(tuple); pw.write(tuple); pw.write("\n"); } pw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public boolean checkForRecord(String fileName,String record) { try { BufferedReader buff1 = new BufferedReader(new FileReader(fileName)); String line; while((line = buff1.readLine())!=null) { if(record.compareTo(line)==0) { return true; } } buff1.close(); }catch(IOException e) { e.printStackTrace(); } return false; } public void deleteAllOutputFiles() { for(int i=0;i<M-1;i++) { boolean success = (new File(table1+i)).delete(); if (success) { } success = (new File(table2+i)).delete(); } } }
/* * 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 gui; import glbank.database.ConnectionProvider; import java.util.Arrays; /** * * @author Martin */ public class LoginForm extends javax.swing.JFrame { /** * Creates new form LoginForm */ public LoginForm() { initComponents(); errorMessage.setVisible(false); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); txtLogin = new javax.swing.JTextField(); txtPassword = new javax.swing.JPasswordField(); btnLogin = new javax.swing.JButton(); errorMessage = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); jLabel1.setFont(new java.awt.Font("Dialog", 1, 48)); // NOI18N jLabel1.setText("GL Bank"); jLabel2.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N jLabel2.setText("Login :"); jLabel3.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N jLabel3.setText("Password :"); txtLogin.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtLogin.setToolTipText(""); txtPassword.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N btnLogin.setBackground(new java.awt.Color(153, 153, 153)); btnLogin.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N btnLogin.setForeground(new java.awt.Color(0, 0, 0)); btnLogin.setText("Login"); btnLogin.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnLoginActionPerformed(evt); } }); errorMessage.setForeground(new java.awt.Color(255, 51, 51)); errorMessage.setText("Incorrect Login or Password"); 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.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(114, 114, 114) .addComponent(jLabel1)) .addGroup(layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING)) .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtPassword, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtLogin, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(errorMessage)))) .addGap(29, 29, 29) .addComponent(btnLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(21, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jLabel1) .addGap(30, 30, 30) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(btnLogin)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE) .addComponent(errorMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(36, 36, 36)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed String login = txtLogin.getText(); char[] password = txtPassword.getPassword(); String passwordString = new String(password); if(!login.equals("") && passwordString.length() >= 3){ ConnectionProvider conn = new ConnectionProvider(); if(conn.isEmployeePasswordValid(login, passwordString)){ errorMessage.setVisible(false); conn.logEmployeeAccess(conn.getEmployeeId(login)); MainForm mainForm = new MainForm(conn.getEmployeeId(login)); mainForm.setLocationRelativeTo(null); mainForm.setVisible(true); this.setVisible(false); } else{ errorMessage.setVisible(true); } } else{ errorMessage.setVisible(true); } }//GEN-LAST:event_btnLoginActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnLogin; private javax.swing.JLabel errorMessage; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JTextField txtLogin; private javax.swing.JPasswordField txtPassword; // End of variables declaration//GEN-END:variables }
package com.billing.app.dto; import com.billing.app.dao.Bill; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Data; @Data public class BillDetailDTO { @JsonProperty("MOV_TIPDOC") public String movTipdoc; @JsonProperty("MOV_CODIGO") public String movCodigo; @JsonProperty("INV_DESCRI") public String invDescri; @JsonProperty("MOV_CANTID") public String movCantid; @JsonProperty("MOV_UNDMED") public String movUnmed; @JsonProperty("MOV_PRECIO") public String movPrecio; @JsonProperty("MOV_DESCUE") public String movDescue; @JsonProperty("MOV_TOTAL") public String movTotal; @JsonProperty("MOV_ITEM") public String movItem; @JsonProperty("MOV_ITBMS") public String movItbms; @JsonProperty("MOV_OBS") public String movObs; public BillDetailDTO(Bill bill){ this.setMovTipdoc(bill.MOV_TIPDOC); this.setMovCodigo(bill.MOV_CODIGO); this.setInvDescri(bill.INV_DESCRI); this.setMovCantid(bill.MOV_CANTID); this.setMovUnmed(bill.MOV_UNDMED); this.setMovPrecio(bill.MOV_PRECIO); this.setMovDescue(bill.MOV_DESCUE); this.setMovTotal(bill.MOV_TOTAL); this.setMovItem(bill.MOV_ITEM); this.setMovItbms(bill.MOV_ITBMS); this.setMovObs(bill.MOV_OBS); } }
package com.example.vcv.activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import com.example.vcv.R; import com.example.vcv.ui.login.LoginFragment; import com.example.vcv.ui.signin.SigninFragment; import com.example.vcv.utility.QueryDB; import com.example.vcv.utility.User; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GetTokenResult; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.firebase.messaging.FirebaseMessaging; import java.util.Locale; import java.util.concurrent.Executor; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.biometric.BiometricManager; import androidx.biometric.BiometricPrompt; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; /** * @author Mattia Da Campo e Andrea Dalle Fratte * @version 1.0 */ public class LoginActivity extends AppCompatActivity { private int REQUEST_CODE_FORGOT_PASSWORD = 0; private FirebaseAuth mAuth; private FragmentManager fragmentManager; private FragmentTransaction fragmentTransaction; private boolean isLogginin = true; private DatabaseReference mDatabase; private Executor executor; private BiometricPrompt biometricPrompt; private BiometricPrompt.PromptInfo promptInfo; FirebaseUser currentUser; /** * Create login activity * * @param savedInstanceState */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); insertFragmentLogin(); Button button_log_sign = (Button) findViewById(R.id.b_access); button_log_sign.setOnClickListener(new View.OnClickListener() { /** * Handle click of login button * * @param view */ @Override public void onClick(View view) { access(view); } }); //initialize for biometric authentication executor = ContextCompat.getMainExecutor(this); biometricPrompt = new BiometricPrompt(LoginActivity.this, executor, new BiometricPrompt.AuthenticationCallback() { /** * Handle biometric authentication error * * @param errorCode * @param errString */ @Override public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) { super.onAuthenticationError(errorCode, errString); Toast.makeText(getApplicationContext(), getString(R.string.authentication_failed), Toast.LENGTH_SHORT) .show(); Log.e("BIOMETRIC_AUTH", "Biometric authentication error"); logout(); } /** * Handle biometric authentication success * * @param result */ @Override public void onAuthenticationSucceeded( @NonNull BiometricPrompt.AuthenticationResult result) { super.onAuthenticationSucceeded(result); Toast.makeText(getApplicationContext(), getString(R.string.authentication_succes), Toast.LENGTH_SHORT).show(); Log.i("BIOMETRIC_AUTH", "Biometric authentication success"); login(currentUser); } /** * Handle biometric authentication failed */ @Override public void onAuthenticationFailed() { super.onAuthenticationFailed(); Toast.makeText(getApplicationContext(), getString(R.string.authentication_failed), Toast.LENGTH_SHORT) .show(); Log.e("BIOMETRIC_AUTH", "Biometric authentication failed"); } }); promptInfo = new BiometricPrompt.PromptInfo.Builder() .setTitle(getString(R.string.biometric_title)) .setSubtitle(getString(R.string.biometric_subtitle)) .setNegativeButtonText(getString(R.string.biometric_negative)) .setConfirmationRequired(false) .build(); // Initialize Firebase Auth mAuth = FirebaseAuth.getInstance(); // Initialize Firebase DB mDatabase = FirebaseDatabase.getInstance().getReference(); // Check if currentUser is signed in (non-null) currentUser = mAuth.getCurrentUser(); if (currentUser != null) { //check with finger print or face recognition BiometricManager biometricManager = BiometricManager.from(this); if (biometricManager.canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS) { biometricPrompt.authenticate(promptInfo); } } } /** * Handle click on login tab and set background based on the selected item (login) * * @param view */ // Handler public void clickLoginTab(View view) { Button TLogin = findViewById(R.id.b_login); Button TSignin = findViewById(R.id.b_signin); Button BAccess = findViewById(R.id.b_access); TLogin.setBackgroundResource(R.drawable.tab_left_border_selected); TSignin.setBackgroundResource(R.drawable.tab_right_border); insertFragmentLogin(); BAccess.setText(R.string.login); isLogginin = true; } /** * Handle click on login tab and set background based on the selected item (signin) * * @param view */ public void clickSigninTab(View view) { Button TLogin = findViewById(R.id.b_login); Button TSignin = findViewById(R.id.b_signin); Button BAccess = findViewById(R.id.b_access); TLogin.setBackgroundResource(R.drawable.tab_left_border); TSignin.setBackgroundResource(R.drawable.tab_right_border_selected); insertFragmentSignin(); BAccess.setText(R.string.signin); isLogginin = false; } /** * Method to login or signin based on the selected tab * * @param view */ public void access(View view) { if (isLogginin) { login(null); } else { signin(view); } } /** * Start forgot password activity with an intent * * @param view */ public void forgotPassword(View view) { Intent myIntent = new Intent(this, ForgotPasswordActivity.class); startActivityForResult(myIntent, REQUEST_CODE_FORGOT_PASSWORD); } // Utility /** * Method to switch to login fragment */ private void insertFragmentLogin() { LinearLayout containerFragment = findViewById(R.id.container_fragment); containerFragment.setPadding(15, 10, 15, 70); fragmentManager = getSupportFragmentManager(); Fragment fragment = fragmentManager.findFragmentById(R.id.body_login_signin_fragment); if (fragment != null) { fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.remove(fragment); fragmentTransaction.commit(); } Fragment newFragment = new LoginFragment(); fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.body_login_signin_fragment, newFragment); fragmentTransaction.commit(); } /** * Method to switch to signin fragment */ private void insertFragmentSignin() { LinearLayout containerFragment = findViewById(R.id.container_fragment); containerFragment.setPadding(15, 10, 15, 35); fragmentManager = getSupportFragmentManager(); Fragment fragment = fragmentManager.findFragmentById(R.id.body_login_signin_fragment); if (fragment != null) { fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.remove(fragment); fragmentTransaction.commit(); } Fragment newFragment = new SigninFragment(); fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.add(R.id.body_login_signin_fragment, newFragment); fragmentTransaction.commit(); } /** * Method use for login with firebase * * @param user */ private void login(FirebaseUser user) { String email = ""; String password = ""; if (user != null) { try { user.getIdToken(true).addOnCompleteListener(new OnCompleteListener<GetTokenResult>() { /** * Callback triggered when task is completed * * @param task */ @Override public void onComplete(@NonNull Task<GetTokenResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information goToMainActivity(); } } }); } catch (Exception e) { Log.e("AUTHENTICATION", "The authentication error is " + e.getMessage()); } } else { email = ((EditText) findViewById(R.id.et_email)).getText().toString(); password = ((EditText) findViewById(R.id.et_password)).getText().toString(); if (!email.equals("") && !password.equals("")) { mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { /** * Callback triggered when sign in with email and password on firebase is completed * * @param task */ @Override public void onComplete(@NonNull Task<AuthResult> task) { FirebaseUser user = mAuth.getCurrentUser(); if (user != null) { if (task.isSuccessful() && user.isEmailVerified()) { // Download firebase data and insert them in sqlite DatabaseReference dbFirebase = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()); dbFirebase.addListenerForSingleValueEvent(new ValueEventListener() { /** * Handle the snapshot of referenced data. This method is triggered only once * * @param dataSnapshot */ @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { User completeUser = dataSnapshot.getValue(User.class); if (completeUser != null) { Log.i("AUTHENTICATION", "Login in successful"); QueryDB db = new QueryDB(LoginActivity.this); db.insertUserData(completeUser); goToMainActivity(); } } /** * Handle the error occured while retriving data. This method is triggered only once * * @param databaseError */ @Override public void onCancelled(@NonNull DatabaseError databaseError) { Log.e("AUTHENTICATION", databaseError.getMessage()); } }); } else { // If sign goes wrong, display a message to the user Log.e("AUTHENTICATION", "Login failure", task.getException()); Toast.makeText(LoginActivity.this, getString(R.string.authentication_failed), Toast.LENGTH_SHORT).show(); } } else { // If sign goes wrong, display a message to the user Log.e("AUTHENTICATION", "Login failure", task.getException()); Toast.makeText(LoginActivity.this, getString(R.string.authentication_failed), Toast.LENGTH_SHORT).show(); } } }); } else { Log.e("AUTHENTICATION", "Missing email or password"); Toast.makeText(LoginActivity.this, getString(R.string.authentication_failed), Toast.LENGTH_SHORT).show(); } } } /** * Method use for signin user on firebase * * @param view */ private void signin(final View view) { final String name = ((EditText) findViewById(R.id.et_name)).getText().toString(); final String surname = ((EditText) findViewById(R.id.et_surname)).getText().toString(); final String telephone = ((EditText) findViewById(R.id.et_telephone)).getText().toString(); final String email = ((EditText) findViewById(R.id.et_email_signin)).getText().toString(); final String badgeNumber = ((EditText) findViewById(R.id.et_badge_signin)).getText().toString(); String pssw = ((EditText) findViewById(R.id.et_password_signin)).getText().toString(); String psswConfirm = ((EditText) findViewById(R.id.et_confirm_password_signin)).getText().toString(); final User user = new User(name, surname, telephone, badgeNumber, email); if (!name.equals("") && !surname.equals("") && !telephone.equals("") && !email.equals("") && !badgeNumber.equals("") && !pssw.equals("") && pssw.equals(psswConfirm) && !(pssw.length() < 6)) { mAuth.createUserWithEmailAndPassword(email, pssw) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { /** * Callback triggered when the user has been created on firebase * * @param task */ @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information Log.i("REGISTRATION", "Create with success user with email and password"); final FirebaseUser userFirebase = mAuth.getCurrentUser(); if (userFirebase != null) { userFirebase.sendEmailVerification() .addOnCompleteListener(new OnCompleteListener() { /** * Callback triggered when email has been sent * * @param task */ @Override public void onComplete(@NonNull Task task) { if (task.isSuccessful()) { Toast.makeText(LoginActivity.this, getString(R.string.send_email_check) + " " + email, Toast.LENGTH_SHORT).show(); // Initialize Firebase DB mDatabase = FirebaseDatabase.getInstance().getReference(); mDatabase.child("users").child(userFirebase.getUid()).setValue(user) .addOnSuccessListener(new OnSuccessListener<Void>() { /** * Callback triggered when user is inserted with success in firebase users' collection * * @param aVoid */ @Override public void onSuccess(Void aVoid) { Log.i("REGISTRATION", "User added with success to users' collection"); mAuth.signOut(); } }) .addOnFailureListener(new OnFailureListener() { /** * Callback triggered when user can not be inserted in firebase users' collection * * @param e */ @Override public void onFailure(@NonNull Exception e) { Log.e("REGISTRATION", "User can not be inserted in firebase users' collection" + e.getMessage()); mAuth.signOut(); } }); } else { Log.e("REGISTRATION", "Failed to send verification email"); Toast.makeText(LoginActivity.this, getString(R.string.send_email_error), Toast.LENGTH_SHORT).show(); mAuth.signOut(); } clickLoginTab(view); } }); } } else { // If sign in goes wrong, display a message to the userf Log.e("REGISTRATION", "Can not create user with email and password on firebase"); Toast.makeText(LoginActivity.this, getString(R.string.authentication_failed), Toast.LENGTH_SHORT).show(); } } }); } else { Log.e("REGISTRATION", "Some mandatory fields are missing"); Toast.makeText(LoginActivity.this, getString(R.string.please_change_fields), Toast.LENGTH_SHORT).show(); } } /** * Method used for loggin out from firebase and to clear local db */ private void logout() { FirebaseMessaging.getInstance().unsubscribeFromTopic(getLocaleTopic()).addOnSuccessListener(new OnSuccessListener<Void>() { /** * Callback triggered when user has been deleted from the topic, for firebase notification, with success * * @param aVoid */ @Override public void onSuccess(Void aVoid) { Log.i("FIREBASE_NOTIFICATIONS", "User has been removed with success from '" + getLocaleTopic() + "' topic"); } }); mAuth.signOut(); QueryDB db = new QueryDB(LoginActivity.this); db.cleanLogout(); } /** * Method use to change activity and go to the main one */ private void goToMainActivity() { Log.i("GO_MAIN_ACTIVITY", "Go to main activity"); ((EditText) findViewById(R.id.et_email)).setText(""); ((EditText) findViewById(R.id.et_password)).setText(""); Intent myIntent = new Intent(LoginActivity.this, MainActivity.class); startActivity(myIntent); } /** * Method use to get name of topic where register the user for firebase notification * * @return the name of firebase's topic to subscribe user. It depends on the device language to get the notification in the right language */ private String getLocaleTopic() { return "all-" + Locale.getDefault().getLanguage(); } }
package textdecorators.driver; import textdecorators.*; import textdecorators.util.FileDisplayInterface; import textdecorators.util.FileProcessor; import textdecorators.util.InputDetails; import textdecorators.util.Logger; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.InvalidPathException; public class Driver { private static final int REQUIRED_NUMBER_OF_CMDLINE_ARGS = 5; public static void main(String[] args) throws IllegalArgumentException { /* * As the build.xml specifies the arguments as input,output or metrics, in case the * argument value is not given java takes the default value specified in * build.xml. To avoid that, below condition is used */ try { if ((args.length != 5) || (args[0].equals("${input}")) || (args[1].equals("${misspelled}")) || (args[2].equals("${keywords}")) || (args[3].equals("${output}")) || (args[4].equals("${debug}"))) { System.err.printf("Error: Incorrect number of arguments. Program accepts %d arguments.", REQUIRED_NUMBER_OF_CMDLINE_ARGS); System.exit(0); } System.out.println("Let's start Assignment 5.."); System.out.println(); /** * Instantiations to read input files cmd line arguments */ FileProcessor input = new FileProcessor(args[0]); FileProcessor misspelled = new FileProcessor(args[1]); FileProcessor keywords = new FileProcessor(args[2]); int debugValue = Integer.parseInt(args[4]); if(!(debugValue > 0 && debugValue <=4)) { throw new NumberFormatException("Debug value should be between 1 and 4 including"); } Logger.setDebugValue(debugValue); /** * Decorators instantiations */ InputDetails inputD = new InputDetails(input, misspelled, keywords, args[3]); AbstractTextDecorator sentenceDecorator = new SentenceDecorator(null, inputD); AbstractTextDecorator spellCheckDecorator = new SpellCheckDecorator(sentenceDecorator, inputD); AbstractTextDecorator keywordDecorator = new KeywordDecorator(spellCheckDecorator, inputD); AbstractTextDecorator mostFreqWordDecorator = new MostFrequentWordDecorator(keywordDecorator, inputD); inputD.readFile(); mostFreqWordDecorator.processInputDetails(); ((FileDisplayInterface) inputD).writeToFile(); input.close(); misspelled.close(); keywords.close(); inputD.close(); } /** * Exceptions handling */ catch (FileNotFoundException file) { System.err.println("No File found...Exiting"); System.err.println(file.getMessage()); file.printStackTrace(); System.exit(0); } catch (IOException io) { System.err.println("Invalid I/O processed...Exiting"); System.err.println(io.getMessage()); io.printStackTrace(); System.exit(0); } catch(InvalidPathException path) { System.err.println("Invalid path...Exiting"); System.err.println(path.getMessage()); path.printStackTrace(); System.exit(0); } catch(SecurityException security) { System.err.println("Security Exception check...Exiting"); System.err.println(security.getMessage()); security.printStackTrace(); System.exit(0); } catch(NumberFormatException number) { System.err.println("Invalid number detected...Exiting"); System.err.println(number.getMessage()); number.printStackTrace(); System.exit(0); } catch(IllegalArgumentException arg) { System.err.println("Illegal arguments...Exiting"); System.err.println(arg.getMessage()); arg.printStackTrace(); System.exit(0); } catch(NullPointerException nullPtr) { System.err.println("Null pointer exception...Exiting"); System.err.println(nullPtr.getMessage()); nullPtr.printStackTrace(); System.exit(0); } finally { } } }
package com.biz.rbooks.repository; import com.biz.rbooks.domain.MemberDTO; public interface MemberDao { public MemberDTO findById(String m_id); public int insert(MemberDTO memberDTO); }
import java.util.Scanner; /** * Main class */ public class Source { /** * Main method * @param args */ public static void main(String[] args) { // Student code begins Scanner sc = new Scanner(System.in); int arr[] = new int[3]; boolean flag = true; for(int i=0;i<3;i++) { arr[i] = sc.nextInt(); } for(int i=0;i<2;i++) { if(arr[i]<arr[i+1]) { flag = false; } } if(flag) { int a = arr[1]*arr[1]; int b = arr[2]*arr[2]; int sum = a+b; double result = Math.sqrt(sum); if(result == arr[0]) { System.out.println("RIGHT ANGLE"); } else{ System.out.println("NOT RIGHT ANGLE"); } } else{ System.out.println("INVALID_INPUT"); } // Student code ends; } }
package com.smxknife.java2.thread.cyclicbarrier.demo02; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * @author smxknife * 2018-12-25 */ public class MyThread extends Thread { private CyclicBarrier barrier; public MyThread(CyclicBarrier barrier) { this.barrier = barrier; } @Override public void run() { try { barrier.await(); } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } } }
package com.tencent.mm.plugin.webview.ui.tools.fts; import android.graphics.PorterDuff.Mode; import android.view.View; import android.widget.ImageButton; import com.tencent.map.lib.mapstructure.MapRouteSectionWithName; import com.tencent.mm.R; import com.tencent.mm.bp.a; import com.tencent.mm.compatible.util.d; import com.tencent.mm.plugin.sns.i$l; import com.tencent.mm.sdk.platformtools.ad; public class FTSSOSMoreWebViewUI extends BaseSOSWebViewUI { private int qdX; private View qeG; protected final void ant() { super.ant(); this.qeG = findViewById(R.h.webview_keyboard_ll); bXk().czi(); bXk().aQY(); this.mPT.setVisibility(0); bXk().aQW(); this.lAV.setVisibility(8); this.qdX = a.fromDPToPix(this, 48); bXk().setIconRes(com.tencent.mm.au.a.b(getType(), this)); if (aUM() == 24) { this.qeG.setVisibility(4); } findViewById(R.h.root).setOnTouchListener(new 1(this)); if (getIntent() != null && getIntent().getBooleanExtra("ftsneedkeyboard", false)) { this.mController.contentView.postDelayed(new 2(this), 128); } Z(getResources().getColor(R.e.white), true); ImageButton clearBtn = bXk().getClearBtn(); if (clearBtn != null) { clearBtn.getDrawable().setColorFilter(-16777216, Mode.SRC_ATOP); } } protected final int anu() { if (!d.fR(23) || com.tencent.mm.ui.statusbar.d.Af()) { return super.anu(); } return getResources().getColor(R.e.white); } public final void fg(boolean z) { super.fg(z); if (z) { this.qdi.setPadding(0, 0, this.qdi.getPaddingRight(), 0); this.mPT.setVisibility(8); bXk().aQX(); } else { this.qdi.setPadding(this.qdX, 0, this.qdi.getPaddingRight(), 0); this.mPT.setVisibility(0); bXk().aQW(); } bXk().aQY(); } public boolean anx() { bXk().aQY(); this.qeG.setVisibility(0); return super.anx(); } protected final int getLayoutId() { return R.i.sos_more_webview_ui; } protected final void bXg() { finish(); } public String getHint() { int i = -1; if (getType() != 8 || !this.qdz) { switch (getType()) { case 1: i = R.l.search_education_biz_contact; break; case 2: i = R.l.search_education_article; break; case 8: i = R.l.fts_header_timeline; break; case 16: i = R.l.fts_header_poi; break; case i$l.AppCompatTheme_imageButtonStyle /*64*/: i = R.l.app_brand_entrance; break; case MapRouteSectionWithName.kMaxRoadNameLength /*128*/: i = R.l.fts_header_emoji_product; break; case 256: case 384: i = R.l.fts_header_emoji; break; case 512: i = R.l.fts_header_music; break; case 1024: i = R.l.fts_header_novel; break; } } i = R.l.fts_header_timeline_publisher; if (i < 0) { return ad.getContext().getResources().getString(R.l.app_search) + AT(getType()); } return ad.getContext().getResources().getString(R.l.search_detail_page_hint, new Object[]{ad.getContext().getResources().getString(i)}); } protected final void bXh() { super.bXh(); this.qeG.setVisibility(0); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.ftp.parser; import java.util.Calendar; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPFileEntryParser; /** */ public class UnixFTPEntryParserTest extends AbstractFTPParseTest { private static final String[] badsamples = { "zrwxr-xr-x 2 root root 4096 Mar 2 15:13 zxbox", "dxrwr-xr-x 2 root root 4096 Aug 24 2001 zxjdbc", "drwxr-xr-x 2 root root 4096 Jam 4 00:03 zziplib", "drwxr-xr-x 2 root 99 4096 Feb 23 30:01 zzplayer", "drwxr-xr-x 2 root root 4096 Aug 36 2001 zztpp", "-rw-r--r-- 1 14 staff 80284 Aug 22 zxJDBC-1.2.3.tar.gz", "-rw-r--r-- 1 14 staff 119:26 Aug 22 2000 zxJDBC-1.2.3.zip", /* "-rw-r--r-- 1 ftp no group 83853 Jan 22 2001 zxJDBC-1.2.4.tar.gz", */ "-rw-r--r-- 1ftp nogroup 126552 Jan 22 2001 zxJDBC-1.2.4.zip", "-rw-r--r-- 1 root root 190144 2001-04-27 zxJDBC-2.0.1b1.zip", "-rw-r--r-- 1 root root 111325 Apr -7 18:79 zxJDBC-2.0.1b1.tar.gz" }; private static final String[] goodsamples = { "-rw-r--r-- 1 500 500 21 Aug 8 14:14 JB3-TES1.gz", "-rwxr-xr-x 2 root root 4096 Mar 2 15:13 zxbox", "drwxr-xr-x 2 root root 4096 Aug 24 2001 zxjdbc", "drwxr-xr-x 2 root root 4096 Jan 4 00:03 zziplib", "drwxr-xr-x 2 root 99 4096 Feb 23 2001 zzplayer", "drwxr-xr-x 2 root root 4096 Aug 6 2001 zztpp", "drwxr-xr-x 1 usernameftp 512 Jan 29 23:32 prog", "lrw-r--r-- 1 14 14 80284 Aug 22 2000 zxJDBC-1.2.3.tar.gz", "frw-r--r-- 1 14 staff 119926 Aug 22 2000 zxJDBC-1.2.3.zip", "crw-r--r-- 1 ftp nogroup 83853 Jan 22 2001 zxJDBC-1.2.4.tar.gz", "brw-r--r-- 1 ftp nogroup 126552 Jan 22 2001 zxJDBC-1.2.4.zip", "-rw-r--r-- 1 root root 111325 Apr 27 2001 zxJDBC-2.0.1b1.tar.gz", "-rw-r--r-- 1 root root 190144 Apr 27 2001 zxJDBC-2.0.1b1.zip", "-rwxr-xr-x 2 500 500 166 Nov 2 2001 73131-testtes1.afp", "-rw-r--r-- 1 500 500 166 Nov 9 2001 73131-testtes1.AFP", "-rw-r--r-- 1 500 500 166 Nov 12 2001 73131-testtes2.afp", "-rw-r--r-- 1 500 500 166 Nov 12 2001 73131-testtes2.AFP", "-rw-r--r-- 1 500 500 2040000 Aug 5 07:35 testRemoteUPCopyNIX", "-rw-r--r-- 1 500 500 2040000 Aug 5 07:31 testRemoteUPDCopyNIX", "-rw-r--r-- 1 500 500 2040000 Aug 5 07:31 testRemoteUPVCopyNIX", "-rw-r--r-T 1 500 500 0 Mar 25 08:20 testSticky", "-rwxr-xr-t 1 500 500 0 Mar 25 08:21 testStickyExec", "-rwSr-Sr-- 1 500 500 0 Mar 25 08:22 testSuid", "-rwsr-sr-- 1 500 500 0 Mar 25 08:23 testSuidExec", "-rwsr-sr-- 1 500 500 0 Mar 25 0:23 testSuidExec2", "drwxrwx---+ 23 500 500 0 Jan 10 13:09 testACL", "-rw-r--r-- 1 1 3518644 May 25 12:12 std", "lrwxrwxrwx 1 neeme neeme 23 Mar 2 18:06 macros -> ./../../global/macros/.", "-rw-r--r-- 1 ftp group with spaces in it as allowed in cygwin see bug 38634" + " 83853 Jan 22 2001 zxJDBC-1.2.4.tar.gz", // Bug 38634 => NET-16 "crw-r----- 1 root kmem 0, 27 Jan 30 11:42 kmem", // FreeBSD device "crw------- 1 root sys 109,767 Jul 2 2004 pci@1c,600000:devctl", // Solaris device "-rwxrwx--- 1 ftp ftp-admin 816026400 Oct 5 2008 bloplab 7 cd1.img", // NET-294 // https://mail-archives.apache.org/mod_mbox/commons-dev/200408.mbox/%3c4122F3C1.9090402@tanukisoftware.com%3e "-rw-r--r-- 1 1 3518644 May 25 12:12 std", "-rw-rw---- 1 ep1adm sapsys 0 6\u6708 3\u65e5 2003\u5e74 \u8a66\u9a13\u30d5\u30a1\u30a4\u30eb.csv", "-rw-rw---- 1 ep1adm sapsys 0 8\u6708 17\u65e5 20:10 caerrinf", }; public UnixFTPEntryParserTest(final String name) { super(name); } private void checkPermissions(final FTPFile f) { assertTrue("Should have user read permission.", f.hasPermission(FTPFile.USER_ACCESS, FTPFile.READ_PERMISSION)); assertTrue("Should have user write permission.", f.hasPermission(FTPFile.USER_ACCESS, FTPFile.WRITE_PERMISSION)); assertTrue("Should have user execute permission.", f.hasPermission(FTPFile.USER_ACCESS, FTPFile.EXECUTE_PERMISSION)); assertTrue("Should have group read permission.", f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.READ_PERMISSION)); assertFalse("Should NOT have group write permission.", f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.WRITE_PERMISSION)); assertTrue("Should have group execute permission.", f.hasPermission(FTPFile.GROUP_ACCESS, FTPFile.EXECUTE_PERMISSION)); assertTrue("Should have world read permission.", f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.READ_PERMISSION)); assertFalse("Should NOT have world write permission.", f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.WRITE_PERMISSION)); assertTrue("Should have world execute permission.", f.hasPermission(FTPFile.WORLD_ACCESS, FTPFile.EXECUTE_PERMISSION)); } @Override protected void doAdditionalGoodTests(final String test, final FTPFile f) { final String link = f.getLink(); if (null != link) { final int linklen = link.length(); if (linklen > 0) { assertEquals(link, test.substring(test.length() - linklen)); assertEquals(f.getType(), FTPFile.SYMBOLIC_LINK_TYPE); } } final int type = f.getType(); switch (test.charAt(0)) { case 'd': assertEquals("Type of " + test, type, FTPFile.DIRECTORY_TYPE); break; case 'l': assertEquals("Type of " + test, type, FTPFile.SYMBOLIC_LINK_TYPE); break; case 'b': case 'c': assertEquals(0, f.getHardLinkCount()); //$FALL-THROUGH$ TODO this needs to be fixed if a device type is introduced case 'f': case '-': assertEquals("Type of " + test, type, FTPFile.FILE_TYPE); break; default: assertEquals("Type of " + test, type, FTPFile.UNKNOWN_TYPE); } for (int access = FTPFile.USER_ACCESS; access <= FTPFile.WORLD_ACCESS; access++) { for (int perm = FTPFile.READ_PERMISSION; perm <= FTPFile.EXECUTE_PERMISSION; perm++) { final int pos = 3 * access + perm + 1; final char permchar = test.charAt(pos); assertEquals("Permission " + test.substring(1, 10), Boolean.valueOf(f.hasPermission(access, perm)), Boolean.valueOf(permchar != '-' && !Character.isUpperCase(permchar))); } } assertNotNull("Expected to find a timestamp", f.getTimestamp()); // Perhaps check date range (need to ensure all good examples qualify) // assertTrue(test,f.getTimestamp().get(Calendar.YEAR)>=2000); } @Override protected String[] getBadListing() { return badsamples; } @Override protected String[] getGoodListing() { return goodsamples; } @Override protected FTPFileEntryParser getParser() { return new UnixFTPEntryParser(); } public void testCorrectGroupNameParsing() { final FTPFile f = getParser().parseFTPEntry("-rw-r--r-- 1 ftpuser ftpusers 12414535 Mar 17 11:07 test 1999 abc.pdf"); assertNotNull(f); assertEquals(1, f.getHardLinkCount()); assertEquals("ftpuser", f.getUser()); assertEquals("ftpusers", f.getGroup()); assertEquals(12414535, f.getSize()); assertEquals("test 1999 abc.pdf", f.getName()); final Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, Calendar.MARCH); cal.set(Calendar.DAY_OF_MONTH, 17); cal.set(Calendar.HOUR_OF_DAY, 11); cal.set(Calendar.MINUTE, 7); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); assertEquals(f.getTimestamp().get(Calendar.MONTH), cal.get(Calendar.MONTH)); assertEquals(f.getTimestamp().get(Calendar.DAY_OF_MONTH), cal.get(Calendar.DAY_OF_MONTH)); assertEquals(f.getTimestamp().get(Calendar.HOUR_OF_DAY), cal.get(Calendar.HOUR_OF_DAY)); assertEquals(f.getTimestamp().get(Calendar.MINUTE), cal.get(Calendar.MINUTE)); assertEquals(f.getTimestamp().get(Calendar.SECOND), cal.get(Calendar.SECOND)); } @Override public void testDefaultPrecision() { testPrecision("drwxr-xr-x 2 user group 4096 Mar 2 2014 zxbox", CalendarUnit.DAY_OF_MONTH); } public void testFilenamesWithEmbeddedNumbers() { final FTPFile f = getParser().parseFTPEntry("-rw-rw-rw- 1 user group 5840 Mar 19 09:34 123 456 abc.csv"); assertEquals("123 456 abc.csv", f.getName()); assertEquals(5840, f.getSize()); assertEquals("user", f.getUser()); assertEquals("group", f.getGroup()); } public void testGroupNameWithSpaces() { final FTPFile f = getParser().parseFTPEntry("drwx------ 4 maxm Domain Users 512 Oct 2 10:59 .metadata"); assertNotNull(f); assertEquals("maxm", f.getUser()); assertEquals("Domain Users", f.getGroup()); } public void testLeadingSpacesDefault() { // the default has been changed to keep spaces final FTPFile f = getParser().parseFTPEntry("drwxr-xr-x 2 john smith group 4096 Mar 2 15:13 zxbox"); assertNotNull(f); assertEquals(" zxbox", f.getName()); // leading spaces retained } public void testLeadingSpacesNET566() { // check new behavior final FTPFile f = new UnixFTPEntryParser(null, false).parseFTPEntry("drwxr-xr-x 2 john smith group 4096 Mar 2 15:13 zxbox"); assertNotNull(f); assertEquals(" zxbox", f.getName()); // leading spaces retained } public void testNameWIthPunctuation() { final FTPFile f = getParser().parseFTPEntry("drwx------ 4 maxm Domain Users 512 Oct 2 10:59 abc(test)123.pdf"); assertNotNull(f); assertEquals("abc(test)123.pdf", f.getName()); } public void testNET294() { final FTPFile f = getParser().parseFTPEntry("-rwxrwx--- 1 ftp ftp-admin 816026400 Oct 5 2008 bloplab 7 cd1.img"); assertNotNull(f); assertEquals("ftp", f.getUser()); assertEquals("ftp-admin", f.getGroup()); assertEquals(816026400L, f.getSize()); assertNotNull("Timestamp should not be null", f.getTimestamp()); assertEquals(2008, f.getTimestamp().get(Calendar.YEAR)); assertEquals("bloplab 7 cd1.img", f.getName()); } public void testNoSpacesBeforeFileSize() { final FTPFile f = getParser().parseFTPEntry("drwxr-x---+1464 chrism chrism 41472 Feb 25 13:17 20090225"); assertNotNull(f); assertEquals(41472, f.getSize()); assertEquals(f.getType(), FTPFile.DIRECTORY_TYPE); assertEquals("chrism", f.getUser()); assertEquals("chrism", f.getGroup()); assertEquals(1464, f.getHardLinkCount()); } public void testNumericDateFormat() { final String testNumericDF = "-rw-r----- 1 neeme neeme 346 2005-04-08 11:22 services.vsp"; final String testNumericDF2 = "lrwxrwxrwx 1 neeme neeme 23 2005-03-02 18:06 macros -> ./../../global/macros/."; final UnixFTPEntryParser parser = new UnixFTPEntryParser(UnixFTPEntryParser.NUMERIC_DATE_CONFIG); final FTPFile f = parser.parseFTPEntry(testNumericDF); assertNotNull("Failed to parse " + testNumericDF, f); final Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(Calendar.YEAR, 2005); cal.set(Calendar.MONTH, Calendar.APRIL); cal.set(Calendar.DAY_OF_MONTH, 8); cal.set(Calendar.HOUR_OF_DAY, 11); cal.set(Calendar.MINUTE, 22); assertEquals(cal.getTime(), f.getTimestamp().getTime()); final FTPFile f2 = parser.parseFTPEntry(testNumericDF2); assertNotNull("Failed to parse " + testNumericDF2, f2); assertEquals("symbolic link", "./../../global/macros/.", f2.getLink()); } public void testOwnerAndGroupNameWithSpaces() { final FTPFile f = getParser().parseFTPEntry("drwxr-xr-x 2 john smith test group 4096 Mar 2 15:13 zxbox"); assertNotNull(f); assertEquals("john smith", f.getUser()); assertEquals("test group", f.getGroup()); } public void testOwnerNameWithSpaces() { final FTPFile f = getParser().parseFTPEntry("drwxr-xr-x 2 john smith group 4096 Mar 2 15:13 zxbox"); assertNotNull(f); assertEquals("john smith", f.getUser()); } @Override public void testParseFieldsOnDirectory() throws Exception { final FTPFile f = getParser().parseFTPEntry("drwxr-xr-x 2 user group 4096 Mar 2 15:13 zxbox"); assertNotNull("Could not parse entry.", f); assertTrue("Should have been a directory.", f.isDirectory()); checkPermissions(f); assertEquals(2, f.getHardLinkCount()); assertEquals("user", f.getUser()); assertEquals("group", f.getGroup()); assertEquals("zxbox", f.getName()); assertEquals(4096, f.getSize()); final Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, Calendar.MARCH); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); if (f.getTimestamp().getTime().before(cal.getTime())) { cal.add(Calendar.YEAR, -1); } cal.set(Calendar.DAY_OF_MONTH, 2); cal.set(Calendar.HOUR_OF_DAY, 15); cal.set(Calendar.MINUTE, 13); assertEquals(df.format(cal.getTime()), df.format(f.getTimestamp().getTime())); } @Override public void testParseFieldsOnFile() throws Exception { final FTPFile f = getParser().parseFTPEntry("-rwxr-xr-x 2 user my group 500 5000000000 Mar 2 15:13 zxbox"); assertNotNull("Could not parse entry.", f); assertTrue("Should have been a file.", f.isFile()); checkPermissions(f); assertEquals(2, f.getHardLinkCount()); assertEquals("user", f.getUser()); assertEquals("my group 500", f.getGroup()); assertEquals("zxbox", f.getName()); assertEquals(5000000000L, f.getSize()); final Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, Calendar.MARCH); cal.set(Calendar.DAY_OF_MONTH, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); if (f.getTimestamp().getTime().before(cal.getTime())) { cal.add(Calendar.YEAR, -1); } cal.set(Calendar.DAY_OF_MONTH, 2); cal.set(Calendar.HOUR_OF_DAY, 15); cal.set(Calendar.MINUTE, 13); assertEquals(df.format(cal.getTime()), df.format(f.getTimestamp().getTime())); } // https://mail-archives.apache.org/mod_mbox/commons-dev/200408.mbox/%3c4122F3C1.9090402@tanukisoftware.com%3e public void testParseFieldsOnFileJapaneseTime() { final FTPFile f = getParser().parseFTPEntry("-rwxr-xr-x 2 user group 4096 3\u6708 2\u65e5 15:13 zxbox"); assertNotNull("Could not parse entry.", f); assertTrue("Should have been a file.", f.isFile()); checkPermissions(f); assertEquals(2, f.getHardLinkCount()); assertEquals("user", f.getUser()); assertEquals("group", f.getGroup()); assertEquals("zxbox", f.getName()); assertEquals(4096, f.getSize()); assertNotNull("Timestamp not null", f.getTimestamp()); final Calendar cal = Calendar.getInstance(); cal.set(Calendar.MONTH, Calendar.MARCH); cal.set(Calendar.DATE, 1); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); if (f.getTimestamp().getTime().before(cal.getTime())) { cal.add(Calendar.YEAR, -1); } cal.set(Calendar.DATE, 2); cal.set(Calendar.HOUR_OF_DAY, 15); cal.set(Calendar.MINUTE, 13); assertEquals(df.format(cal.getTime()), df.format(f.getTimestamp().getTime())); } // https://mail-archives.apache.org/mod_mbox/commons-dev/200408.mbox/%3c4122F3C1.9090402@tanukisoftware.com%3e public void testParseFieldsOnFileJapaneseYear() { final FTPFile f = getParser().parseFTPEntry("-rwxr-xr-x 2 user group 4096 3\u6708 2\u65e5 2003\u5e74 \u8a66\u9a13\u30d5\u30a1\u30a4\u30eb.csv"); assertNotNull("Could not parse entry.", f); assertTrue("Should have been a file.", f.isFile()); checkPermissions(f); assertEquals(2, f.getHardLinkCount()); assertEquals("user", f.getUser()); assertEquals("group", f.getGroup()); assertEquals("\u8a66\u9a13\u30d5\u30a1\u30a4\u30eb.csv", f.getName()); assertEquals(4096, f.getSize()); assertNotNull("Timestamp not null", f.getTimestamp()); final Calendar cal = Calendar.getInstance(); cal.set(Calendar.YEAR, 2003); cal.set(Calendar.MONTH, Calendar.MARCH); cal.set(Calendar.DATE, 2); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); assertEquals(df.format(cal.getTime()), df.format(f.getTimestamp().getTime())); } @Override public void testRecentPrecision() { testPrecision("drwxr-xr-x 2 user group 4096 Mar 2 15:13 zxbox", CalendarUnit.MINUTE); } public void testTrailingSpaces() { final FTPFile f = getParser().parseFTPEntry("drwxr-xr-x 2 john smith group 4096 Mar 2 15:13 zxbox "); assertNotNull(f); assertEquals("zxbox ", f.getName()); } public void testTrimLeadingSpacesNET566() { // check can trim spaces as before final FTPFile f = new UnixFTPEntryParser(null, true).parseFTPEntry("drwxr-xr-x 2 john smith group 4096 Mar 2 15:13 zxbox"); assertNotNull(f); assertEquals("zxbox", f.getName()); // leading spaces trimmed } }
package com.example.demo.service; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.demo.dao.PublicationRepository; import com.example.demo.entities.Publication; @Service public class PublicationImpl implements IPublicationService { @Autowired PublicationRepository publicationRepository; @Override public Publication addPublication(Publication publication) { publicationRepository.save(publication); return publication; } @Override public void deletePublication(Long id) { publicationRepository.deleteById(id); } @Override public Publication updatePublication(Publication publication) { return publicationRepository.saveAndFlush(publication); } @Override public Publication findPublication(Long id) { return publicationRepository.findById(id).get(); } @Override public List<Publication> findAll() { return publicationRepository.findAll(); } @Override public List<Publication> findByTitreStartingWith(String titre) { return publicationRepository.findByTitreStartingWith(titre); } @Override public List<Publication> findByType(String type) { return publicationRepository.findByType(type); } @Override public List<Publication> findByDate(Date date) { return publicationRepository.findByDate(date); } }
package com.yksoul.pay.cache; import com.yksoul.pay.api.IPaymentStrategy; import com.yksoul.pay.api.IPaymentWay; import com.yksoul.pay.domain.enums.PayErrorCodeEnum; import com.yksoul.pay.exception.EasyPayException; import java.util.Map; import java.util.Objects; import java.util.ServiceLoader; import java.util.concurrent.ConcurrentHashMap; /** * 支付方式缓存 * * @author yk * @version 1.0 * @date 2018-07-11 */ public class PaymentCache { private static final Map<String, Map<Integer, IPaymentStrategy>> PAYMENT_STRATEGY_MAP = new ConcurrentHashMap<>(); public static void initPaymentCache() { // 初始化所有支付方式 PaymentCache.clearAll(); ServiceLoader<IPaymentStrategy> loader = ServiceLoader.load(IPaymentStrategy.class); for (IPaymentStrategy next : loader) { putPayment(next); } if (PaymentCache.getPayment().isEmpty()) { throw new EasyPayException(PayErrorCodeEnum.INIT_PAYMENT_CACHE_FAILED); } } /** * 添加一个 * * @param next */ private static void putPayment(IPaymentStrategy next) { IPaymentWay paymentWay = next.supportsPayment(); String prefix = paymentWay.supportsPaymentPrefix(); if (PAYMENT_STRATEGY_MAP.containsKey(prefix)) { PAYMENT_STRATEGY_MAP.get(prefix).put(paymentWay.getCode(), next); } else { Map<Integer, IPaymentStrategy> map = new ConcurrentHashMap<>(1); map.put(paymentWay.getCode(), next); PAYMENT_STRATEGY_MAP.put(paymentWay.supportsPaymentPrefix(), map); } } /** * 获取所有支付方式集合 * * @return */ public static Map<String, Map<Integer, IPaymentStrategy>> getPayment() { if (PAYMENT_STRATEGY_MAP.isEmpty()) { throw new EasyPayException(PayErrorCodeEnum.PAYMENT_CACHE_IS_EMPTY); } return PAYMENT_STRATEGY_MAP; } public static Map<Integer, IPaymentStrategy> getPaymentByPrefix(String prefix) { Map<Integer, IPaymentStrategy> strategyMap = getPayment().get(prefix); if (strategyMap.isEmpty()) { throw new EasyPayException(PayErrorCodeEnum.PAYMENT_CACHE_PREFIX_IS_EMPTY); } return strategyMap; } public static IPaymentStrategy getPaymentByPrefixAndCode(String prefix, Integer payCode) { IPaymentStrategy strategy = getPaymentByPrefix(prefix).get(payCode); if (Objects.isNull(strategy)) { throw new EasyPayException(PayErrorCodeEnum.PAYMENT_CACHE_CODE_IS_EMPTY); } return strategy; } /** * 清除缓存 */ public static void clearAll() { PAYMENT_STRATEGY_MAP.clear(); } }
package com.hpu.sencondhand.bean; /** * Detail: * on 2019/12/30 */ public class Product { private String owner; private String imgPath; private String title; private String category; private String price; private String description; private String contactDetail; public Product(String owner, String imgPath, String title, String category, String prie,String contactDetail, String detail) { this.owner = owner; this.imgPath = imgPath; this.title = title; this.category = category; this.price = prie; this.contactDetail=contactDetail; this.description = detail; } public Product() { } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner; } public String getImgPath() { return imgPath; } public void setImgPath(String imgPath) { this.imgPath = imgPath; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getPrie() { return price; } public void setPrie(String prie) { this.price = prie; } public String getDetail() { return description; } public void setDetail(String detail) { this.description = detail; } public String getContactDetail() { return contactDetail; } public void setContactDetail(String contactDetail) { this.contactDetail = contactDetail; } }
package com.wipe.zc.journey.ui.adapter; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.easemob.chat.EMMessage; import com.nostra13.universalimageloader.core.ImageLoader; import com.wipe.zc.journey.R; import com.wipe.zc.journey.domain.ChatMessage; import com.wipe.zc.journey.global.MyApplication; import com.wipe.zc.journey.http.AppURL; import com.wipe.zc.journey.lib.CircleImageView; import com.wipe.zc.journey.util.ImageLoaderOption; import com.wipe.zc.journey.util.LogUtil; import com.wipe.zc.journey.util.TimeUtil; import java.util.List; /** * Chat页面Adapter */ public class ChatAdapter extends BaseAdapter { private List<ChatMessage> list; public ChatAdapter(List<ChatMessage> list) { this.list = list; } @Override public int getCount() { return list.size(); } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public int getViewTypeCount() { return 3; } @Override public int getItemViewType(int position) { String receiver = list.get(position).getReceiveAvatar(); if (receiver.equals(MyApplication.getNickname())) { //本人接收 return 1; } else { //本人发送 return 2; } } @Override public View getView(int position, View convertView, ViewGroup viewGroup) { int type = getItemViewType(position); ChatMessage chatMessage = list.get(position); switch (type) { case 1: //接收的消息(左) if (convertView == null) { convertView = View.inflate(MyApplication.getContext(), R.layout .layout_list_chat_left, null); } setLeftHolder(convertView, chatMessage, position); return convertView; case 2: //发送的消息(右) if (convertView == null) { convertView = View.inflate(MyApplication.getContext(), R.layout .layout_list_chat_right, null); } setRightHolder(convertView, chatMessage, position); return convertView; default: LogUtil.i("ChatListView", position + ""); return null; } } /** * 设置左侧Holder * * @param convertView convertView * @param chatMessage chat信息 * @param position 位置 */ public void setLeftHolder(View convertView, ChatMessage chatMessage, int position) { LeftViewHolder holder_left = LeftViewHolder.getHolder(convertView); //头像加载 ImageLoader.getInstance().displayImage(AppURL.getimage + "?nickname=" + chatMessage.getSendAvatar(), holder_left .civ_chat_left_icon, ImageLoaderOption.list_options); //消息内容 if (chatMessage.getType() == EMMessage.Type.TXT) { //隐藏其他内容 holder_left.iv_chat_left_image.setVisibility(View.INVISIBLE); holder_left.tv_chat_left_content.setVisibility(View.VISIBLE); holder_left.tv_chat_left_content.setText(chatMessage.getContent()); } //图片内容 else if (chatMessage.getType() == EMMessage.Type.IMAGE) { //隐藏其他内容 holder_left.tv_chat_left_content.setVisibility(View.INVISIBLE); holder_left.iv_chat_left_image.setVisibility(View.VISIBLE); ImageLoader.getInstance().displayImage(chatMessage.getContent(), holder_left .iv_chat_left_image, ImageLoaderOption.list_options); } //时间显示 if (position != 0) { showLeftTime(chatMessage, holder_left, position); } else { holder_left.tv_chat_left_time.setVisibility(View.VISIBLE); if (position == list.size()) { holder_left.tv_chat_left_time.setText(TimeUtil.getFromatTime(chatMessage.getChatTime (), false)); } else { holder_left.tv_chat_left_time.setText(TimeUtil.getFromatDate(chatMessage .getChatTime(), false) + " " + TimeUtil.getFromatTime(chatMessage .getChatTime(), false)); } } } /** * 左侧时间显示 * * @param chatMessage chat信息 * @param holder_left 左侧ViewHolder * @param position 位置 */ public void showLeftTime(ChatMessage chatMessage, LeftViewHolder holder_left, int position) { String time; switch (TimeUtil.compareCalendar10(chatMessage.getChatTime(), list.get(position - 1).getChatTime())) { case -1: time = TimeUtil.getFromatDate(chatMessage.getChatTime(), true); holder_left.tv_chat_left_time.setText(time); break; case 0: time = TimeUtil.getFromatDate(chatMessage.getChatTime(), false); holder_left.tv_chat_left_time.setText(time); break; case 1: time = TimeUtil.getFromatTime(chatMessage.getChatTime(), false); holder_left.tv_chat_left_time.setText(time); break; case 2: holder_left.tv_chat_left_time.setVisibility(View.GONE); break; } } /** * 设置右侧Hodler * * @param convertView convertView * @param chatMessage chat信息 * @param position 位置 */ public void setRightHolder(View convertView, ChatMessage chatMessage, int position) { RightViewHolder holder_right = RightViewHolder.getHolder(convertView); //头像加载 ImageLoader.getInstance().displayImage(AppURL.getimage + "?nickname=" + chatMessage.getSendAvatar(), holder_right .civ_chat_right_icon, ImageLoaderOption.list_options); //消息内容 if (chatMessage.getType() == EMMessage.Type.TXT) { //隐藏其他内容 holder_right.iv_chat_right_image.setVisibility(View.INVISIBLE); holder_right.tv_chat_right_content.setVisibility(View.VISIBLE); holder_right.tv_chat_right_content.setText(chatMessage.getContent()); } //图片内容 else if (chatMessage.getType() == EMMessage.Type.IMAGE) { //隐藏其他内容 holder_right.tv_chat_right_content.setVisibility(View.INVISIBLE); holder_right.iv_chat_right_image.setVisibility(View.VISIBLE); ImageLoader.getInstance().displayImage(chatMessage.getContent(), holder_right.iv_chat_right_image, ImageLoaderOption.list_options); } //时间显示 if (position != 0) { showRightTime(chatMessage, holder_right, position); } else { holder_right.tv_chat_right_time.setVisibility(View.VISIBLE); holder_right.tv_chat_right_time.setText(TimeUtil.getFromatDate(chatMessage .getChatTime(), false) + " " + TimeUtil.getFromatTime(chatMessage .getChatTime(), false)); } } /** * 显示右侧时间 * * @param chatMessage chat信息 * @param holder_right 右侧ViewHolder * @param position 位置 */ public void showRightTime(ChatMessage chatMessage, RightViewHolder holder_right, int position) { String time ; switch (TimeUtil.compareCalendar10(chatMessage.getChatTime(), list.get(position - 1).getChatTime())) { case -1: //年月日 time = TimeUtil.getFromatDate(chatMessage.getChatTime(), true); holder_right.tv_chat_right_time.setText(time); break; case 0: //月日 time = TimeUtil.getFromatDate(chatMessage.getChatTime(), false); holder_right.tv_chat_right_time.setText(time); break; case 1: time = TimeUtil.getFromatTime(chatMessage.getChatTime(), false); holder_right.tv_chat_right_time.setText(time); break; case 2: holder_right.tv_chat_right_time.setVisibility(View.GONE); break; } } static class LeftViewHolder { public TextView tv_chat_left_time; public CircleImageView civ_chat_left_icon; public TextView tv_chat_left_content; public ImageView iv_chat_left_image; public LeftViewHolder(View convertView) { tv_chat_left_time = (TextView) convertView.findViewById(R.id.tv_chat_left_time); civ_chat_left_icon = (CircleImageView) convertView.findViewById(R.id .civ_chat_left_icon); tv_chat_left_content = (TextView) convertView.findViewById(R.id.tv_chat_left_content); iv_chat_left_image = (ImageView) convertView.findViewById(R.id.iv_chat_left_image); } public static LeftViewHolder getHolder(View convertView) { LeftViewHolder holder = (LeftViewHolder) convertView.getTag(); if (holder == null) { holder = new LeftViewHolder(convertView); convertView.setTag(holder); } return holder; } } static class RightViewHolder { public TextView tv_chat_right_time; public TextView tv_chat_right_content; public CircleImageView civ_chat_right_icon; public ImageView iv_chat_right_image; public RightViewHolder(View convertView) { tv_chat_right_time = (TextView) convertView.findViewById(R.id.tv_chat_right_time); tv_chat_right_content = (TextView) convertView.findViewById(R.id.tv_chat_right_content); civ_chat_right_icon = (CircleImageView) convertView.findViewById(R.id .civ_chat_right_icon); iv_chat_right_image = (ImageView) convertView.findViewById(R.id.iv_chat_right_image); } public static RightViewHolder getHolder(View convertView) { RightViewHolder holder = (RightViewHolder) convertView.getTag(); if (holder == null) { holder = new RightViewHolder(convertView); convertView.setTag(holder); } return holder; } } }
/* Document : SME_Lending Created on : August 21, 2015, 11:56:42 AM Author : Anuj Verma */ package com.spring.service; //import javax.servlet.ServletContext; //import org.springframework.web.context.ServletContextAware; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.spring.dao.CustomerCareDao; import com.spring.domain.ChequeInventory; @Service public class CustomerCareServiceImpl implements CustomerCareService { @Autowired CustomerCareDao customerCareDao; @Override public List<ChequeInventory> getChequeReport(int buyerId) { return customerCareDao.getChequeReport(buyerId); } }
/* * Copyright (c) 2016. Universidad Politecnica de Madrid * * @author Badenes Olmedo, Carlos <cbadenes@fi.upm.es> * */ package org.librairy.modeler.lda.eventbus; import org.librairy.boot.model.Event; import org.librairy.boot.model.modules.BindingKey; import org.librairy.boot.model.modules.EventBus; import org.librairy.boot.model.modules.EventBusSubscriber; import org.librairy.boot.model.modules.RoutingKey; import org.librairy.modeler.lda.helper.ModelingHelper; import org.librairy.modeler.lda.services.ParallelExecutorService; import org.librairy.modeler.lda.tasks.LDADistributionsTask; import org.librairy.modeler.lda.tasks.LDASubdomainShapingTask; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; /** * Created by cbadenes on 11/01/16. */ @Component public class LdaSubdomainShapesCreatedEventHandler implements EventBusSubscriber { private static final Logger LOG = LoggerFactory.getLogger(LdaSubdomainShapesCreatedEventHandler.class); @Autowired protected EventBus eventBus; @Autowired ModelingHelper helper; private ParallelExecutorService executor; @PostConstruct public void init(){ BindingKey bindingKey = BindingKey.of(RoutingKey.of(LDASubdomainShapingTask.ROUTING_KEY_ID), "modeler.lda.subdomains" + ".shapes.created"); LOG.info("Trying to register as subscriber of '" + bindingKey + "' events .."); eventBus.subscribe(this,bindingKey ); LOG.info("registered successfully"); executor = new ParallelExecutorService(); } @Override public void handle(Event event) { LOG.info("lda subdomain shapes created event received: " + event); try{ String domainUri = event.to(String.class); executor.execute(domainUri, 1000, new LDADistributionsTask(domainUri, helper)); } catch (Exception e){ // TODO Notify to event-bus when source has not been added LOG.error("Error creating subdomains shapes in domain: " + event, e); } } }
package com.java.service.bean.master; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.validation.constraints.Size; @Entity @Table(name = "master_server_config") public class ServerConfigDO implements java.io.Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", unique = true, nullable = false) private Integer id; @Column(name = "from_mail_id") private String sFromMailId; @Column(name = "from_mail_password") private String sFromMailPassword; @Column(name = "smtp_host_name") private String sSMTPHostName; @Column(name = "smtp_host_no") private String sSMTPHostNumber; @Column(name = "smtp_auth") private String sSMTPAuth; @Column(name = "smtp_debug") private String sSMTPDebug; @Column(name = "smtp_startls") private String sSMTPStartTls; @Column(name = "smtp_mechanisms") private String sSMTPMechanisms; @Column(name = "timeout") private Integer iTimeout; @Column(name = "maintain_start_date") @Temporal(TemporalType.TIMESTAMP) private Date dMaintainStartDate; @Column(name = "maintain_end_date") @Temporal(TemporalType.TIMESTAMP) private Date dMaintainEndDate; @Column(name = "questions_timeout") private Integer iQuestions_Timeout; @Column(name = "total_survey_time") private Integer iTotalSurveyTime; @Column(name = "created_by") @Size(max=100) private String sCreatedBy; @Column(name = "created_date") @Temporal(TemporalType.TIMESTAMP) private Date dCreatedDate; @Column(name = "updated_by") @Size(max=100) private String sUpdatedBy; @Column(name = "updated_date") @Temporal(TemporalType.TIMESTAMP) private Date dUpdatedDate; public ServerConfigDO() {} public ServerConfigDO(Integer id) { this.id = id; } /** * @return the id */ public Integer getId() { return id; } /** * @param id the id to set */ public void setId(Integer id) { this.id = id; } /** * @return the sFromMailId */ public String getsFromMailId() { return sFromMailId; } /** * @param sFromMailId the sFromMailId to set */ public void setsFromMailId(String sFromMailId) { this.sFromMailId = sFromMailId; } /** * @return the sFromMailPassword */ public String getsFromMailPassword() { return sFromMailPassword; } /** * @param sFromMailPassword the sFromMailPassword to set */ public void setsFromMailPassword(String sFromMailPassword) { this.sFromMailPassword = sFromMailPassword; } /** * @return the sSMTPHostName */ public String getsSMTPHostName() { return sSMTPHostName; } /** * @param sSMTPHostName the sSMTPHostName to set */ public void setsSMTPHostName(String sSMTPHostName) { this.sSMTPHostName = sSMTPHostName; } /** * @return the sSMTPHostNumber */ public String getsSMTPHostNumber() { return sSMTPHostNumber; } /** * @param sSMTPHostNumber the sSMTPHostNumber to set */ public void setsSMTPHostNumber(String sSMTPHostNumber) { this.sSMTPHostNumber = sSMTPHostNumber; } /** * @return the sSMTPAuth */ public String getsSMTPAuth() { return sSMTPAuth; } /** * @param sSMTPAuth the sSMTPAuth to set */ public void setsSMTPAuth(String sSMTPAuth) { this.sSMTPAuth = sSMTPAuth; } /** * @return the sSMTPDebug */ public String getsSMTPDebug() { return sSMTPDebug; } /** * @param sSMTPDebug the sSMTPDebug to set */ public void setsSMTPDebug(String sSMTPDebug) { this.sSMTPDebug = sSMTPDebug; } /** * @return the sSMTPStartTls */ public String getsSMTPStartTls() { return sSMTPStartTls; } /** * @param sSMTPStartTls the sSMTPStartTls to set */ public void setsSMTPStartTls(String sSMTPStartTls) { this.sSMTPStartTls = sSMTPStartTls; } /** * @return the sSMTPMechanisms */ public String getsSMTPMechanisms() { return sSMTPMechanisms; } /** * @param sSMTPMechanisms the sSMTPMechanisms to set */ public void setsSMTPMechanisms(String sSMTPMechanisms) { this.sSMTPMechanisms = sSMTPMechanisms; } /** * @return the iTimeout */ public Integer getiTimeout() { return iTimeout; } /** * @param iTimeout the iTimeout to set */ public void setiTimeout(Integer iTimeout) { this.iTimeout = iTimeout; } /** * @return the dMaintainStartDate */ public Date getdMaintainStartDate() { return dMaintainStartDate; } /** * @param dMaintainStartDate the dMaintainStartDate to set */ public void setdMaintainStartDate(Date dMaintainStartDate) { this.dMaintainStartDate = dMaintainStartDate; } /** * @return the dMaintainEndDate */ public Date getdMaintainEndDate() { return dMaintainEndDate; } /** * @param dMaintainEndDate the dMaintainEndDate to set */ public void setdMaintainEndDate(Date dMaintainEndDate) { this.dMaintainEndDate = dMaintainEndDate; } /** * @return the iQuestions_Timeout */ public Integer getiQuestions_Timeout() { return iQuestions_Timeout; } /** * @param iQuestions_Timeout the iQuestions_Timeout to set */ public void setiQuestions_Timeout(Integer iQuestions_Timeout) { this.iQuestions_Timeout = iQuestions_Timeout; } /** * @return the iTotalSurveyTime */ public Integer getiTotalSurveyTime() { return iTotalSurveyTime; } /** * @param iTotalSurveyTime the iTotalSurveyTime to set */ public void setiTotalSurveyTime(Integer iTotalSurveyTime) { this.iTotalSurveyTime = iTotalSurveyTime; } /** * @return the sCreatedBy */ public String getsCreatedBy() { return sCreatedBy; } /** * @param sCreatedBy the sCreatedBy to set */ public void setsCreatedBy(String sCreatedBy) { this.sCreatedBy = sCreatedBy; } /** * @return the dCreatedDate */ public Date getdCreatedDate() { return dCreatedDate; } /** * @param dCreatedDate the dCreatedDate to set */ public void setdCreatedDate(Date dCreatedDate) { this.dCreatedDate = dCreatedDate; } /** * @return the sUpdatedBy */ public String getsUpdatedBy() { return sUpdatedBy; } /** * @param sUpdatedBy the sUpdatedBy to set */ public void setsUpdatedBy(String sUpdatedBy) { this.sUpdatedBy = sUpdatedBy; } /** * @return the dUpdatedDate */ public Date getdUpdatedDate() { return dUpdatedDate; } /** * @param dUpdatedDate the dUpdatedDate to set */ public void setdUpdatedDate(Date dUpdatedDate) { this.dUpdatedDate = dUpdatedDate; } }
package com.tencent.mm.plugin.collect.reward.a; import com.tencent.mm.ab.b; import com.tencent.mm.ab.b.a; import com.tencent.mm.ab.e; import com.tencent.mm.network.q; import com.tencent.mm.plugin.report.service.h; import com.tencent.mm.protocal.c.mn; import com.tencent.mm.protocal.c.mo; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.aa; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public final class g extends a { private final String TAG = "MicroMsg.NetSceneQrRewardSetCode"; private b diG; private e diJ; public mo hVd; public g(LinkedList<Integer> linkedList, String str, boolean z, boolean z2) { a aVar = new a(); aVar.dIG = new mn(); aVar.dIH = new mo(); aVar.dIF = 1562; aVar.uri = "/cgi-bin/mmpay-bin/setrewardqrcode"; aVar.dII = 0; aVar.dIJ = 0; this.diG = aVar.KT(); mn mnVar = (mn) this.diG.dID.dIL; mnVar.rqc = linkedList; mnVar.desc = str; mnVar.rqC = z; mnVar.rqD = z2; x.i("MicroMsg.NetSceneQrRewardSetCode", "desc: %s, flag: %s, default: %s", new Object[]{str, Boolean.valueOf(z), Boolean.valueOf(z2)}); } public final int getType() { return 1562; } public final int a(com.tencent.mm.network.e eVar, e eVar2) { this.diJ = eVar2; return a(eVar, this.diG, this); } public final void b(int i, int i2, String str, q qVar) { x.i("MicroMsg.NetSceneQrRewardSetCode", "errType: %s, errCode: %s, errMsg: %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str}); this.hVd = (mo) ((b) qVar).dIE.dIL; x.i("MicroMsg.NetSceneQrRewardSetCode", "retcode: %s, retmsg: %s", new Object[]{Integer.valueOf(this.hVd.hUm), this.hVd.hUn}); if (!(this.hUU || this.hVd.hUm == 0)) { this.hUV = true; } if (!this.hUU && !this.hUV) { com.tencent.mm.kernel.g.Ei().DT().a(aa.a.sYN, Integer.valueOf(this.hVd.rqf)); com.tencent.mm.kernel.g.Ei().DT().a(aa.a.sYO, Integer.valueOf(this.hVd.rqb)); com.tencent.mm.kernel.g.Ei().DT().a(aa.a.sYQ, this.hVd.desc); com.tencent.mm.kernel.g.Ei().DT().a(aa.a.sYW, this.hVd.mwO); List arrayList = new ArrayList(); Iterator it = this.hVd.rqc.iterator(); while (it.hasNext()) { arrayList.add(String.valueOf(((Integer) it.next()).intValue())); } com.tencent.mm.kernel.g.Ei().DT().a(aa.a.sYT, bi.c(arrayList, ",")); h.mEJ.a(724, 5, 1, false); } else if (this.hUU) { h.mEJ.a(724, 7, 1, false); } else { h.mEJ.a(724, 6, 1, false); } if (this.diJ != null) { this.diJ.a(i, i2, str, this); } } }
import java.io.*; import java.util.*; /** * 149. Max Points on a Line */ class Solution { // 最大公约数 private int getGcd(int a, int b) { return b == 0 ? a : getGcd(b, a % b); } public int maxPoints(int[][] points) { if (points.length <= 2) return points.length; int max = 0; for (int i = 0; i < points.length; i++) { int duplicate = 1, m = 0; Map<String, Integer> map = new HashMap<>(); for (int j = i + 1; j < points.length; j++) { int y = points[j][1] - points[i][1]; int x = points[j][0] - points[i][0]; if (x == 0 && y == 0) { // 重复的点也在线上 duplicate++; continue; } int gcd = getGcd(x, y); y /= gcd; x /= gcd; String key = y + "/" + x; // 分数做键,避免精度问题 int pointNum = map.getOrDefault(key, 0) + 1; map.put(key, pointNum); m = Math.max(m, pointNum); } max = Math.max(max, m + duplicate); } return max; } public static void main(String[] args) throws IOException { Solution s = new Solution(); File f = new File("input.txt"); Scanner scan = new Scanner(f); while (scan.hasNextLine()) { String in = scan.nextLine(); String[] pairs = new String[0]; if (in.length() > 2) pairs = in.substring(2, in.length() - 2).split("\\],\\["); int[][] points = new int[pairs.length][2]; for (int i = 0; i < points.length; i++) { String[] nums = pairs[i].split(","); points[i][0] = Integer.parseInt(nums[0]); points[i][1] = Integer.parseInt(nums[1]); } System.out.println(s.maxPoints(points)); } scan.close(); } }
package Lab06.Zad1; public class Main { public static void main(String[] args) { FactoryPostOffice postoffice = new FactoryPostOffice(); FactoryPostman postman = new FactoryPostman(); } }
package com.wb.cloud.load; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractLoadBalancerRule; import com.netflix.loadbalancer.ILoadBalancer; import com.netflix.loadbalancer.Server; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; /** * @ClassName : MyRuleBalancer * @Author : 王斌 * @Date : 2020-11-23 15:54 * @Description 自己实现负载均衡 * @Version */ public class MyRuleBalancer extends AbstractLoadBalancerRule { private AtomicInteger atomicInteger = new AtomicInteger(0); /** * 通过自旋来更新 * @return */ public final int getAndIncrement(){ int current; int next; do{ current = atomicInteger.get(); next = current >= Integer.MAX_VALUE ? 0 : current + 1; }while (!atomicInteger.compareAndSet(current,next)); System.out.println ( "******* 第几次访问,次数next: " + next ); return next; } @Override public void initWithNiwsConfig(IClientConfig iClientConfig) { } @Override public Server choose(Object key) { return choose(getLoadBalancer(), key); } private Server choose(ILoadBalancer lb, Object key) { if (lb == null) { return null; } List<Server> allList = lb.getAllServers(); return allList.get(getAndIncrement() % allList.size()); } }
package me.mani.clhub.listener; import me.mani.clcore.Core; import me.mani.clhub.Hub; import me.mani.clhub.portal.Portal; import org.bukkit.Material; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; public class BlockBreakListener implements Listener { @EventHandler public void onBlockBreak(BlockBreakEvent event) { if (event.getPlayer().getItemInHand() != null) { if (event.getPlayer().getItemInHand().getType() == Material.STICK && event.getBlock().getType() == Portal.PORTAL_MATERIAL) { Hub.getInstance().getPortals().add(Portal.createPortal(event.getBlock().getLocation(), "build")); // TODO: Add some server input event.getPlayer().sendMessage(Core.getLocaleManager().translate("portal-create")); if (Hub.getInstance().getDataManager().savePortals(Hub.getInstance().getPortals()) == 0) event.getPlayer().sendMessage(Core.getLocaleManager().translate("portal-save-error")); event.setCancelled(true); } } } }
package com.allisonmcentire.buildingtradesandroid; /** * Created by allisonmcentire on 12/3/17. */ import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.squareup.picasso.Picasso; public class UserViewHolder extends RecyclerView.ViewHolder { public TextView nameView; public TextView emailView; public TextView phoneView; public ImageView picture; public UserViewHolder(View itemView) { super(itemView); nameView = itemView.findViewById(R.id.field_full_name_view); emailView = itemView.findViewById(R.id.email_link); phoneView = itemView.findViewById(R.id.phone_link); picture = itemView.findViewById(R.id.profile_picture); } public void bindToPost(User user, View.OnClickListener starClickListener) { nameView.setText(user.field_full_name); emailView.setText(user.name); phoneView.setText(user.field_phone_number); Picasso.with(picture.getContext()).load(user.field_profile_picture).into(picture); } }
package org.icabanas.jee.api.integracion.dao.consulta; public enum OperadorWhereEnum { OP_EQUAL("="), OP_AND("AND"), OP_OR("OR"), OP_IS_NULL("IS NULL"), OP_IS_NOT_NULL("IS NOT NULL"), OP_NOT_EQUAL("!="), OP_GREATER_THAN(">"), OP_LIKE("LIKE"); private String value; private OperadorWhereEnum(String value) { this.value = value; } public String getOperador() { return value; } }
package fontRendering; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import fontMeshCreator.FontType; import fontMeshCreator.GUIText; import fontMeshCreator.TextMeshData; import renderEngine.Loader; public class TextMaster { private static Loader loader; private static Map<FontType, List<GUIText>> texts = new HashMap<FontType, List<GUIText>>(); private static FontRenderer renderer; public static void init( Loader theLoader ) { renderer = new FontRenderer(); loader = theLoader; } public static void render() { renderer.render( texts ); } public static void loadText( GUIText text ) { FontType font = text.getFont(); TextMeshData data = font.loadText( text ); int vao = loader.loadToVAO( data.getVertexPositions(), data.getTextureCoords() ); text.setMeshInfo( vao, data.getVertexCount() ); List<GUIText> textBatch = texts.get( font ); if( textBatch == null ) { textBatch = new ArrayList<GUIText>(); texts.put( font, textBatch ); } textBatch.add( text ); } public static void removeText( GUIText text ) { List<GUIText> textBatch = texts.get( text.getFont() ); textBatch.remove( text ); if( textBatch.isEmpty() ) { texts.remove( text.getFont() ); } } public static void cleanUp() { renderer.cleanUp(); } }
package app.ReaderApp; import android.animation.Animator; import android.annotation.SuppressLint; import android.app.Service; import android.content.Intent; import android.graphics.PixelFormat; import android.media.AudioManager; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.support.design.widget.FloatingActionButton; import android.support.v7.widget.PopupMenu; import android.util.DisplayMetrics; import android.util.Log; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.MenuItem; import android.view.ViewAnimationUtils; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.LinearLayout; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.Toast; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.InterstitialAd; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Method; public class ChatHeadService extends Service { FrameLayout media_toolbar; FloatingActionButton fab; LinearLayout fab_layout, toolbar_layout; LayoutInflater li; private Animation fab_in, fab_out; private WindowManager windowManager; ImageButton popupbutton, pauseplaybutton, previousButton, nextButton, repeatButton; private MediaPlayer mMediaPlayer; private Uri uri; String text, fileName; private InterstitialAd mInterstitialAd; private AdRequest adRequest; private boolean playing = true; private View MyView; @Override public int onStartCommand(Intent intent, int flags, int startId) { fab.setVisibility(View.VISIBLE); fab.startAnimation(fab_in); if(intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { text = extras.getString("text", ""); fileName = extras.getString("filename", ""); Log.i("File", fileName); /*Intent i = new Intent(ChatHeadService.this, AudioService.class); i.putExtra("filename", fileName); startService(i);*/ mInterstitialAd = new InterstitialAd(this); // set the ad unit ID mInterstitialAd.setAdUnitId("ca-app-pub-4544715806674108/2130696710"); adRequest = new AdRequest.Builder() .build(); mInterstitialAd.loadAd(adRequest); mInterstitialAd.loadAd(adRequest); mInterstitialAd.setAdListener(new AdListener() { public void onAdLoaded() { if(mInterstitialAd.isLoaded()) mInterstitialAd.show(); } }); // Load ads into Interstitial Ads String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/ReaderApp/" + fileName; uri = Uri.parse("file://" + filename); Log.i("QW", "file://" + filename); mMediaPlayer = new MediaPlayer(); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mMediaPlayer.setDataSource(getApplicationContext(), uri); mMediaPlayer.prepare(); mMediaPlayer.start(); } catch (Exception e) { e.printStackTrace(); } startService(new Intent(ChatHeadService.this, ChatHeadService.class)); } } return START_STICKY; } @Override public IBinder onBind(Intent intent) { // Not used return null; } int length = 0; //@SuppressLint("ClickableViewAccessibility") @Override public void onCreate() { super.onCreate(); windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); setTheme(R.style.AppTheme); mInterstitialAd = new InterstitialAd(this); // set the ad unit ID mInterstitialAd.setAdUnitId("ca-app-pub-4544715806674108/2130696710"); adRequest = new AdRequest.Builder() .build(); mInterstitialAd.loadAd(adRequest); mInterstitialAd.setAdListener(new AdListener() { public void onAdLoaded() { if(mInterstitialAd.isLoaded()) mInterstitialAd.show(); } }); fab_in = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.design_fab_in); fab_out = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.design_fab_out); final WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); final WindowManager.LayoutParams FullScreenParams = new WindowManager.LayoutParams( WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH, PixelFormat.TRANSLUCENT); FullScreenParams.gravity = Gravity.RIGHT | Gravity.TOP; DisplayMetrics displayMetrics = new DisplayMetrics(); windowManager.getDefaultDisplay().getMetrics(displayMetrics); SetupLayout(); MyView = new View(this); MyView.setLayoutParams(FullScreenParams); //windowManager.addView(MyView, FullScreenParams); MyView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { MyView.performClick(); if(motionEvent.getAction() == MotionEvent.ACTION_DOWN) { ScaleDownFrameLayout(media_toolbar); windowManager.removeView(MyView); } return false; } }); //MyView.performClick(); if(mMediaPlayer != null && length != 0) { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); try { mMediaPlayer.setDataSource(getApplicationContext(), uri); mMediaPlayer.prepare(); mMediaPlayer.seekTo(length); mMediaPlayer.start(); } catch (Exception e) { e.printStackTrace(); } Log.i("mediaplayering", true + " oncreate " + length); mMediaPlayer.start(); } if(playing) { pauseplaybutton.setImageResource(R.drawable.ic_pause_button_vector); fab.setImageResource(R.drawable.ic_pause_button_vector); Log.i("mediaplayering", true + ""); } else { mMediaPlayer.pause(); pauseplaybutton.setImageResource(R.drawable.ic_play_button_vector); fab.setImageResource(R.drawable.ic_play_button_vector); Log.i("mediaplayering", false + ""); } pauseplaybutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(playing) { pauseplaybutton.setImageResource(R.drawable.ic_play_button_vector); fab.setImageResource(R.drawable.ic_play_button_vector); mMediaPlayer.pause(); length = mMediaPlayer.getCurrentPosition(); } else { pauseplaybutton.setImageResource(R.drawable.ic_pause_button_vector); fab.setImageResource(R.drawable.ic_pause_button_vector); mMediaPlayer.seekTo(length); mMediaPlayer.start(); } playing = !playing; } }); previousButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { backwardSong(5000); } }); nextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { forwardSong(5000); } }); repeatButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(mMediaPlayer.isPlaying()) { mMediaPlayer.stop(); playing = !playing; } else { pauseplaybutton.setImageResource(R.drawable.ic_pause_button_vector); playing =!playing; } mMediaPlayer.reset(); try { if( uri != null) { mMediaPlayer.setDataSource(getApplicationContext(), uri); mMediaPlayer.prepare(); mMediaPlayer.start(); playing = true; } } catch (IOException e) { e.printStackTrace(); } } }); fab.setVisibility(View.VISIBLE); fab.startAnimation(fab_in); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { fab.startAnimation(fab_out); fab.setVisibility(View.INVISIBLE); new Handler().postDelayed(new Runnable() { @Override public void run() { windowManager.removeView(fab_layout); params.gravity = Gravity.BOTTOM; params.y = 0; windowManager.addView(MyView, params); windowManager.addView(toolbar_layout, params); new Handler().postDelayed(new Runnable() { @Override public void run() { media_toolbar.setVisibility(View.VISIBLE); ScaleUpFrameLayout(media_toolbar); } },100); } }, 100); } }); params.gravity = Gravity.TOP | Gravity.RIGHT; params.x = 0; params.y = 200; popupbutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPopupWindow(v); } }); /* toolbar_layout.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: ScaleDownFrameLayout(media_toolbar); // windowManager.removeView(MyView); break; } return false; } });*/ mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(final MediaPlayer mp) { //pauseplaybutton.setImageResource(R.drawable.ic_play_button_vector); mInterstitialAd.loadAd(adRequest); mInterstitialAd.setAdListener(new AdListener() { public void onAdLoaded() { if(mInterstitialAd.isLoaded()) mInterstitialAd.show(); } }); } }); fab_layout.setOnTouchListener(new View.OnTouchListener() { private int initialX; private int initialY; private float initialTouchX; private float initialTouchY; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: initialX = params.x; initialY = params.y; initialTouchX = event.getRawX(); initialTouchY = event.getRawY(); return true; case MotionEvent.ACTION_UP: return true; case MotionEvent.ACTION_MOVE: params.x = initialX - (int) (event.getRawX() - initialTouchX); params.y = initialY + (int) (event.getRawY() - initialTouchY); windowManager.updateViewLayout(fab_layout, params); return true; } return false; } }); windowManager.addView(fab_layout, params); } private void showPopupWindow(View view) { PopupMenu popup = new PopupMenu(ChatHeadService.this, view); try { Field[] fields = popup.getClass().getDeclaredFields(); for (Field field : fields) { if ("mPopup".equals(field.getName())) { field.setAccessible(true); Object menuPopupHelper = field.get(popup); Class<?> classPopupHelper = Class.forName(menuPopupHelper.getClass().getName()); Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class); setForceIcons.invoke(menuPopupHelper, true); break; } } } catch (Exception e) { e.printStackTrace(); } popup.getMenuInflater().inflate(R.menu.main_menu, popup.getMenu()); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { switch(item.getItemId()){ case R.id.settings: TransitionAnimation(media_toolbar, SettingsPreferencesActivity.class, text, fileName); break; case R.id.help: TransitionAnimation(media_toolbar, WelcomeActivity.class, text, fileName); break; case R.id.exit: Intent i = new Intent(ChatHeadService.this, AppRater.class); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(i); KillBar(media_toolbar); break; } return true; } }); popup.show(); } @Override public void onDestroy() { // Stop the MediaPlayer mMediaPlayer.stop(); // Release the MediaPlayer mMediaPlayer.release(); super.onDestroy(); if (fab_layout != null) { try { windowManager.removeView(fab_layout); } catch (Exception ignored) {} } } private void KillBar (final View myView) { int cx = (myView.getLeft() + myView.getRight()) / 2; int cy = (myView.getTop() + myView.getBottom()) / 2; int finalRadius = Math.max(myView.getWidth(), myView.getHeight()); Animator animator = ViewAnimationUtils.createCircularReveal(myView, cx, cy, finalRadius, 0); animator.setInterpolator(new AccelerateDecelerateInterpolator()); animator.setDuration(500); animator.start(); new Handler().postDelayed(new Runnable() { @Override public void run() { myView.setVisibility(View.INVISIBLE); windowManager.removeView(toolbar_layout); windowManager.removeView(MyView); stopSelf(); } },500); } private void TransitionAnimation (final View myView, final Class activity, final String text, final String filename) { int cx = (myView.getLeft() + myView.getRight()) / 2; int cy = (myView.getTop() + myView.getBottom()) / 2; int finalRadius = Math.max(myView.getWidth(), myView.getHeight()); Animator animator = ViewAnimationUtils.createCircularReveal(myView, cx, cy, finalRadius, 0); animator.setInterpolator(new AccelerateDecelerateInterpolator()); animator.setDuration(500); animator.start(); new Handler().postDelayed(new Runnable() { @Override public void run() { myView.setVisibility(View.INVISIBLE); windowManager.removeView(toolbar_layout); windowManager.removeView(MyView); Intent i = new Intent(ChatHeadService.this, activity); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.putExtra("text", text); i.putExtra("filename", filename); startActivity(i); stopSelf(); } },500); } private void ScaleDownFrameLayout(final View myView) { int cx = (myView.getLeft() + myView.getRight()) / 2; int cy = (myView.getTop() + myView.getBottom()) / 2; // get the final radius for the clipping circle int finalRadius = Math.max(myView.getWidth(), myView.getHeight()); // i just swapped from radius, to radius arguments Animator animator = ViewAnimationUtils.createCircularReveal(myView, cx, cy, finalRadius, 0); animator.setInterpolator(new AccelerateDecelerateInterpolator()); animator.setDuration(500); animator.start(); new Handler().postDelayed(new Runnable() { @Override public void run() { myView.setVisibility(View.INVISIBLE); windowManager.removeView(toolbar_layout); length = mMediaPlayer.getCurrentPosition(); mMediaPlayer.pause(); onCreate(); } },500); } private void ScaleUpFrameLayout(View myView) { int cx = (myView.getLeft() + myView.getRight()) / 2; int cy = (myView.getTop() + myView.getBottom()) / 2; int finalRadius = Math.max(myView.getWidth(), myView.getHeight()); Animator animator = ViewAnimationUtils.createCircularReveal(myView, cx, cy, 0, finalRadius); animator.setInterpolator(new AccelerateDecelerateInterpolator()); animator.setDuration(500); animator.start(); } LinearLayout screen; private void SetupLayout() { li = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); fab_layout = (LinearLayout) li.inflate(R.layout.layout, null); toolbar_layout = (LinearLayout) li.inflate(R.layout.toolbar_layout, null); screen = toolbar_layout.findViewById(R.id.screen); popupbutton = toolbar_layout.findViewById(R.id.popup); media_toolbar = toolbar_layout.findViewById(R.id.mediatoolbar); fab = fab_layout.findViewById(R.id.fab); nextButton = toolbar_layout.findViewById(R.id.next); previousButton = toolbar_layout.findViewById(R.id.previous); pauseplaybutton = toolbar_layout.findViewById(R.id.pauseplay); repeatButton = toolbar_layout.findViewById(R.id.repeat); mMediaPlayer = new MediaPlayer(); } public void forwardSong(int seekForwardTime) { if (mMediaPlayer != null) { int currentPosition = mMediaPlayer.getCurrentPosition(); if (currentPosition + seekForwardTime <= mMediaPlayer.getDuration()) { mMediaPlayer.seekTo(currentPosition + seekForwardTime); } else { mMediaPlayer.seekTo(mMediaPlayer.getDuration()); } } } public void backwardSong(int seekForwardTime) { if (mMediaPlayer != null) { int currentPosition = mMediaPlayer.getCurrentPosition(); if (currentPosition - seekForwardTime >= 0) { mMediaPlayer.seekTo(currentPosition - seekForwardTime); } else { mMediaPlayer.seekTo(0); } } } }
package com.arc.test; import android.app.Activity; import android.content.Context; import android.hardware.camera2.CameraManager; import android.os.Bundle; import android.text.Editable; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; /** * @author 叶超 * @since 2019/4/26 17:48 */ public class FlashActivity extends Activity implements View.OnClickListener { private EditText lightInput; private Button lightBtn; private CameraManager manager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_flash); lightInput = findViewById(R.id.lightInput); lightBtn = findViewById(R.id.lightBtn); // button.setOnClickListener(new SouDianTongView()); } @Override public void onClick(View v) { if (v.getId() == R.id.b1) { Editable text = lightInput.getText(); Toast.makeText(this, "=-= \n" + text.toString(), Toast.LENGTH_SHORT).show(); // int progress = processBar.getProgress(); // progress += 10; // if (progress > 100) { // progress = 0; // } } } public void flashLight(boolean flag) { if (flag) { //open try { screenLight(); if (manager == null) { manager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE); } manager.setTorchMode("0", true);// "0"是主闪光灯 } catch (Exception e) { } } else { //close try { // if (manager == null) { // return; // } if (manager == null) { manager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE); } manager.setTorchMode("0", false); } catch (Exception e) { } } } private void screenLight() { Window localWindow = this.getWindow(); WindowManager.LayoutParams params = localWindow.getAttributes(); params.screenBrightness = 1.0f; localWindow.setAttributes(params); } // class SouDianTongView implements View.OnClickListener { // //手电筒的开关控制代码,固定格式,基本上没什么可修改的。 // @Override // public void onClick(View v) { // // // } // } }
package com.szcinda.express.persistence; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.transaction.annotation.Transactional; import java.util.Collection; import java.util.List; public interface CarrierRepository extends JpaRepository<Carrier,String> { Carrier findFirstById(String id); List<Carrier> findByNameIn(Collection<String> names); @Modifying @Transactional @Query("delete from Carrier where id = ?1") void deleteById(String id); }
package com.example.a16031940.taskmanager; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; 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 java.util.ArrayList; import java.util.Calendar; import java.util.List; public class MainActivity extends AppCompatActivity { ListView lv; ArrayList<String> taskArrayList; ArrayAdapter arrayAdapter; Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DBHelper mydb = new DBHelper(this); lv = findViewById(R.id.lv); taskArrayList = new ArrayList<String>(); ArrayList mydbArray = mydb.getAllTasks(); taskArrayList.addAll(mydbArray); arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, taskArrayList); lv.setAdapter(arrayAdapter); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, SecondActivity.class); startActivityForResult(i, 3); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 3) { if (resultCode == RESULT_OK) { Notifiers(requestCode); } } } public void Notifiers(int code){ Calendar cal = Calendar.getInstance(); cal.add(Calendar.SECOND,3); Intent intent = new Intent(MainActivity.this,MyReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this,code,intent,PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),pendingIntent); } }
package com.beiyelin.account.config; import lombok.extern.slf4j.Slf4j; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Created by xinsh on 2017/9/6. */ @Configuration @Slf4j public class GlobalCorsConfig extends WebMvcConfigurerAdapter{ // @Bean // public FilterRegistrationBean filterRegistrationBean() { // log.info("-------------------配置CORS-------------------------"); // log.info("config.setAllowCredentials(true);"); // log.info("config.addAllowedOrigin(\"http://localhost\");"); // log.info("config.addAllowedOrigin(\"https://www.getpostman.com\");"); // log.info("config.addAllowedHeader(\"*\");"); // log.info("config.addAllowedMethod(\"*\");"); // log.info("source.registerCorsConfiguration(\"/**\", config);"); // // UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // CorsConfiguration config = new CorsConfiguration(); // config.setAllowCredentials(true); // config.addAllowedOrigin("http://localhost"); // config.addAllowedOrigin("https://www.getpostman.com"); // config.addAllowedHeader("*"); // config.addAllowedMethod("*"); // source.registerCorsConfiguration("/**", config); // FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); // bean.setOrder(0); // return bean; // } @Override public void addCorsMappings(CorsRegistry registry) { log.info("------------------配置全局支持CORS(跨源请求)----------------------"); registry.addMapping("/**").allowedOrigins("*") .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .exposedHeaders("access-control-allow-headers", "access-control-allow-methods", "access-control-allow-origin", "access-control-max-age", "X-Frame-Options") .allowCredentials(false).maxAge(3600); super.addCorsMappings(registry); } }
package graphSeries; import java.util.*; public class ShortestPathBFS { public static void main(String[] args) { } static int[] shortestPathBFS(ArrayList<ArrayList<Integer>> adj, int V, int src) { int distance[] = new int[V]; Arrays.fill(distance, Integer.MAX_VALUE); Queue<Integer> q = new LinkedList<>(); distance[src] = 0; q.add(src); while (!q.isEmpty()) { int node = q.poll(); for (Integer it : adj.get(node)) { if (distance[node] + 1 < distance[it]) { distance[it] = distance[node] + 1; q.add(it); } } } return distance; } }
package com.br.cortex.cambio.api.web.request; import java.math.BigDecimal; public class CambioRequestTO { private String moedaOrigem; private String moedaDestino; private BigDecimal valor; private String dataCotacao; public CambioRequestTO(String moedaOrigem, String moedaDestino, BigDecimal valor, String dataCotacao) { this.moedaOrigem = moedaOrigem; this.moedaDestino = moedaDestino; this.valor = valor; this.dataCotacao = dataCotacao; } public CambioRequestTO() { } public String getMoedaOrigem() { return moedaOrigem; } public void setMoedaOrigem(String moedaOrigem) { this.moedaOrigem = moedaOrigem; } public String getMoedaDestino() { return moedaDestino; } public void setMoedaDestino(String moedaDestino) { this.moedaDestino = moedaDestino; } public BigDecimal getValor() { return valor; } public void setValor(BigDecimal valor) { this.valor = valor; } public String getDataCotacao() { return dataCotacao; } public void setDataCotacao(String dataCotacao) { this.dataCotacao = dataCotacao; } }
package com.pz.Converter; import com.pz.DataBase.PokojeRezerwacje; import com.pz.Dto.PokojeRezerwacjeDto; public interface PokojeRezerwacjeConverter extends DefaultConverter<PokojeRezerwacje,PokojeRezerwacjeDto> { }
package com.everis.eCine.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.everis.eCine.model.Film; @Repository public interface FilmRepository extends JpaRepository<Film, Long> { public Film findByTitre(String titre); }
package com.tfxk.framework.utils; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.database.Cursor; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.widget.Toast; import com.tfxk.framework.R; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created by chenchunpeng on 2015/6/8. * email:fpa@shubaobao.com<br> * for Intent Action */ public class IntentUtil { public static final int REQUEST_CODE_PIC_IMAGE = 101; public static File uri2File(Activity context, Uri uri) { File file = null; String[] proj = {MediaStore.Images.Media.DATA}; Cursor actualimagecursor = context.managedQuery(uri, proj, null, null, null); int actual_image_column_index = actualimagecursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); actualimagecursor.moveToFirst(); String img_path = actualimagecursor .getString(actual_image_column_index); file = new File(img_path); return file; } /** * @param context * @param requestCode * @see FileUtils#parseImageFromFile(Context, Intent) */ public static void pickImage(Activity context, int requestCode) { Intent innerIntent = new Intent(); // "android.intent.action.GET_CONTENT" if (Build.VERSION.SDK_INT < 19) { innerIntent.setAction(Intent.ACTION_GET_CONTENT); } else { // innerIntent.setAction(Intent.ACTION_OPEN_DOCUMENT); innerIntent.setAction(Intent.ACTION_PICK); innerIntent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI); } innerIntent.setType("image/*"); Intent wrapperIntent = Intent.createChooser(innerIntent, context.getString(R.string.choose_picture)); context.startActivityForResult(wrapperIntent, requestCode); } /** * select a picture by Camera, * * @param context * @param imagePath the path of the image which take by the camera * @param imageName the name of the image which take by the camera * @param requestCode */ public static File selectPicFromCamera(Activity context, String imagePath, String imageName, int requestCode) { if (!FileUtils.isSdCardExists()) { String st = context.getResources().getString(R.string.sd_card_does_not_exist); Toast.makeText(context, st, Toast.LENGTH_SHORT).show(); return null; } File cameraFile = new File(imagePath, imageName); cameraFile.getParentFile().mkdirs(); context.startActivityForResult( new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)), requestCode); return cameraFile; } public static File selectPicFromCamera(Activity context, String filePath, int requestCode) { if (!FileUtils.isSdCardExists()) { String st = context.getResources().getString(R.string.sd_card_does_not_exist); Toast.makeText(context, st, Toast.LENGTH_SHORT).show(); return null; } File cameraFile = new File(filePath); cameraFile.getParentFile().mkdirs(); context.startActivityForResult( new Intent(MediaStore.ACTION_IMAGE_CAPTURE).putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile)), requestCode); return cameraFile; } public static void downloadApk(Context context, String url) { Uri uri = Uri.parse(url); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(uri); context.startActivity(intent); } /** * 检查手机上是否安装了指定的软件 * * @param context * @param packageName:应用包名 * @return */ public static boolean isAvilible(Context context, String packageName) { //获取packagemanager final PackageManager packageManager = context.getPackageManager(); //获取所有已安装程序的包信息 List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0); //用于存储所有已安装程序的包名 List<String> packageNames = new ArrayList<String>(); //从pinfo中将包名字逐一取出,压入pName list中 if (packageInfos != null) { for (int i = 0; i < packageInfos.size(); i++) { String packName = packageInfos.get(i).packageName; packageNames.add(packName); } } //判断packageNames中是否有目标程序的包名,有TRUE,没有FALSE return packageNames.contains(packageName); } /** * 通知相册改变 * @param context * @param path */ public static void notifyDICMUpdate(Context context,String path) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 判断SDK版本是不是4.4或者高于4.4 String[] paths = new String[]{path}; MediaScannerConnection.scanFile(context, paths, null, null); } else { File file=new File(path); final Intent intent; if (file.isDirectory()) { intent = new Intent(Intent.ACTION_MEDIA_MOUNTED); intent.setClassName("com.android.providers.media", "com.android.providers.media.MediaScannerReceiver"); intent.setData(Uri.fromFile(file)); } else { intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); intent.setData(Uri.fromFile(new File(path))); } context.sendBroadcast(intent); } } }
/** * @author smxknife * 2020/6/13 */ package com.smxknife.guava.cache;
package crdhn.sis.controller; import crdhn.sis.configuration.Configuration; import crdhn.sis.model.CommentInfo; import crdhn.sis.model.ReportInfo; import crdhn.sis.model.SessionInfo; import crdhn.sis.model.UserInfo; import crdhn.sis.transport.SISMongoDBConnectorClient; import crdhn.sis.utils.DataResponse; import crdhn.sis.utils.ServletUtil; import crdhn.sis.utils.Utils; import firo.Controller; import firo.Request; import firo.Response; import firo.Route; import firo.RouteInfo; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import java.util.stream.Stream; import org.json.JSONException; import org.json.JSONObject; public class ReportController extends Controller { public ReportController() { rootPath = "/report/"; } @RouteInfo(method = "get,post", path = "/getOrganizations") public Route getOrganizations() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo == null) { return DataResponse.SESSION_EXPIRED; } else { return SISMongoDBConnectorClient.getInstance().getOrganizations(); } }; } @RouteInfo(method = "get,post", path = "/getStatus") public Route getStatusReport() { return (Request request, Response response) -> { Utils.printLogSystem("ReportController", "getStatusReport"); String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { List<Object> arrStatus = new ArrayList(); for (ReportInfo.ReportStatus rStatus : ReportInfo.ReportStatus.values()) { HashMap obj = new HashMap(); obj.put("value", rStatus.getValue()); obj.put("description", rStatus.getDescription()); arrStatus.add(obj); } return new DataResponse(arrStatus); } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get", path = "/getAddress") public Route getAddress() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { String HOME_PATH = System.getProperty("apppath"); if (HOME_PATH == null || HOME_PATH.isEmpty()) { HOME_PATH = "."; } List<Object> arrAddress = new ArrayList(); String path = HOME_PATH + File.separator + "data" + File.separator + Configuration.path_address_report; try (Stream<String> stream = Files.lines(Paths.get(path), StandardCharsets.UTF_8)) { stream.forEach(line -> { if (!line.isEmpty() && line.trim().length() > 0) { try { JSONObject dataAddress = new JSONObject(line); HashMap obj = new HashMap(); obj.put("districtName", dataAddress.getString("districtName")); obj.put("provinceName", dataAddress.getString("provinceName")); arrAddress.add(obj); } catch (JSONException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } }); } catch (IOException e) { e.printStackTrace(); } return new DataResponse(arrAddress); } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/addReport") public Route addReport() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { String content = ServletUtil.getStringParameter(request, "content"); List<String> images = ServletUtil.getListStringParameter(request, "images", ","); List<String> organizationIds = ServletUtil.getListStringParameter(request, "organizationIds", ","); // int type = ServletUtil.getIntParameter(request, "type"); // ReportInfo.ReportType reportType = ReportInfo.ReportType.getReportTypeByValue(type); // if (reportType == null) { // return DataResponse.PARAM_ERROR; // } String districtAddress = ServletUtil.getStringParameter(request, "districtName"); String provinceName = ServletUtil.getStringParameter(request, "provinceName"); ReportInfo rInfo = new ReportInfo(); rInfo.setReporterName(sessionInfo.getAccountName()); rInfo.setContent(content); rInfo.setImages(images); rInfo.setComments(new ArrayList<>()); rInfo.setOrganizationIds(organizationIds); rInfo.setStatus(ReportInfo.ReportStatus.Created.getValue()); // rInfo.setType(reportType.getValue()); rInfo.setCityAddress(provinceName); rInfo.setDistrictAddress(districtAddress); rInfo.setCreateTime(System.currentTimeMillis()); DataResponse resp = SISMongoDBConnectorClient.getInstance().addReport(rInfo); System.out.println("ReportController.addReport resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/follow") public Route followReport() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { long reportId = ServletUtil.getLongParameter(request, "reportId"); if(reportId<=0){ return DataResponse.PARAM_ERROR; } DataResponse resp = SISMongoDBConnectorClient.getInstance().followReport(reportId, sessionInfo.accountName); System.out.println("ReportController.followReport resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/unfollow") public Route unfollowReport() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { long reportId = ServletUtil.getLongParameter(request, "reportId"); if(reportId<=0){ return DataResponse.PARAM_ERROR; } DataResponse resp = SISMongoDBConnectorClient.getInstance().unfollowReport(reportId, sessionInfo.getAccountName()); System.out.println("ReportController.unfollowReport resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/getReportFollowing") public Route getReportFollowing() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { int page = ServletUtil.getIntParameter(request, "page"); DataResponse resp = SISMongoDBConnectorClient.getInstance().getListReportFollowing(sessionInfo.getAccountName(), page); System.out.println("ReportController.getReportFollowing resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/getDetail") public Route getDetailReport() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { long reportId = ServletUtil.getLongParameter(request, "reportId"); DataResponse resp = SISMongoDBConnectorClient.getInstance().getReportDetail(reportId, sessionInfo.getAccountName()); System.out.println("ReportController.getDetailReport resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/getreport") public Route getReportsByReporterName() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { int page = ServletUtil.getIntParameter(request, "page"); DataResponse resp = SISMongoDBConnectorClient.getInstance().getReportsByReporterName(sessionInfo.getAccountName(), page); System.out.println("ReportController.getReportsByReporterName resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/getreport/new") public Route getReportsLastTime() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { int page = ServletUtil.getIntParameter(request, "page"); DataResponse resp = SISMongoDBConnectorClient.getInstance().getReportsLastTime(sessionInfo.getAccountName(), page); System.out.println("ReportController.getReportsLastTime resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/getreport/address") public Route getReportsByAddress() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { int page = ServletUtil.getIntParameter(request, "page"); String districtName = ServletUtil.getStringParameter(request, "districtName"); String provinceName = ServletUtil.getStringParameter(request, "provinceName"); DataResponse resp = SISMongoDBConnectorClient.getInstance().getReportsByAddress(sessionInfo.getAccountName(), districtName, provinceName, page); System.out.println("ReportController.getReportsByAddress resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/organization/getreport") public Route getReportOrganizationsByStatus() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { int paramStatus = ServletUtil.getIntParameter(request, "status"); int page = ServletUtil.getIntParameter(request, "page"); ReportInfo.ReportStatus reportStatus = ReportInfo.ReportStatus.getReportStatusByValue(paramStatus); if (paramStatus > 0 && reportStatus == null) { return DataResponse.PARAM_ERROR; } DataResponse resp = SISMongoDBConnectorClient.getInstance().getReportOrganizationsByStatus(sessionInfo.getAccountName(), paramStatus, page); System.out.println("ReportController.getReportOrganizationsByStatus resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/forward") public Route forwardReport() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { if (sessionInfo.accountType != UserInfo.TYPE_ORGANAZATION) { return DataResponse.ACCESS_DENY; } int reportId = ServletUtil.getIntParameter(request, "reportId"); List<String> forwardIds = ServletUtil.getListStringParameter(request, "destination", ","); if (reportId <= 0 || forwardIds.isEmpty()) { return DataResponse.PARAM_ERROR; } DataResponse resp = SISMongoDBConnectorClient.getInstance().forwardReport(sessionInfo.getAccountName(), forwardIds, reportId); System.out.println("ReportController.forwardReport resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/changeStatus") public Route changeStatusReport() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { if (sessionInfo.accountType != UserInfo.TYPE_ORGANAZATION) { return DataResponse.ACCESS_DENY; } int reportId = ServletUtil.getIntParameter(request, "reportId"); int status = ServletUtil.getIntParameter(request, "status"); long deadlineTime = ServletUtil.getLongParameter(request, "deadlineTime"); ReportInfo.ReportStatus reportStatus = ReportInfo.ReportStatus.getReportStatusByValue(status); if (reportId <= 0 || reportStatus == null || (reportStatus.getValue() == ReportInfo.ReportStatus.Received.getValue() && deadlineTime <= 0)) { return DataResponse.PARAM_ERROR; } DataResponse resp = SISMongoDBConnectorClient.getInstance().changeStatusReport(sessionInfo.getAccountName(), reportId, reportStatus.getValue(), deadlineTime); System.out.println("ReportController.changeStatusReport resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/comment/add") public Route addComment() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { int reportId = ServletUtil.getIntParameter(request, "reportId"); String content = ServletUtil.getStringParameter(request, "content"); List<String> images = ServletUtil.getListStringParameter(request, "images", ","); if (reportId <= 0 || content.isEmpty()) { return DataResponse.PARAM_ERROR; } CommentInfo cInfo = new CommentInfo(); cInfo.setContent(content); cInfo.setReportId(reportId); cInfo.setOwnerId(sessionInfo.accountName); cInfo.setTypeUser(sessionInfo.accountType); cInfo.setImages(images); cInfo.setCreateTime(System.currentTimeMillis()); DataResponse resp = SISMongoDBConnectorClient.getInstance().addComment(cInfo); System.out.println("ReportController.addComment resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/comment/get") public Route getComment() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { int reportId = ServletUtil.getIntParameter(request, "reportId"); if (reportId <= 0) { return DataResponse.PARAM_ERROR; } DataResponse resp = SISMongoDBConnectorClient.getInstance().getComment(reportId, 0); System.out.println("ReportController.getComment resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } @RouteInfo(method = "get,post", path = "/monitoring") public Route getDataMonitoring() { return (Request request, Response response) -> { String sessionKey = ServletUtil.getStringParameter(request, "sessionKey"); SessionInfo sessionInfo = SISMongoDBConnectorClient.getInstance().checkSession(sessionKey); if (sessionInfo != null) { String organizationId = ServletUtil.getParameter(request, "organizationId"); if (organizationId == null || organizationId.isEmpty()) { return DataResponse.PARAM_ERROR; } if (sessionInfo.accountType != UserInfo.TYPE_ORGANAZATION) { return DataResponse.ACCESS_DENY; } DataResponse resp = SISMongoDBConnectorClient.getInstance().getDataMonitoringByOrganization(organizationId); System.out.println("ReportController.getDataMonitoring resp =" + resp); return resp; } else { return DataResponse.SESSION_EXPIRED; } }; } }
public class SplitAStringInBalancedStrings_1221 { public static int balancedStringSplit(String s) { int count = 0, curr = 0; for(char ch : s.toCharArray()){ if(ch == 'R') curr--; else curr++; if(curr == 0) ++count; } return count; } public static void main(String[] args){ System.out.println(balancedStringSplit("LLRRLRLRLR")); } }
package classes; import java.util.Date; import java.util.List; public class TDCategory { private List<TDEntry> entries; private String name; private Date dateCreated; public TDCategory(List<TDEntry> entries, String name, Date date) { super(); this.entries = entries; this.name = name; this.dateCreated = date; } public List<TDEntry> getEntries() { return entries; } public void setEntries(List<TDEntry> entries) { this.entries = entries; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDCreated() { return dateCreated; } public void setDCreated(Date dateCreated) { this.dateCreated = dateCreated; } public int getNEntries() { return entries.size(); } public int getNChecked() { int nChecked = 0; for(TDEntry e : entries) { if(e.isChecked()) nChecked ++; } return nChecked; } public int getNPending() { int nPendig = 0; for(TDEntry entry : entries){ if(!entry.isChecked()) nPendig++; } return nPendig; } }
package com.ssp.tp; import java.io.File; import java.io.FileNotFoundException; import java.util.*; /** * systemd 启动机器, 3个机器,2个查询。 1号机器依赖与2, 2号机器依赖于3, 3号机器不依赖什么。 * 请问启动1号机器后,总共多少机器。关闭2号机器后,总供多少机器 * * 3 2 * 1 2 * 1 3 * 0 * 1 1 * 0 2 */ public class Main_JD_QZ { public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner( new File("/Users/sunyindong/workspace/TestJava/Leetcode/src/main/resources/input.txt")); // Scanner sc = new Scanner(System.in); Set<Integer> startSet = new HashSet<>(); int n = sc.nextInt(); int q = sc.nextInt(); sc.nextLine(); Map<Integer, Set<Integer>> mapNext = new HashMap<>(); Map<Integer, Set<Integer>> mapPre = new HashMap<>(); int curLin = 1; while (n-- > 0) { String line = sc.nextLine(); String[] s = line.split(" "); if (s.length > 1) { for (int i = 1; i < s.length; i++) { int curJ = Integer.parseInt(s[i]); Set<Integer> orDefault = mapNext.getOrDefault(curLin, new HashSet<>()); orDefault.add(curJ); mapNext.put(curLin, orDefault); Set<Integer> orPre = mapPre.getOrDefault(curJ, new HashSet<>()); orPre.add(curLin); mapPre.put(curJ, orPre); } } curLin++; } while (q-- > 0) { String query = sc.nextLine(); String[] qArray = query.split(" "); boolean isStart = qArray[0].equals("0") ? false : true; Integer needStart = Integer.parseInt(qArray[1]); if (isStart) { if (!startSet.contains(needStart)) { startSet.add(needStart); Set<Integer> integers = mapNext.getOrDefault(needStart, new HashSet<>()); Deque<Integer> deque = new LinkedList<>(integers); while (!deque.isEmpty()) { Integer need = deque.pollFirst(); if (startSet.contains(need)) { continue; } else { startSet.add(need); Set<Integer> orDefault = mapNext.getOrDefault(need, null); if (orDefault != null) { deque.addAll(orDefault); } } } } } else { if (startSet.contains(needStart)) { startSet.remove(needStart); Set<Integer> integers = mapPre.getOrDefault(needStart, new HashSet<>()); Deque<Integer> deque = new LinkedList<>(integers); while (!deque.isEmpty()) { Integer need = deque.pollFirst(); if (!startSet.contains(need)) { continue; } else { startSet.remove(need); Set<Integer> orDefault = mapPre.getOrDefault(need, null); if (orDefault != null) { deque.addAll(orDefault); } } } } } System.out.println(startSet.size()); } } }
package com.smxknife.springboot.v2.responsebodyRequestBody.component; import com.fasterxml.jackson.databind.ObjectMapper; import com.smxknife.springboot.v2.responsebodyRequestBody.domain.JsonModel; import org.springframework.http.HttpInputMessage; import org.springframework.http.HttpOutputMessage; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.http.converter.HttpMessageNotWritableException; import javax.annotation.PostConstruct; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class JsonParseHttpMessageConverter implements HttpMessageConverter<JsonModel> { private static List<MediaType> supportMediaTypes = Collections.synchronizedList(new ArrayList<>()); ObjectMapper objectMapper; public JsonParseHttpMessageConverter(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } @PostConstruct void init() { this.getSupportedMediaTypes().add(MediaType.APPLICATION_JSON); } @Override public boolean canRead(Class<?> clazz, MediaType mediaType) { return support(clazz) && supportRead(mediaType); } private boolean supportRead(MediaType mediaType) { if (mediaType == null) return true; for (MediaType supportMediaType : supportMediaTypes) { if (supportMediaType.includes(mediaType)) return true; } return false; } private boolean support(Class<?> clazz) { return JsonModel.class.isAssignableFrom(clazz); } @Override public boolean canWrite(Class<?> clazz, MediaType mediaType) { return support(clazz) && supportWrite(mediaType); } private boolean supportWrite(MediaType mediaType) { if (mediaType == null || MediaType.ALL.equals(mediaType)) { return true; } for (MediaType supportedMediaType : getSupportedMediaTypes()) { if (supportedMediaType.isCompatibleWith(mediaType)) { return true; } } return false; } @Override public List<MediaType> getSupportedMediaTypes() { return supportMediaTypes; } @Override public JsonModel read(Class<? extends JsonModel> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { return objectMapper.readValue(inputMessage.getBody(), clazz); } @Override public void write(JsonModel jsonModel, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { objectMapper.writeValue(outputMessage.getBody(), jsonModel); } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.extension.frontend.client.widget.openmeetings; import java.util.ArrayList; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style.Unit; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.TabLayoutPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; import com.openkm.extension.frontend.client.service.OKMOpenMeetingsService; import com.openkm.extension.frontend.client.service.OKMOpenMeetingsServiceAsync; import com.openkm.extension.frontend.client.widget.openmeetings.finddocument.FindDocumentSelectPopup; import com.openkm.extension.frontend.client.widget.openmeetings.invite.InvitationPopup; import com.openkm.frontend.client.bean.extension.GWTRoom; import com.openkm.frontend.client.extension.comunicator.GeneralComunicator; /** * OpenMeetings * * @author jllort * */ public class OpenMeetingsManager extends Composite { private final OKMOpenMeetingsServiceAsync openMeetingsService = (OKMOpenMeetingsServiceAsync) GWT .create(OKMOpenMeetingsService.class); private static final int TAB_HEIGHT = 20; private final int NUMBER_OF_COLUMNS = 2; private TabLayoutPanel tabPanel; private RoomPanel conferenceRooms; private RoomPanel privateConferenceRooms; private RoomPanel restrictedRooms; private RoomPanel interviewRooms; private ManageRoom manageRoom; private Status conferenceStatus; private Status privateConferenceStatus; private Status restrictedStatus; private Status interviewStatus; public ScrollPanel scrollPanel; private HorizontalPanel hPanel; private VerticalPanel vPanelLeft; private VerticalPanel vPanelRight; private List<Long> userLoggedRoom; private InvitationPopup invitationPopup; private FindDocumentSelectPopup findDocumentSelectPopup; /** * OpenMeetingsManager * * @param width * @param height */ public OpenMeetingsManager(int width, int height) { userLoggedRoom = new ArrayList<Long>(); invitationPopup = new InvitationPopup(); invitationPopup.setWidth("400px"); invitationPopup.setHeight("100px"); invitationPopup.setStyleName("okm-Popup"); findDocumentSelectPopup = new FindDocumentSelectPopup(); findDocumentSelectPopup.setWidth("700px"); findDocumentSelectPopup.setHeight("390px"); findDocumentSelectPopup.setStyleName("okm-Popup"); findDocumentSelectPopup.addStyleName("okm-DisableSelect"); tabPanel = new TabLayoutPanel(TAB_HEIGHT, Unit.PX); tabPanel.setPixelSize(width, height); conferenceRooms = new RoomPanel("openmeetings.room.public.conference", true, false, false); privateConferenceRooms = new RoomPanel("openmeetings.room.private.conference", true, true, true); restrictedRooms = new RoomPanel("openmeetings.room.restricted", true, true, true); interviewRooms = new RoomPanel("openmeetings.room.interview", true, true, true); conferenceStatus = new Status(conferenceRooms); privateConferenceStatus = new Status(privateConferenceRooms); restrictedStatus = new Status(restrictedRooms); interviewStatus = new Status(interviewRooms); conferenceStatus.setStyleName("okm-StatusPopup"); restrictedStatus.setStyleName("okm-StatusPopup"); interviewStatus.setStyleName("okm-StatusPopup"); manageRoom = new ManageRoom(); vPanelLeft = new VerticalPanel(); vPanelRight = new VerticalPanel(); hPanel = new HorizontalPanel(); scrollPanel = new ScrollPanel(hPanel); vPanelLeft.add(conferenceRooms); vPanelLeft.add(privateConferenceRooms); vPanelLeft.add(restrictedRooms); vPanelLeft.add(interviewRooms); vPanelRight.add(manageRoom); hPanel.add(vPanelLeft); hPanel.add(vPanelRight); tabPanel.add(scrollPanel, GeneralComunicator.i18nExtension("openmeetings.rooms")); hPanel.setHeight("100%"); vPanelRight.setHeight("100%"); initDeletePublicRooms(); initWidget(tabPanel); } /** * firstTimeInitDeletePublicRoom */ private void initDeletePublicRooms() { if (GeneralComunicator.getWorkspace() != null) { if (GeneralComunicator.getWorkspace().isAdminRole()) { conferenceRooms.setDelete(true); } reset(); // First time get rooms } else { Timer timer = new Timer() { @Override public void run() { initDeletePublicRooms(); } }; timer.schedule(1000); } } @Override public void setPixelSize(int width, int height) { super.setPixelSize(width, height); scrollPanel.setPixelSize(width, height - TAB_HEIGHT); } /** * setWidth * * @param width */ public void setWidth(int width) { int columnWidth = width / NUMBER_OF_COLUMNS; // Trying to distribute widgets on columns with max size conferenceRooms.setWidth(columnWidth); privateConferenceRooms.setWidth(columnWidth); restrictedRooms.setWidth(columnWidth); interviewRooms.setWidth(columnWidth); manageRoom.setWidth("" + columnWidth+"px"); manageRoom.setHeight("100%"); } /** * reset */ public void reset() { getRoomsPublic(conferenceRooms, GWTRoom.TYPE_CONFERENCE); getPrivateConferenceUserRooms(privateConferenceRooms); getRestrictedUserRooms(restrictedRooms); getInterviewUserRooms(interviewRooms); } /** * getRoomsPublic * * @param rp * @param roomType */ private void getRoomsPublic(final RoomPanel rp, final int roomType) { conferenceStatus.setGetRooms(); openMeetingsService.loginUser(new AsyncCallback<String>() { @Override public void onSuccess(String result) { String SID = result; openMeetingsService.getRoomsPublic(SID, roomType, new AsyncCallback<List<GWTRoom>>() { @Override public void onSuccess(List<GWTRoom> result) { rp.addRooms(result); conferenceStatus.unsetGetRooms(); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("getRoomsPublic", caught); conferenceStatus.unsetGetRooms(); } }); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("loginUser", caught); conferenceStatus.unsetGetRooms(); } }); } /** * getRestrictedUserRooms */ private void getPrivateConferenceUserRooms(final RoomPanel rp) { privateConferenceStatus.setGetRooms(); openMeetingsService.loginUser(new AsyncCallback<String>() { @Override public void onSuccess(String result) { String SID = result; openMeetingsService.getPrivateConferenceUserRooms(SID, new AsyncCallback<List<GWTRoom>>() { @Override public void onSuccess(List<GWTRoom> result) { rp.addRooms(result); privateConferenceStatus.unsetGetRooms(); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("getPrivateConferenceUserRooms", caught); privateConferenceStatus.unsetGetRooms(); } }); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("loginUser", caught); privateConferenceStatus.unsetGetRooms(); } }); } /** * getRestrictedUserRooms */ private void getRestrictedUserRooms(final RoomPanel rp) { restrictedStatus.setGetRooms(); openMeetingsService.loginUser(new AsyncCallback<String>() { @Override public void onSuccess(String result) { String SID = result; openMeetingsService.getRestrictedUserRooms(SID, new AsyncCallback<List<GWTRoom>>() { @Override public void onSuccess(List<GWTRoom> result) { rp.addRooms(result); restrictedStatus.unsetGetRooms(); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("getRestrictedUserRooms", caught); restrictedStatus.unsetGetRooms(); } }); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("loginUser", caught); restrictedStatus.unsetGetRooms(); } }); } /** * getInterviewUserRooms */ private void getInterviewUserRooms(final RoomPanel rp) { interviewStatus.setGetRooms(); openMeetingsService.loginUser(new AsyncCallback<String>() { @Override public void onSuccess(String result) { String SID = result; openMeetingsService.getInterviewUserRooms(SID, new AsyncCallback<List<GWTRoom>>() { @Override public void onSuccess(List<GWTRoom> result) { rp.addRooms(result); interviewStatus.unsetGetRooms(); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("getInterviewUserRooms", caught); interviewStatus.unsetGetRooms(); } }); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("loginUser", caught); interviewStatus.unsetGetRooms(); } }); } /** * langRefresh */ public void langRefresh() { invitationPopup.langRefresh(); findDocumentSelectPopup.langRefresh(); conferenceRooms.langRefresh(); privateConferenceRooms.langRefresh(); restrictedRooms.langRefresh(); interviewRooms.langRefresh(); manageRoom.langRefresh(); int selecteTab = tabPanel.getSelectedIndex(); List<Widget> widgetList = new ArrayList<Widget>(); // Save widgets for (int i = 0; i < tabPanel.getWidgetCount(); i++) { widgetList.add(tabPanel.getWidget(i)); } tabPanel.clear(); // Restores widgets for (Widget widget : widgetList) { if (widget instanceof ScrollPanel) { tabPanel.add(widget, GeneralComunicator.i18nExtension("openmeetings.rooms")); } else if (widget instanceof TabRoom) { TabRoom tabRoom = (TabRoom) widget; tabPanel.add(tabRoom, tabRoom.getRoomName()); ; } } tabPanel.selectTab(selecteTab); } /** * enterPublicRoom * * @param roomId */ public void enterPublicRoom(final String roomName, final long roomId) { openMeetingsService.loginUser(new AsyncCallback<String>() { @Override public void onSuccess(String result) { String SID = result; String lang = GeneralComunicator.getLang(); boolean moderator = GeneralComunicator.getWorkspace().isAdminRole(); boolean showAudioVideoTest = true; openMeetingsService.getPublicRoomURL(SID, roomId, moderator, showAudioVideoTest, lang, new AsyncCallback<String>() { @Override public void onSuccess(String result) { TabRoom tabRoom = new TabRoom(result, roomName, roomId); tabPanel.add(tabRoom, roomName); tabPanel.selectTab(tabRoom); // Show actual view userLoggedRoom.add(new Long(roomId)); reset(); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("getPublicRoomURL", caught); } }); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("loginUser", caught); } }); } /** * createNewRoom */ public void createNewRoom(final String name, final long roomType, final long numberOfPartizipants, final boolean isPublic, final boolean appointment, final boolean moderated, final boolean allowUserQuestions, final boolean audioOnly, final boolean waitForRecording, final boolean allowRecording, final boolean topBar) { OpenMeetings.get().generalStatus.setCreateRoom(); openMeetingsService.loginUser(new AsyncCallback<String>() { @Override public void onSuccess(String result) { String SID = result; openMeetingsService.createNewRoom(SID, name, roomType, numberOfPartizipants, isPublic, appointment, moderated, allowUserQuestions, audioOnly, waitForRecording, allowRecording, topBar, new AsyncCallback<Object>() { @Override public void onSuccess(Object result) { reset(); OpenMeetings.get().generalStatus.unsetCreateRoom(); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("createNewRoom", caught); OpenMeetings.get().generalStatus.unsetCreateRoom(); } }); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("loginUser", caught); OpenMeetings.get().generalStatus.unsetCreateRoom(); } }); } /** * deleteRoom * * @param roomId */ public void deleteRoom(final long roomId) { OpenMeetings.get().generalStatus.setDeleteRoom(); openMeetingsService.loginUser(new AsyncCallback<String>() { @Override public void onSuccess(String result) { String SID = result; openMeetingsService.deleteRoom(SID, roomId, new AsyncCallback<Object>() { @Override public void onSuccess(Object result) { // Remove tabPanel if user is connected for (int i = 0; i < tabPanel.getWidgetCount(); i++) { if (tabPanel.getWidget(i) instanceof TabRoom) { TabRoom tabRoom = (TabRoom) tabPanel.getWidget(i); if (tabRoom.getRoomId() == roomId) { tabPanel.remove(i); break; } } } reset(); OpenMeetings.get().generalStatus.unsetDeleteRoom(); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("deleteRoom", caught); OpenMeetings.get().generalStatus.unsetDeleteRoom(); } }); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("loginUser", caught); OpenMeetings.get().generalStatus.unsetDeleteRoom(); } }); } /** * sendInvitation */ public void sendInvitation(final long roomId, final String users, final String roles, final String subject, final String message) { OpenMeetings.get().generalStatus.setSendInvitation(); openMeetingsService.loginUser(new AsyncCallback<String>() { @Override public void onSuccess(String result) { String SID = result; openMeetingsService.sendInvitation(SID, roomId, users, roles, subject, message, GeneralComunicator.getLang(), new AsyncCallback<Object>() { @Override public void onSuccess(Object result) { OpenMeetings.get().generalStatus.unsetSendInvitation(); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("sendInvitation", caught); OpenMeetings.get().generalStatus.unsetSendInvitation(); } }); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("loginUser", caught); OpenMeetings.get().generalStatus.unsetSendInvitation(); } }); } /** * executeInviteUsers */ public void executeInviteUsers(long roomId) { invitationPopup.executeSendInvitation(roomId); } /** * addDocumentToRoom */ public void addDocumentToRoom(final long roomId, final String path) { OpenMeetings.get().generalStatus.setAddDocument(); openMeetingsService.loginUser(new AsyncCallback<String>() { @Override public void onSuccess(String result) { String SID = result; openMeetingsService.addDocumentToRoom(SID, roomId, path, new AsyncCallback<Object>() { @Override public void onSuccess(Object result) { OpenMeetings.get().generalStatus.unsetAddDocument(); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("addDocumentToRoom", caught); OpenMeetings.get().generalStatus.unsetAddDocument(); } }); } @Override public void onFailure(Throwable caught) { GeneralComunicator.showError("loginUser", caught); OpenMeetings.get().generalStatus.unsetAddDocument(); } }); } /** * executeFindDocument */ public void executeFindDocument(long roomId) { findDocumentSelectPopup.show(roomId); } /** * closeLoggedRoom * * @param roomId */ public void closeLoggedRoom(long roomId) { // Removing from logged list for (Long id : userLoggedRoom) { if (id.longValue() == roomId) { userLoggedRoom.remove(id); break; } } // Remove tabPanel if user is connected for (int i = 0; i < tabPanel.getWidgetCount(); i++) { if (tabPanel.getWidget(i) instanceof TabRoom) { TabRoom tabRoom = (TabRoom) tabPanel.getWidget(i); if (tabRoom.getRoomId() == roomId) { tabPanel.remove(i); break; } } } reset(); } /** * isUserLooged */ public boolean isUserLooged(long roomId) { boolean found = false; for (Long id : userLoggedRoom) { if (id.longValue() == roomId) { found = true; break; } } return found; } }
/* * 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 esfera; public class Esfera { private double angulo1; private double angulo2; private double r; public Esfera( double angulo1, double angulo2, double r ){ this.r = r; this.angulo1 = angulo1; this.angulo2 = angulo2; } public double getR(){ return r; } public double setR(double r){ this.r = r; } public double getR(){ return r; } }
package Http; import Http.Commands.MessageCommand; import Util.Config.BasicConfig; import Util.Timer; import Util.UDP.GroupListener; import Util.UDP.ProcessUDPListener; import Util.UDP.UDPClient; import com.sun.net.httpserver.HttpServer; import java.io.*; import java.net.*; import java.util.*; import java.util.concurrent.TimeUnit; public class Server implements Runnable { private int processNumber; private Timer timer; private boolean iWantToEnterCriticalRegion = false; private boolean imAtCriticalRegion = false; private Queue<Map<String,Integer>> reqList = new LinkedList<>(); private List<Integer> processesPorts = new ArrayList<>(); private UDPClient udpClient = new UDPClient(); private int clientsReady = 1; public Server(int processNumber){ this.processNumber = processNumber; this.timer = new Timer(this); Thread udpListener = new Thread( new ProcessUDPListener( this) ); Thread groupListener = new Thread( new GroupListener(this) ); udpListener.start(); groupListener.start(); this.timer.start(); } @Override public void run() { long start = System.currentTimeMillis(); while ( System.currentTimeMillis() <= start + 10000L) { this.udpClient.broadcast("START:" + Integer.toString( this.getProcessNumber() ) + "," + this.udpPort() ); } HttpServer httpServer; try { httpServer = HttpServer.create(new InetSocketAddress(this.getHttpPort()),0); httpServer.createContext("/message", new MessageCommand(this)); httpServer.setExecutor(null); httpServer.start(); System.out.println("Process " + this.processNumber + " initiated"); } catch (IOException | NullPointerException e) { e.printStackTrace(); } } public boolean doIWantToEnterCriticalRegion() { return this.iWantToEnterCriticalRegion; } public void setiWantToEnterCriticalRegion(boolean iWantToEnterCriticalRegion) { this.iWantToEnterCriticalRegion = iWantToEnterCriticalRegion; } public boolean amIAtCriticalRegion() { return this.imAtCriticalRegion; } public void setImAtCriticalRegion(boolean imAtCriticalRegion) { this.imAtCriticalRegion = imAtCriticalRegion; } public Queue<Map<String,Integer>> getReqList() { return this.reqList; } public void resetReqList() { this.reqList = new LinkedList<>(); } public List<Integer> getProcessesPorts() { return this.processesPorts; } public Timer getTimer() { return this.timer; } private int getHttpPort(){ switch (this.processNumber) { case 1: return 8000; case 2: return 8001; case 3: return 8002; default: System.out.println("Erro ao definir a porta"); System.exit(0); return -1; } } public int getProcessNumber(){ return this.processNumber; } private void delay(long seconds){ try { TimeUnit.SECONDS.sleep(seconds); } catch (InterruptedException e) { e.printStackTrace(); } } private int udpPort(){ return this.processNumber == 1 ? 9876 : this.processNumber == 2 ? 9877 : 9878; } public void addClientsReady() { this.clientsReady++; } public boolean checkForOtherNodes(){ UDPClient udp = new UDPClient(); udp.setTimeout(5000); int responseNumber = 0; for(int port : this.getProcessesPorts()) { udp.send("PING", port); String response = udp.receive(); if(response == null) { return false; } responseNumber++; } return responseNumber >= BasicConfig.NUMBER_OF_NODES - 1; } }
package com.smxknife.drools.demo02.service; import com.smxknife.drools.demo02.model.PromoteExecute; import org.springframework.stereotype.Service; /** * 规则库生成 * @author smxknife * 2020/6/15 */ @Service public class PromoteNeaten { public PromoteExecute editRule(String rule) throws RuntimeException { PromoteExecute promoteExecute = new PromoteExecute(); promoteExecute.setWorkContent(rule); // 促销业务规则 // 规则库 初始化 promoteExecute.getWorkSession(); return promoteExecute; } }
package me.ljseokd.basicboard.modules.notification; import lombok.Getter; import lombok.NoArgsConstructor; import me.ljseokd.basicboard.modules.account.Account; import org.springframework.data.annotation.CreatedDate; import javax.persistence.*; import java.time.LocalDateTime; import static javax.persistence.FetchType.LAZY; import static lombok.AccessLevel.PROTECTED; @Entity @Getter @NoArgsConstructor(access = PROTECTED) public class Notification { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) @Column(name = "notification_id") private Long id; private String title; private String message; @CreatedDate @Column(updatable = false) private LocalDateTime createdDateTime; private boolean checked; @ManyToOne(fetch = LAZY) @JoinColumn(name = "account_id") private Account account; @PrePersist private void prePersist(){ LocalDateTime now = LocalDateTime.now(); createdDateTime = now; } public Notification(String title, String message, Account account) { this.title = title; this.message = message; this.account = account; this.account.addNotification(this); } }
/** * Author: obullxl@gmail.com * Copyright (c) 2004-2014 All Rights Reserved. */ package com.github.obullxl.lang.storex; import java.io.File; import com.github.obullxl.lang.storex.impl.JSSStoreX; /** * 京东云测试 * * @author obullxl@gmail.com * @version $Id: JSSStoreXMain.java, V1.0.1 2014年6月13日 下午9:25:03 $ */ public class JSSStoreXMain { /** * @param args */ public static void main(String[] args) { JSSStoreX store = new JSSStoreX(); store.setBucket("azdai"); store.setAccessId("831835cde8d445f6a1157671f8d6893e"); store.setAccessKey("3cc9c8cbabcf49ab9ee66ccb8b250c57GrqAR2g1"); store.init(); // 上传文件 store.store(new File("c:/azdai.db"), "public/azdai.db"); store.destroy(); } }
package com.survey.search; import com.survey.model.Survey; public interface SurveySearcher { public InformationOnSurveys search(String subject); public void add(Survey survey); }
package com.smxknife.java2.jvm.refference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.concurrent.TimeUnit; /** * @author smxknife * 2019/9/5 */ public class WeakReferenceDemo { public static void main(String[] args) throws InterruptedException { // 垃圾回收时会回收。不过由于垃圾回收器是一个优先级低的线程,因此不一定会很快发现那些只有若引用的对象 WeakReference<String> weakReference = new WeakReference<>("Hello"); System.out.println("WeakReference-1 : " + weakReference.get()); ReferenceQueue<String> referenceQueue = new ReferenceQueue<>(); Reference rr = null; while ((rr = referenceQueue.poll()) != null) { System.out.println("queue: " + rr.get()); } WeakReference<String> weakReference2 = new WeakReference<>("Test", referenceQueue); System.out.println("WeakReference-2 : " + weakReference2.get()); // 由于这里调用System.gc,一直没有执行,所以下面的效果模拟不好 // System.gc(); // Runtime.getRuntime().freeMemory(); // System.gc(); System.out.println("after gc..."); TimeUnit.SECONDS.sleep(5); System.out.println("Weak...1 : " + weakReference.get()); System.out.println("Weak...2 : " + weakReference2.get()); while ((rr = referenceQueue.poll()) != null) { System.out.println("queue: " + rr.get()); } } }
package maxzonov.shareloc; import android.app.Application; import android.content.Context; import maxzonov.shareloc.di.component.AppComponent; import maxzonov.shareloc.di.component.DaggerAppComponent; import maxzonov.shareloc.di.module.AppModule; import maxzonov.shareloc.utils.LocaleManager; public class App extends Application { private AppComponent appComponent; private static final String DEFAULT_LANGUAGE_RU = "ru"; public static AppComponent getAppComponent(Context context) { return ((App) context.getApplicationContext()).appComponent; } /** * Sets the persisted language */ @Override protected void attachBaseContext(Context context) { super.attachBaseContext(LocaleManager .onAttach(context, DEFAULT_LANGUAGE_RU)); } @Override public void onCreate() { super.onCreate(); appComponent = DaggerAppComponent.builder() .appModule(new AppModule(this)) .build(); } }
package stringPractice; public class CountAndSay { public static void main(String[] args) { System.out.println(countAndSayMod(4)); } static String countAndSay(int n) { if (n == 1) { return "1"; } if (n == 2) { return "11"; } String s = "11"; for (int i = 3; i <= n; i++) { String t = ""; // Not sure why add this at the last of the string s = s + "&"; int count = 1; for (int j = 1; j < s.length(); j++) { if (s.charAt(j) != s.charAt(j - 1)) { t = t + Integer.toString(count); t = t + s.charAt(j - 1); count = 1; } else { count++; } } s = t; } return s; } static String countAndSayMod(int n) { String s = "1"; for (int i = 1; i < n; i++) { s = countIndex(s); } return s; } static String countIndex(String s) { char c = s.charAt(0); int count = 1; String sb = ""; for (int i = 1; i < s.length(); i++) { if (s.charAt(i) == c) { count++; } else { sb += Integer.toString(count); sb += c; c = s.charAt(i); count = 1; } } sb += Integer.toString(count); sb += c; return sb; } }
public class Test { public static void main(String[] args) { String str = new String("Welcome to java course"); System.out.print("Return value: "); System.out.println(str.substring(11)); } }
/*You have to enter information about your birthday. */ import java.text.SimpleDateFormat;//library for date format determin. import java.util.Date;// library for Date objects creation import java.util.Scanner;// import the class in order to enter information from the keyboard public class MyAge { public static void main(String[] args) { SimpleDateFormat dateFormat = new SimpleDateFormat ("dd.MM.yyyy"); Date currentDate = new Date(); Date birthDate = new Date(); Scanner sc = new Scanner(System.in); System.out.println("Enter your date of birth: "); String date = sc.nextLine(); try { birthDate = dateFormat.parse(date); } catch (Exception var12) { System.out.println("Mistake, please enter data in (\"dd.MM.yyyy\") format"); } System.out.println(date); long current = currentDate.getTime(); long fullTime = birthDate.getTime(); long lifeTime = current - fullTime; System.out.println("__________________________"); System.out.println("___________________________"); System.out.printf("You've lived " + lifeTime / 1000L / 60L / 60L / 24L / 365L + "years!\n"); System.out.printf("You've lived " + lifeTime / 1000L / 60L / 60L / 24L + "days!\n"); System.out.printf("You've lived " + lifeTime / 1000L / 60L / 60L + "hours!\n"); System.out.printf("You've lived " + lifeTime / 1000L / 60L + "minutes!\n"); System.out.printf("You've lived " + lifeTime / 1000L + "seconds!\n"); System.out.printf("You've lived " + lifeTime + "milliseconds!\n"); System.out.println("__________________________"); System.out.println("___________________________"); } }
package com.tencent.mm.plugin.talkroom.model; import com.tencent.mm.plugin.talkroom.model.g.2; class g$2$1 implements Runnable { final /* synthetic */ 2 oxl; g$2$1(2 2) { this.oxl = 2; } public final void run() { g.c(this.oxl.oxj); } }
/** * DNet eBusiness Suite * Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package net.nan21.dnet.module.bd.presenter.impl.uom.model; import net.nan21.dnet.core.api.annotation.Ds; import net.nan21.dnet.core.api.annotation.SortField; import net.nan21.dnet.core.presenter.model.AbstractTypeWithCodeLov; import net.nan21.dnet.module.bd.domain.impl.uom.UomType; @Ds(entity = UomType.class, sort = {@SortField(field = UomTypeLov_Ds.f_code)}) public class UomTypeLov_Ds extends AbstractTypeWithCodeLov<UomType> { public UomTypeLov_Ds() { super(); } public UomTypeLov_Ds(UomType e) { super(e); } }
package com.tencent.mm.plugin.card.model; import com.tencent.mm.g.a.nz; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.x; class am$4 extends c<nz> { final /* synthetic */ am hxV; am$4(am amVar) { this.hxV = amVar; this.sFo = nz.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { x.i("MicroMsg.SubCoreCard.ResetCardRetryCounter", "deal with reset card retry counter event"); al axj = am.axj(); x.d("MicroMsg.PendingCardIdInfoStorage", "resetRetryCounter"); axj.diF.fV("PendingCardId", "update PendingCardId set retryCount = 0 where retryCount >= 10"); return false; } }
package com.sinata.rwxchina.basiclib.payment.entity; import java.util.List; /** * @author HRR * @datetime 2018/1/5 * @describe 优惠券,积分,余额抵扣信息实体类 * @modifyRecord */ public class DeductibleEntity { /** * coupon : {"count":4,"list":[{"couponid":"2","money":"5","coupon_name":"测试礼包","coupon_describe":"测试\r\ncdcdcdcd\r\ncdcd","end_time":"2026-03-24"},{"couponid":"2","money":"5","coupon_name":"测试礼包","coupon_describe":"测试\r\ncdcdcdcd\r\ncdcd","end_time":"2026-03-24"},{"couponid":"2","money":"5","coupon_name":"测试礼包","coupon_describe":"测试\r\ncdcdcdcd\r\ncdcd","end_time":"2026-03-24"},{"couponid":"2","money":"5","coupon_name":"测试礼包","coupon_describe":"测试\r\ncdcdcdcd\r\ncdcd","end_time":"2026-03-24"}]} * integral : 10000000 * money : 10000000.00 */ private CouponBean coupon; private String integral; private String money; private String integral_deduction; public CouponBean getCoupon() { return coupon; } public void setCoupon(CouponBean coupon) { this.coupon = coupon; } public String getIntegral() { return integral; } public void setIntegral(String integral) { this.integral = integral; } public String getMoney() { return money; } public void setMoney(String money) { this.money = money; } public String getIntegral_deduction() { return integral_deduction; } public void setIntegral_deduction(String integral_deduction) { this.integral_deduction = integral_deduction; } public static class CouponBean { /** * count : 4 * list : [{"couponid":"2","money":"5","coupon_name":"测试礼包","coupon_describe":"测试\r\ncdcdcdcd\r\ncdcd","end_time":"2026-03-24"},{"couponid":"2","money":"5","coupon_name":"测试礼包","coupon_describe":"测试\r\ncdcdcdcd\r\ncdcd","end_time":"2026-03-24"},{"couponid":"2","money":"5","coupon_name":"测试礼包","coupon_describe":"测试\r\ncdcdcdcd\r\ncdcd","end_time":"2026-03-24"},{"couponid":"2","money":"5","coupon_name":"测试礼包","coupon_describe":"测试\r\ncdcdcdcd\r\ncdcd","end_time":"2026-03-24"}] */ private int count; private List<CouponEntity> list; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public List<CouponEntity> getList() { return list; } public void setList(List<CouponEntity> list) { this.list = list; } } }
package com.example.cj.perfectj.controller; import java.net.InetAddress; import java.net.UnknownHostException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.example.cj.perfectj.tool.Response; import com.example.cj.perfectj.tool.ResponseUtil; import com.example.cj.perfectstarter.HandsomeService; /** * Created on 2020-04-17 */ @RestController public class HandsomeController { @Autowired private HandsomeService handsomeService; @GetMapping("/handsome") public Response handsome() { return ResponseUtil.buildSuccess(handsomeService.getInfo()); } @GetMapping("") public Response index() throws UnknownHostException { InetAddress addr = InetAddress.getLocalHost(); return ResponseUtil.buildSuccess(addr.getHostName() + ": " + addr.getHostAddress()); } }
package com.jayqqaa12.mobilesafe.ui.space.lost; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.LinearLayout; import com.jayqqaa12.abase.annotation.view.FindEngine; import com.jayqqaa12.abase.annotation.view.FindView; import com.jayqqaa12.abase.core.activity.AbaseGestureActivity; import com.jayqqaa12.mobilesafe.R; import com.jayqqaa12.mobilesafe.engine.space.lost.LostEngine; public class SetupGuide2Activity extends AbaseGestureActivity { private static final String TAG ="SetupGudie2Activity"; @FindView(id = R.id.lost_guide2_ll,gesture=true) private LinearLayout ll; @FindView(id = R.id.lost_guide2_bt_bind,click=true) private Button bt_bind; @FindView(id = R.id.lost_guide2_cb_bind) private CheckBox cb_bind; @FindEngine private LostEngine engine; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_guide2); // change activity setChangeActivity(this, SetupGuide1Activity.class, SetupGuide3Activity.class); } @Override protected void onResume() { super.onResume(); // init view context initViewContext(); } private void initViewContext() { Log.i(TAG,"bind states is " +engine.isSimBind()); if (engine.isSimBind()) { bt_bind.setText(getString(R.string.lost_lable_guide2_off_bind)); cb_bind.setText(getString(R.string.lost_lable_guide2_already_bind)); cb_bind.setChecked(true); } else { bt_bind.setText(getString(R.string.lost_lable_guide2_on_bind)); cb_bind.setText(getString(R.string.lost_lable_guide2_unbind)); cb_bind.setChecked(false); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.lost_guide2_bt_bind: if (!engine.isSimBind()) { Log.i(TAG,"bind"); engine.setSimBind(true); } else { Log.i(TAG,"relieve bind"); engine.setSimBind(false); } initViewContext(); break; default: break; } } }
package javax.microedition.location; /** * The LocationException is thrown when a location API specific error has occurred. The detailed conditions when this exception is thrown are documented in the methods that throw this exception. */ public class LocationException extends java.lang.Exception{ /** * */ private static final long serialVersionUID = 6446593056960983840L; /** * Constructs a LocationException with no detail message. */ public LocationException(){ //TODO codavaj!! } /** * Constructs a LocationException with the specified detail message. * s - the detail message */ public LocationException(java.lang.String s){ super(s); } }
package main.java.Client; import main.java.Client.Views.GameView; import main.java.Protocol.BoardPacket; import main.java.Protocol.GameStatus; import main.java.Protocol.Message; import main.java.Protocol.Packet; import java.io.IOException; import java.io.ObjectInputStream; public class Listener implements Runnable { private GameView gameView; private ObjectInputStream in; private boolean listening; public Listener(GameView gameView, ObjectInputStream in) { this.gameView = gameView; this.in = in; } @Override public void run() { listening = true; while (listening) { try { Packet res = (Packet) in.readObject(); if(res instanceof BoardPacket) { gameView.displayBoard((BoardPacket) res); } else if (res instanceof Message) { gameView.displayMessage((Message) res); } else if (res instanceof GameStatus) { gameView.displayGameStatus((GameStatus) res); } System.out.println(res + " received " + in + "."); } catch (ClassNotFoundException | IOException e) { e.printStackTrace(); listening = false; } } } }
package classes; import java.security.NoSuchAlgorithmException; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import utils.Functions; import com.example.medicalprocess.MainActivity; public class Utilisateur { private int uid; private String nom; private String prenom; private String password; private String email; private Entite entite; private Fonction fonction; private boolean valide; private boolean webmaster; public Utilisateur(ResultSet rs) throws SQLException { uid=rs.getInt("uid"); nom=rs.getString("nom"); prenom=rs.getString("prenom"); password=rs.getString("password"); email=rs.getString("email"); entite=Entite.getByEid(rs.getInt("numeroEntite")); fonction=Fonction.getByNumero(rs.getInt("numeroFonction")); if(rs.getInt("valide")==1) valide=true; else valide=false; if(rs.getInt("webmaster")==1) webmaster=true; else webmaster=false; } public boolean isValide() { return valide; } public void setValide(boolean valide) { this.valide = valide; } public boolean isWebmaster() { return webmaster; } public void setWebmaster(boolean webmaster) { this.webmaster = webmaster; } public static Utilisateur add(String nom, String prenom, String password, String email, int entite, int fonction) throws SQLException, NoSuchAlgorithmException { Statement statement = MainActivity.connexion.createStatement(); statement.executeUpdate("INSERT INTO Utilisateurs SET nom = '"+nom+"' , prenom = '"+prenom+"' , email = '"+email+"' , password = '"+Functions.hash(password)+"' , numeroEntite = "+entite+" , numeroFonction = "+fonction+" , valide=0"); return getByEmail(email); } public int getUid() { return this.uid; } public void setUid(int uid) { this.uid = uid; } public String getNom() { return this.nom; } public void setNom(String nom) { this.nom = nom; } public String getPrenom() { return this.prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public Entite getEntite() { return this.entite; } public void setEntite(Entite entite) { this.entite = entite; } public Fonction getFonction() { return this.fonction; } public void setFonction(Fonction fonction) { this.fonction = fonction; } public static Utilisateur getByUid(int uid) throws SQLException { Statement statement = MainActivity.connexion.createStatement(); ResultSet rs = statement.executeQuery("SELECT * FROM Utilisateurs WHERE uid = '"+uid+"'"); if(rs.next()) return new Utilisateur(rs); return null; } public static Utilisateur getByEmail(String email) throws SQLException { Statement statement = MainActivity.connexion.createStatement(); ResultSet rs = statement.executeQuery("SELECT * FROM Utilisateurs WHERE email = '"+email+"'"); if(rs.next()) return new Utilisateur(rs); return null; } public void refresh() throws SQLException { Utilisateur user = Utilisateur.getByUid(uid); uid=user.getUid(); nom=user.getNom(); prenom=user.getPrenom(); password=user.getPassword(); email=user.getEmail(); entite=user.getEntite(); fonction=user.getFonction(); valide=user.isValide(); webmaster=user.isWebmaster(); } public static List<Utilisateur> listAllPerFonctionPerEntite(Fonction fonction,Entite entite) { List<Utilisateur> list = new ArrayList<Utilisateur>(); Statement statement; ResultSet rs; try { statement = MainActivity.connexion.createStatement(); int fonctionNum = fonction.getNumero(); int entiteNum = entite.getNature().getNumero(); rs = statement.executeQuery("SELECT * FROM Utilisateurs WHERE numeroEntite='"+entiteNum+"' AND numeroFonction='"+fonctionNum+"'"); while(rs.next()) list.add(new Utilisateur(rs)); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return list; } public String toString() { return nom+" "+prenom+" "+uid; } }
package pe.com.entel.sincrespago.mapper; import oracle.sql.STRUCT; import oracle.sql.StructDescriptor; import org.apache.log4j.Logger; import org.springframework.data.jdbc.support.oracle.StructMapper; import pe.com.entel.sincrespago.domain.ItemOrdenVep; import java.sql.Connection; import java.sql.SQLException; import java.util.Arrays; /** * Created by Erika Rumiche on 22/09/2018. */ public class ItemOrdenVepMapper implements StructMapper<ItemOrdenVep> { private static Logger logger = Logger.getLogger(ItemOrdenVepMapper.class); public STRUCT toStruct(ItemOrdenVep source, Connection conn, String typeName) throws SQLException { StructDescriptor descriptor = new StructDescriptor(typeName, conn); Object[] values = new Object[5]; values[0] = source.getOrdenId(); values[1] = source.getClienteCrmId(); values[2] = source.getSiteId(); values[3] = source.getSimNumber(); values[4] = source.getOvepId(); return new STRUCT(descriptor, conn, values); } public ItemOrdenVep fromStruct(STRUCT struct) throws SQLException { ItemOrdenVep dest = new ItemOrdenVep(); Object[] attributes = struct.getAttributes(); //logger.debug("ItemOrdenVepMapper.fromStruct : " + Arrays.toString(attributes)); dest.setOrdenId(Long.valueOf(((Number) attributes[0]).longValue())); dest.setClienteCrmId(Long.valueOf(((Number) attributes[1]).longValue())); dest.setSiteId(Long.valueOf(((Number) attributes[2]).longValue())); dest.setSimNumber(String.valueOf(attributes[3])); dest.setOvepId(Long.valueOf(((Number) attributes[4]).longValue())); return dest; } }
package com.zhouyi.business.core.exception; /** * @author 李秸康 * @ClassNmae: FileuploadException * @Description: TODO 文件上传异常 * @date 2019/7/24 15:22 * @Version 1.0 **/ public class FileuploadException extends RuntimeException { public FileuploadException(String message) { super(message); } }
package com.tencent.mm.plugin.wallet_payu.pay.ui; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import com.tencent.mm.wallet_core.a; class WalletPayUOrderInfoUI$1 implements OnClickListener { final /* synthetic */ WalletPayUOrderInfoUI pFz; WalletPayUOrderInfoUI$1(WalletPayUOrderInfoUI walletPayUOrderInfoUI) { this.pFz = walletPayUOrderInfoUI; } public final void onClick(DialogInterface dialogInterface, int i) { a.c(this.pFz, this.pFz.sy, 0); } }
package dir.gestionarcredenciales; import dir.gestionarcredenciales.forms.GestionarUsuariosRolesDialog; import dir.gestionarcredenciales.forms.LoginDialog; import dir.gestioncredenciales.modelo.Rol; import dir.gestioncredenciales.modelo.Usuario; import dir.gestioncredenciales.servicios.ServiciosLocator; public class Main { private Main(){} public static void main(String[] args) { Usuario user = new Usuario(); user.setId(1); user.setNombre("Oliver"); user.setPassword("43826914"); user.setBloqueado(false); user.setRol(new Rol()); user.getRol().setNombre("Administrador"); ServiciosLocator.getGestionarUsuarios().crearUsuario(user); LoginDialog l = new LoginDialog(); l.show(true); if(l.getValido()){ GestionarUsuariosRolesDialog g = new GestionarUsuariosRolesDialog(); g.show(true); } l.getDialog().dispose(); } }
package com.myproject.lab1.session; public class Icon { private String id; private Integer x; private Integer y; private String username; private String color; public Icon() { } public Icon(String id, Integer x, Integer y, String username, String color) { this.id = id; this.x = x; this.y = y; this.username = username; this.color = color; } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public Integer getX() { return this.x; } public void setX(Integer x) { this.x = x; } public Integer getY() { return this.y; } public void setY(Integer y) { this.y = y; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getColor() { return this.color; } public void setColor(String color) { this.color = color; } }
public class DemoLingkaran { public static void main(String[] args) { Lingkaran l1 = new Lingkaran(); l1.phi = 22.7; l1.r = 7; double luas = l1.hitungKeliling(); double keliling = l1.hitungLuas(); System.out.println("\n----------------------------"); System.out.println("Phi\t\t: " + l1.phi); System.out.println("Jari-jari\t: " + l1.r); System.out.println("----------------------------"); System.out.println("Luas lingkaran\t: " + luas); System.out.println("Luas keliling\t: " + keliling); System.out.println("----------------------------"); } }
package com.awrzosek.ski_station.database_management; import com.awrzosek.ski_station.tables.person.employee.Employee; import com.awrzosek.ski_station.tables.person.employee.EmployeeConsts; import com.awrzosek.ski_station.tables.person.employee.EmployeeDao; import java.sql.Connection; import java.sql.SQLException; public class EmployeeManager { private EmployeeDao employeeDao; //TODO jak starczy czasu to encrypting password - w database public EmployeeManager(Connection connection) { this.employeeDao = new EmployeeDao(connection); } public boolean add(Employee employee) throws SQLException { try { employeeDao.add(employee); return true; } catch (SQLException e) { if (e.getMessage().contains(EmployeeConsts.TAB_NAME + "." + EmployeeConsts.FLD_LOGIN)) return false; else throw e; } } //TODO metoda copiego paste'a public boolean edit(Employee employee) throws SQLException { try { employeeDao.update(employee); return true; } catch (SQLException e) { if (e.getMessage().contains(EmployeeConsts.TAB_NAME + "." + EmployeeConsts.FLD_LOGIN)) return false; else throw e; } } public boolean delete(Employee employee, Employee loggedInEmployee) throws SQLException { if (employee.getId().compareTo(loggedInEmployee.getId()) == 0) return false; employeeDao.delete(employee); return true; } public Employee authenticateLogin(String login, String password) throws SQLException { Employee employee = employeeDao.findByLogin(login).orElse(null); if (employee == null || (!employee.getPasswd().equals(password))) return null; return employee; } public EmployeeDao getEmployeeDao() { return employeeDao; } }
package com.tt.miniapp.msg.file; import com.a; import com.tt.frontendapiinterface.ApiCallResult; import com.tt.miniapp.msg.file.read.ApiReadFileCtrl; import com.tt.miniapp.msg.file.write.ApiWriteFileCtrl; import com.tt.miniapp.msg.sync.SyncMsgCtrl; import com.tt.miniapphost.AppBrandLogger; import org.json.JSONObject; public class FileSystemManagerSync extends SyncMsgCtrl { private String functionName; public FileSystemManagerSync(String paramString1, String paramString2) { super(paramString2); this.functionName = paramString1; } public String act() { byte b; ApiUnlinkCtrl apiUnlinkCtrl; ApiSaveFileCtrl apiSaveFileCtrl; ApiStatCtrl apiStatCtrl; ApiRmDirCtrl apiRmDirCtrl; ApiRenameCtrl apiRenameCtrl; ApiReadDirCtrl apiReadDirCtrl; ApiMkDirCtrl apiMkDirCtrl; ApiCopyFileCtrl apiCopyFileCtrl; ApiAccessCtrl apiAccessCtrl; ApiReadFileCtrl<String, ApiCallResult> apiReadFileCtrl; ApiCallResult apiCallResult; if (this.functionName.equals("protocolPathToAbsPath")) try { null = (new JSONObject(this.mParams)).optString("protocolPath"); JSONObject jSONObject = new JSONObject(); jSONObject.put("absPath", null); return makeOkMsg(jSONObject); } catch (Exception exception) { AppBrandLogger.e("FileSystemManagerSync", new Object[] { exception }); return makeFailMsg(exception); } ApiWriteFileCtrl apiWriteFileCtrl = null; String str = this.functionName; switch (str.hashCode()) { default: b = -1; break; case 2112368109: if (str.equals("readFileSync")) { b = 0; break; } case 1713034038: if (str.equals("writeFileSync")) { b = 10; break; } case 1431909580: if (str.equals("copyFileSync")) { b = 2; break; } case 1317686031: if (str.equals("statSync")) { b = 7; break; } case -271906454: if (str.equals("mkdirSync")) { b = 3; break; } case -734079374: if (str.equals("readdirSync")) { b = 4; break; } case -799949100: if (str.equals("saveFileSync")) { b = 8; break; } case -1142033889: if (str.equals("accessSync")) { b = 1; break; } case -1251412231: if (str.equals("renameSync")) { b = 5; break; } case -1528590803: if (str.equals("rmdirSync")) { b = 6; break; } case -1574561970: if (str.equals("unlinkSync")) { b = 9; break; } } switch (b) { case 10: apiWriteFileCtrl = new ApiWriteFileCtrl(this.functionName); break; case 9: apiUnlinkCtrl = new ApiUnlinkCtrl(this.functionName); break; case 8: apiSaveFileCtrl = new ApiSaveFileCtrl(this.functionName); break; case 7: apiStatCtrl = new ApiStatCtrl(this.functionName); break; case 6: apiRmDirCtrl = new ApiRmDirCtrl(this.functionName); break; case 5: apiRenameCtrl = new ApiRenameCtrl(this.functionName); break; case 4: apiReadDirCtrl = new ApiReadDirCtrl(this.functionName); break; case 3: apiMkDirCtrl = new ApiMkDirCtrl(this.functionName); break; case 2: apiCopyFileCtrl = new ApiCopyFileCtrl(this.functionName); break; case 1: apiAccessCtrl = new ApiAccessCtrl(this.functionName); break; case 0: apiReadFileCtrl = new ApiReadFileCtrl(this.functionName); break; } if (apiReadFileCtrl != null) { apiCallResult = apiReadFileCtrl.invoke(this.mParams); } else { String str1 = a.a("api is not supported in app: %s", new Object[] { this.functionName }); AppBrandLogger.e("FileSystemManagerSync", new Object[] { str1 }); apiCallResult = ApiCallResult.a.b(this.functionName).d(str1).a(); } return apiCallResult.toString(); } public String getName() { return this.functionName; } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\msg\file\FileSystemManagerSync.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
import java.awt.*; import java.awt.event.*; class Mypanel1 extends Panel implements ItemListener { Checkbox box1, box2, box3; CheckboxGroup sex; TextArea text; Mypanel1(TextArea text) { this.text = text; sex = new CheckboxGroup(); box1 = new Checkbox("男", true, sex); box2 = new Checkbox("女", false, sex); box1.addItemListener(this); box2.addItemListener(this); add(box1); add(box2); } public void itemStateChanged(ItemEvent e) { Checkbox box = (Checkbox) e.getSource(); if (box.getState()) { int n = text.getCaretPosition(); text.insert(box.getLabel(), n); } } } class Mypanel2 extends Panel implements ItemListener { Checkbox box1, box2, box3; TextArea text; Mypanel2(TextArea text) { this.text = text; box1 = new Checkbox("张三"); box2 = new Checkbox("李四"); box1.addItemListener(this); box2.addItemListener(this); add(box1); add(box2); } public void itemStateChanged(ItemEvent e) { Checkbox box = (Checkbox) e.getItemSelectable(); if (box.getState()) { int n = text.getCaretPosition(); text.insert(box.getLabel(), n); } } } class WindowBox extends Frame { Mypanel1 panel1; Mypanel2 panel2; TextArea text; WindowBox() { text = new TextArea(); panel1 = new Mypanel1(text); panel2 = new Mypanel2(text); add(panel1, BorderLayout.SOUTH); add(panel2, BorderLayout.NORTH); add(text, BorderLayout.CENTER); setSize(200, 200); setVisible(true); validate(); } } public class ep6_16 { public static void main(String args[]) { new WindowBox(); } }
package gui; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import java.awt.Component; import java.awt.Dimension; import java.awt.GridLayout; import java.util.Vector; import java.util.Map; import java.util.HashMap; import xml.Gruppierung; import xml.Mannschaft; /** * Write a description of class JTableGruppierung here. * * @author (your name) * @version (a version number or a date) */ public class JTableGruppierung extends AbstractTableModel { /** * Constructor for objects of class JTableGruppierung */ public JTableGruppierung(Vector<Gruppierung> data, Map<String, Mannschaft> mannMap) { this.data = data; this.mannMap = mannMap; } private String[] columnNames = {"Datum", "Zeit", "Feld", "Geschlecht", "Schule", "Mannschaft", "Mannschaft", "Schule", "Geschlecht"}; private Vector<Gruppierung> data = new Vector(); private Map<String, Mannschaft> mannMap = new HashMap(); public final Object[] longValues = {"Jane", "Kathy", "None of the above", new Integer(20), Boolean.TRUE}; public int getColumnCount() { return columnNames.length; } public int getRowCount() { return data.size(); } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { Gruppierung grupp = data.elementAt(row); Mannschaft mann1 = mannMap.get(grupp.getMannschaftID1()); Mannschaft mann2 = mannMap.get(grupp.getMannschaftID2()); switch(col){ case 0: return grupp.getDatum(); case 1: return grupp.getZeit(); case 2: return grupp.getFeld(); case 3: return grupp.getKlasse(); case 4: return grupp.getTeam(); case 5: return grupp.getGruppe(); case 6: return grupp.getGruppe(); case 7: return grupp.getGruppe(); case 8: return grupp.getGruppe(); } return "Fehler"; } /* * JTable uses this method to determine the default renderer/ * editor for each cell. If we didn't implement this method, * then the last column would contain text ("true"/"false"), * rather than a check box. */ public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } /* * Don't need to implement this method unless your table's * editable. */ public boolean isCellEditable(int row, int col) { return true; } /* * Don't need to implement this method unless your table's * data can change. */ public void setValueAt(Object value, int row, int col) { if (true) { System.out.println("Setting value at " + row + "," + col + " to " + value + " (an instance of " + value.getClass() + ")"); } Mannschaft mann = data.elementAt(row); String val = (String)value; switch(col){ case 0: mann.setGeschlecht(val); break; case 1: mann.setSchule(val); break; case 2: mann.setName(val); break; case 3: mann.setKlasse(Integer.parseInt(val)); break; case 4: mann.setTeam(Integer.parseInt(val)); break; case 5: mann.setGruppe(Integer.parseInt(val)); break; } fireTableCellUpdated(row, col); } }
/* * Minesweeper Project * by Group3 : Arnaud BABOL, Guillaume SIMMONEAU */ package Model.Events; import Model.Model; /** * * @author nono */ public class ChronometerEvent extends RefreshEvent { private String time; /** * * @param source * @param time */ public ChronometerEvent(Model source, int time) { super(source); this.time = "Time : "+getMin(time)+":"+getSecs(time); } /** * * @return */ public String getTime() { return this.time; } private int getMin(int time) { return time/60; } private int getSecs(int time) { return time%60; } }
package com.h86355.tastyrecipe.fragments; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.widget.SearchView; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.StaggeredGridLayoutManager; import com.h86355.tastyrecipe.R; import com.h86355.tastyrecipe.adapters.ISearchListener; import com.h86355.tastyrecipe.adapters.SearchAdapter; import com.h86355.tastyrecipe.databinding.FragmentSearchBinding; import com.h86355.tastyrecipe.models.RecipeCollection; import com.h86355.tastyrecipe.utils.SearchTags; import com.h86355.tastyrecipe.viewmodels.DetailFragmentViewModel; import com.h86355.tastyrecipe.viewmodels.MainFragmentViewModel; import java.util.List; import co.lujun.androidtagview.TagView; public class SearchFragment extends Fragment implements ISearchListener { private static final String TAG = "SEARCH_FRAGMENT"; private FragmentSearchBinding binding; private SearchAdapter searchAdapter; private MainFragmentViewModel mainFragmentViewModel; private DetailFragmentViewModel detailFragmentViewModel; private boolean isQueryForMore; private int fromPage = 0; private String searchQuery = ""; private String searchTag = ""; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = FragmentSearchBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mainFragmentViewModel = new ViewModelProvider(requireActivity()).get(MainFragmentViewModel.class); detailFragmentViewModel = new ViewModelProvider(requireActivity()).get(DetailFragmentViewModel.class); subscribeObserver(); initSearchView(); initTags(); initRecyclerView(); handleClick(); } private void handleClick() { binding.searchBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (binding.searchView.isFocused()) { binding.searchView.clearFocus(); } getFragmentManager().popBackStack(); } }); } private void subscribeObserver() { mainFragmentViewModel.getSearchRecipes().observe(getViewLifecycleOwner(), new Observer<List<RecipeCollection>>() { @Override public void onChanged(List<RecipeCollection> recipeCollections) { if (recipeCollections == null) { Log.d(TAG, "onChanged: null recipes"); if (searchAdapter.getItemViewType(0) != SearchAdapter.ERROR) { binding.tagView.setVisibility(View.GONE); binding.searchRv.setVisibility(View.VISIBLE); searchAdapter.displayError(); } if (binding.animationView.getVisibility() == View.VISIBLE) { binding.animationView.setAnimation(R.raw.empty); } } else { Log.d(TAG, "onChanged: not null recipes"); if (isQueryForMore) { binding.animationView.setVisibility(View.GONE); searchAdapter.addSearchResults(recipeCollections); if (binding.animationView.getVisibility() == View.VISIBLE) { binding.animationView.setVisibility(View.GONE); } } else { searchAdapter.setSearchResults(recipeCollections); } } } }); } private void initRecyclerView() { searchAdapter = new SearchAdapter(getActivity(), this); binding.searchRv.setAdapter(searchAdapter); binding.searchRv.setLayoutManager(new LinearLayoutManager(getActivity(), RecyclerView.VERTICAL, false)); binding.searchRv.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (!recyclerView.canScrollVertically(1) && newState==RecyclerView.SCROLL_STATE_IDLE) { if (binding.animationView.getVisibility() != View.VISIBLE) { fromPage += 10; mainFragmentViewModel.getSearchRecipesAPI(fromPage, 10, searchQuery, searchTag); binding.animationView.setVisibility(View.VISIBLE); isQueryForMore = true; } } if (newState == RecyclerView.SCROLL_STATE_DRAGGING) { binding.animationView.setVisibility(View.GONE); } } }); } private void initSearchView() { binding.searchView.setFocusable(true); binding.searchView.setIconified(false); binding.searchView.requestFocusFromTouch(); binding.searchView.setOnCloseListener(new SearchView.OnCloseListener() { @Override public boolean onClose() { binding.searchView.setQueryHint("Search"); binding.searchRv.setVisibility(View.INVISIBLE); binding.tagView.setVisibility(View.VISIBLE); return true; } }); binding.searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { binding.searchView.setQueryHint(query); binding.tagView.setVisibility(View.GONE); binding.searchRv.setVisibility(View.VISIBLE); searchAdapter.displayLoading(); mainFragmentViewModel.getSearchRecipesAPI(0, 10, query, ""); searchQuery = query; return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); } private void initTags() { binding.tagView.setTags(SearchTags.getTags()); binding.tagView.setOnTagClickListener(new TagView.OnTagClickListener() { @Override public void onTagClick(int position, String text) { binding.searchView.setQueryHint(text); binding.searchView.clearFocus(); binding.searchRv.setVisibility(View.VISIBLE); binding.tagView.setVisibility(View.GONE); searchAdapter.displayLoading(); mainFragmentViewModel.getSearchRecipesAPI(0, 10, "", text); searchTag = text; } @Override public void onTagLongClick(int position, String text) { } @Override public void onSelectedTagDrag(int position, String text) { } @Override public void onTagCrossClick(int position) { } }); } @Override public void onDestroyView() { super.onDestroyView(); binding = null; } @Override public void onItemClick(int position) { RecipeCollection recipeCollection = searchAdapter.getSelectedRecipe(position); detailFragmentViewModel.setSelectedRecipeCollection(recipeCollection); if (recipeCollection.getRecipes() == null) { getFragmentManager() .beginTransaction() .setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right) .replace(R.id.layout_main_container, new DetailFragment()) .addToBackStack(null) .commit(); } else { getFragmentManager() .beginTransaction() .setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right) .replace(R.id.layout_main_container, new RecipeListFragment(), getString(R.string.fragment_recipes_tag)) .addToBackStack(getString(R.string.fragment_recipes_tag)) .commit(); } } }
package k2.exception; public class CantDrawCardsTwiceInTheSameTurnException extends Exception { }
/* * Sonar PHP Plugin * Copyright (C) 2010 Sonar PHP Plugin * dev@sonar.codehaus.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.plugins.php.phpdepend; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.CoreProperties.PROJECT_EXCLUSIONS_PROPERTY; import static org.sonar.plugins.php.MockUtils.getFile; import static org.sonar.plugins.php.MockUtils.getMockProject; import static org.sonar.plugins.php.core.PhpPlugin.FILE_SUFFIXES_KEY; import static org.sonar.plugins.php.phpdepend.PhpDependConfiguration.PDEPEND_IGNORE_KEY; import java.io.File; import java.util.Arrays; import java.util.List; import org.apache.commons.configuration.Configuration; import org.apache.commons.lang.StringUtils; import org.junit.Test; import org.sonar.api.resources.Project; public class PhpDependExecutorTest { /** * Test method for {@link org.sonar.plugins.php.codesniffer.PhpCodeSnifferExecutor#getCommandLine()} . */ @Test public void testGetCommandLine1() { Configuration configuration = mock(Configuration.class); when(configuration.getStringArray(FILE_SUFFIXES_KEY)).thenReturn(null); Project project = getMockProject(); PhpDependConfiguration c = getWindowsConfiguration(project); PhpDependExecutor executor = new PhpDependExecutor(c); List<String> commandLine = executor.getCommandLine(); String s1 = "pdepend.bat"; String s2 = "--phpunit-xml=" + getFile("C:/projets/PHP/Monkey/target/logs/pdepend.xml"); String s3 = "--suffix=php,php3,php4,php5,phtml,inc"; String s4 = new File("C:/projets/PHP/Monkey/sources/main").toString(); List<String> expected = Arrays.asList(s1, s2, s3, s4); // assertThat(commandLine).isEqualTo(expected); } @Test public void testGetIgnoreDirsWithNotNullWithSonarExclusionNull() { Project project = getMockProject(); PhpDependConfiguration config = getWindowsConfiguration(project); Configuration c = project.getConfiguration(); when(config.isStringPropertySet(PDEPEND_IGNORE_KEY)).thenReturn(true); String pdependExclusionPattern = "Math,Math3*"; when(c.getStringArray(PDEPEND_IGNORE_KEY)).thenReturn(new String[] { pdependExclusionPattern }); when(c.getStringArray(PROJECT_EXCLUSIONS_PROPERTY)).thenReturn(null); assertThat(config.getIgnoreDirs()).isEqualTo(pdependExclusionPattern); PhpDependExecutor executor = new PhpDependExecutor(config); List<String> commandLine = executor.getCommandLine(); String s1 = "pdepend.bat"; String s2 = "--phpunit-xml=" + getFile("C:/projets/PHP/Monkey/target/logs/pdepend.xml"); String s3 = "--suffix=php,php3,php4,php5,phtml,inc"; String s4 = "--ignore=" + pdependExclusionPattern; String s5 = new File("C:/projets/PHP/Monkey/sources/main").toString(); List<String> expected = Arrays.asList(s1, s2, s3, s4, s5); assertThat(commandLine).isEqualTo(expected); } @Test public void testGetIgnoreDirsNullWithSonarExclusionNotNull() { Project project = getMockProject(); PhpDependConfiguration config = getWindowsConfiguration(project); Configuration c = project.getConfiguration(); when(config.isStringPropertySet(PDEPEND_IGNORE_KEY)).thenReturn(false); when(c.getStringArray(PDEPEND_IGNORE_KEY)).thenReturn(null); when(config.isStringPropertySet(PROJECT_EXCLUSIONS_PROPERTY)).thenReturn(true); String[] sonarExclusionPattern = { "*test", "**/math" }; when(c.getStringArray(PROJECT_EXCLUSIONS_PROPERTY)).thenReturn(sonarExclusionPattern); PhpDependExecutor executor = new PhpDependExecutor(config); List<String> commandLine = executor.getCommandLine(); String s1 = "pdepend.bat"; String s2 = "--phpunit-xml=" + getFile("C:/projets/PHP/Monkey/target/logs/pdepend.xml"); String s3 = "--suffix=php,php3,php4,php5,phtml,inc"; String s4 = "--ignore=" + StringUtils.join(sonarExclusionPattern, ","); String s5 = new File("C:/projets/PHP/Monkey/sources/main").toString(); List<String> expected = Arrays.asList(s1, s2, s3, s4, s5); assertThat(commandLine).isEqualTo(expected); } @Test public void testGetIgnoreDirsNotNullWithSonarExclusionNotNull() { Project project = getMockProject(); PhpDependConfiguration config = getWindowsConfiguration(project); Configuration c = project.getConfiguration(); when(config.isStringPropertySet(PDEPEND_IGNORE_KEY)).thenReturn(true); String[] pdependExclusionPattern = { "*Math4.php" }; when(c.getStringArray(PDEPEND_IGNORE_KEY)).thenReturn(pdependExclusionPattern); when(config.isStringPropertySet(PROJECT_EXCLUSIONS_PROPERTY)).thenReturn(true); String[] sonarExclusionPattern = { "sites/all/", "files", "*Math4.php" }; when(c.getStringArray(PROJECT_EXCLUSIONS_PROPERTY)).thenReturn(sonarExclusionPattern); PhpDependExecutor executor = new PhpDependExecutor(config); List<String> commandLine = executor.getCommandLine(); String s1 = "pdepend.bat"; String s2 = "--phpunit-xml=" + getFile("C:/projets/PHP/Monkey/target/logs/pdepend.xml"); String s3 = "--suffix=php,php3,php4,php5,phtml,inc"; String s4 = "--ignore=" + StringUtils.join(pdependExclusionPattern, ",") + "," + StringUtils.join(sonarExclusionPattern, ","); String s5 = new File("C:/projets/PHP/Monkey/sources/main").toString(); List<String> expected = Arrays.asList(s1, s2, s3, s4, s5); assertThat(commandLine).isEqualTo(expected); } /** * Gets the windows configuration. * * @return the windows configuration */ private PhpDependConfiguration getWindowsConfiguration(Project project) { return getConfiguration(project, true, ""); } /** * Gets the configuration. * * @param isOsWindows * the is os windows * @param path * the path * @return the configuration */ private PhpDependConfiguration getConfiguration(Project project, final boolean isOsWindows, final String path) { PhpDependConfiguration config = new PhpDependConfiguration(project) { @SuppressWarnings("unused") public String getCommandLinePath() { return path; } @Override public boolean isOsWindows() { return isOsWindows; } }; return config; } }
package com.tencent.mm.plugin.offline.a; import com.tencent.mm.compatible.e.q; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.offline.k; import com.tencent.mm.sdk.platformtools.ac; import com.tencent.mm.storage.aa.a; import com.tencent.mm.wallet_core.tenpay.model.i; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; public final class n extends i { public static String lJU = ""; public static String lKn = ""; private int hUm = -1; private String hUn = ""; public int lJK = -1; public String lJL = ""; public String lKo = ""; public String lKp = ""; public String lKq = ""; final Map<String, String> lKr = new HashMap(); public n(String str, int i) { this.lKr.put("device_id", q.zz()); this.lKr.put("timestamp", str); this.lKr.put("scene", String.valueOf(i)); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(q.zz()); stringBuilder.append("&"); stringBuilder.append(str); this.lKr.put("sign", ac.ce(stringBuilder.toString())); StringBuilder stringBuilder2 = new StringBuilder(); g.Ek(); this.lKr.put("code_ver", stringBuilder2.append(g.Ei().DT().get(a.sOz, "")).toString()); F(this.lKr); } public final int aBO() { return 49; } public final void a(int i, String str, JSONObject jSONObject) { if (jSONObject != null) { lJU = jSONObject.optString("limit_fee"); lKn = jSONObject.optString("is_show_order_detail"); String optString = jSONObject.optString("pay_amount"); String optString2 = jSONObject.optString("pay_number"); String optString3 = jSONObject.optString("card_logos"); k.bkO(); k.aw(196629, lJU); k.bkO(); k.aw(196641, lKn); k.bkO(); k.aw(196645, optString); k.bkO(); k.aw(196646, optString2); com.tencent.mm.plugin.offline.c.a.Je(optString3); this.hUm = jSONObject.optInt("retcode"); this.hUn = jSONObject.optString("retmsg"); this.lJK = jSONObject.optInt("wx_error_type"); this.lJL = jSONObject.optString("wx_error_msg"); this.lKo = jSONObject.optString("get_code_flag"); this.lKp = jSONObject.optString("micropay_pause_flag"); this.lKq = jSONObject.optString("micropay_pause_word"); } } public final int If() { return 568; } public final String getUri() { return "/cgi-bin/mmpay-bin/tenpay/offlinequeryuser"; } }
package com.gikk; import com.gikk.util.Log; import com.gikk.util.Scheduler; import com.gikk.util.SchedulerBuilder; import com.gikk.util.Touple; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Future; /** * * @author Gikkman */ public class SchedulerSingleton { /** * ************************************************************************* * VARIABLES ************************************************************************** */ private final Map<String, Runnable> permanentOnTick = new ConcurrentHashMap<>(); private final Scheduler scheduler; private Queue<Touple<String, Runnable>> queue = new ConcurrentLinkedQueue<>(); /** * ************************************************************************* * CONSTRUCTOR ************************************************************************* */ private SchedulerSingleton() { scheduler = new SchedulerBuilder(3).setThreadsPrefix("Scheduler-").setThreadsDaemon(true).build(); repeatedTask(1000, 1000, this::tickAction); } private static Runnable tryCatchWrap(Runnable task) { return () -> { try { task.run(); } catch (Throwable t) { Log.error("A scheduled runnable threw an uncaught exception", t); } }; } /** * Fetches the Chat singleton object * * @return the Chat */ public static SchedulerSingleton GET() { return INTERNAL.INSTANCE; } /** * ************************************************************************* * TASK MANAGEMENT ************************************************************************* */ public final Future executeTask(Runnable task) { if (scheduler.isDisposed()) { return null; } return scheduler.executeTask(tryCatchWrap(task)); } public final Future delayedTask(int delayMillis, Runnable task) { if (scheduler.isDisposed()) { return null; } return scheduler.scheduleDelayedTask(delayMillis, tryCatchWrap(task)); } /** * ************************************************************************* * TICK MANAGEMENT ************************************************************************* */ public final Future repeatedTask(int initialDelayMillis, int periodMillis, Runnable task) { if (scheduler.isDisposed()) { return null; } return scheduler.scheduleRepeatedTask(initialDelayMillis, periodMillis, tryCatchWrap(task)); } /** * Adds a runnable to the Tick-batch. Runnables in the Tick-batch are * executed every 1000 ms * * @param identifier name for the runnable * @param runnable the runnable */ public void addTick(String identifier, Runnable runnable) { queue.add(new Touple<>(identifier, runnable)); } /** * Removes a runnable to the Tick-batch. * * @param identifier name for the runnable */ public void removeTick(String identifier) { permanentOnTick.remove(identifier); } /** * ********************* * Singleton internals * ********************** */ private void tickAction() { Queue<Touple<String, Runnable>> oldQueue = queue; queue = new ConcurrentLinkedQueue<>(); Iterator<Entry<String, Runnable>> itr = permanentOnTick.entrySet().iterator(); while (itr.hasNext()) { Entry<String, Runnable> e = itr.next(); try { e.getValue().run(); } catch (Exception ex) { Log.error("A tick task has failed", e.getKey(), ex.getMessage()); } } for (Touple<String, Runnable> t : oldQueue) { permanentOnTick.put(t.left, t.right); } } static class INTERNAL { private static final SchedulerSingleton INSTANCE = new SchedulerSingleton(); static void INIT() { //Just to run the constructor } static void QUIT() { try { Thread.sleep(500); } catch (InterruptedException ignored) { } INSTANCE.scheduler.terminate(); } } }
package com.apprisingsoftware.util; public class Quadruplet<T, U, V, W> extends Triplet<T, U, V> { protected final W fourth; public Quadruplet(T first, U second, V third, W fourth) { super(first, second, third); this.fourth = fourth; } public W getFourth() { return fourth; } // Object @Override public String toString() { return String.format("<%s, %s, %s, %s>", first, second, third, fourth); } }
package admin; /** * * @author aeren */ public class Ogrenci { private int id; private String ad; private String soyad; private String bolum; public Ogrenci(int id, String ad, String soyad,String bolum) { this.id = id; this.ad = ad; this.soyad = soyad; this.bolum = bolum; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getAd() { return ad; } public void setAd(String ad) { this.ad = ad; } public String getSoyad() { return soyad; } public void setSoyad(String soyad) { this.soyad = soyad; } public String getBolum() { return bolum; } public void setBolum(String bolum) { this.bolum = bolum; } }
package ict.kosovo.growth.ora_6; public class InitArray { public static void main(String[] args) { // int[] numrat = new int[10]; // // System.out.printf("%s%8%n", "index", "Value"); // // for (int i = 0;i < numrat.length; i ++){ // System.out.println("%5d%8d%n", i, numrat[i]); } }
package com.twoyears44.myclass; import android.app.Application; import android.content.Context; /** * Created by twoyears44 on 16/4/27. */ public class BCApplication extends Application { private static Context context; @Override public void onCreate() { super.onCreate(); BCApplication.context = getApplicationContext(); } public static Context getContext() { return BCApplication.context; } }
package com.tantransh.workshopapp.requestlistener; import com.android.volley.VolleyError; import com.tantransh.workshopapp.jobbooking.data.CustomerInformation; public interface CustomerRequestListener { void addCustomer(CustomerInformation customerInformation); void searchCustomerByContact(String phoneNo); void searchCustomerByVehicle(String vehicleNo); void updateCustomer(CustomerInformation customerInformation); void changeCustomer(CustomerInformation customerInformation); void changeCustomer(String customerId); void success(String message); void failed(String message); void error(VolleyError error); }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package com.hybris.backoffice.excel.validators; import static com.hybris.backoffice.excel.validators.ExcelMandatoryFieldValidator.VALIDATION_MANDATORY_FIELD_MESSAGE_KEY; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import de.hybris.platform.core.model.c2l.LanguageModel; import de.hybris.platform.core.model.product.ProductModel; import de.hybris.platform.core.model.type.AttributeDescriptorModel; import java.util.ArrayList; import java.util.HashMap; import de.hybris.platform.servicelayer.i18n.CommonI18NService; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.runners.MockitoJUnitRunner; import com.hybris.backoffice.excel.data.ImportParameters; import com.hybris.backoffice.excel.validators.data.ExcelValidationResult; @RunWith(MockitoJUnitRunner.class) public class ExcelMandatoryFieldValidatorTest { @Mock private CommonI18NService commonI18NService; @InjectMocks private ExcelMandatoryFieldValidator excelMandatoryFieldValidator; @Test public void shouldHandleWhenAttributeIsNotOptional() { // given final ImportParameters importParameters = new ImportParameters(ProductModel._TYPECODE, null, null, null, new ArrayList<>()); final AttributeDescriptorModel attributeDescriptor = mock(AttributeDescriptorModel.class); when(attributeDescriptor.getOptional()).thenReturn(false); // when final boolean canHandle = excelMandatoryFieldValidator.canHandle(importParameters, attributeDescriptor); // then assertThat(canHandle).isTrue(); } @Test public void shouldHandleWhenAttributeIsNotOptionalAndItIsLocalizedForCurrentLanguage() { // given final ImportParameters importParameters = new ImportParameters(ProductModel._TYPECODE, "en", null, null, new ArrayList<>()); final AttributeDescriptorModel attributeDescriptor = mock(AttributeDescriptorModel.class); final LanguageModel languageModel = Mockito.mock(LanguageModel.class); when(attributeDescriptor.getOptional()).thenReturn(false); when(attributeDescriptor.getLocalized()).thenReturn(true); when(commonI18NService.getCurrentLanguage()).thenReturn(languageModel); when(languageModel.getIsocode()).thenReturn("en"); // when final boolean canHandle = excelMandatoryFieldValidator.canHandle(importParameters, attributeDescriptor); // then assertThat(canHandle).isTrue(); } @Test public void shouldNotHandleWhenAttributeIsOptional() { // given final ImportParameters importParameters = new ImportParameters(ProductModel._TYPECODE, null, null, null, new ArrayList<>()); final AttributeDescriptorModel attributeDescriptor = mock(AttributeDescriptorModel.class); when(attributeDescriptor.getOptional()).thenReturn(true); // when final boolean canHandle = excelMandatoryFieldValidator.canHandle(importParameters, attributeDescriptor); // then assertThat(canHandle).isFalse(); } @Test public void shouldNotHandleWhenAttributeIsNotOptionalAndIsNotLocalizedForCurrentLanguage() { // given final ImportParameters importParameters = new ImportParameters(ProductModel._TYPECODE, "en", null, null, new ArrayList<>()); final AttributeDescriptorModel attributeDescriptor = mock(AttributeDescriptorModel.class); final LanguageModel languageModel = Mockito.mock(LanguageModel.class); when(attributeDescriptor.getOptional()).thenReturn(false); when(attributeDescriptor.getLocalized()).thenReturn(true); when(commonI18NService.getCurrentLanguage()).thenReturn(languageModel); when(languageModel.getIsocode()).thenReturn("fr"); // when final boolean canHandle = excelMandatoryFieldValidator.canHandle(importParameters, attributeDescriptor); // then assertThat(canHandle).isFalse(); } @Test public void shouldNotReturnValidationErrorWhenCellIsNotBlank() { // given final ImportParameters importParameters = new ImportParameters(ProductModel._TYPECODE, null, "notEmptyCell", null, new ArrayList<>()); final AttributeDescriptorModel attributeDescriptor = mock(AttributeDescriptorModel.class); // when final ExcelValidationResult validationResult = excelMandatoryFieldValidator.validate(importParameters, attributeDescriptor, new HashMap<>()); // then assertThat(validationResult.hasErrors()).isFalse(); assertThat(validationResult.getValidationErrors()).isEmpty(); } @Test public void shouldReturnValidationErrorWhenCellIsBlank() { // given final ImportParameters importParameters = new ImportParameters(ProductModel._TYPECODE, null, "", null, new ArrayList<>()); final AttributeDescriptorModel attributeDescriptor = mock(AttributeDescriptorModel.class); // when final ExcelValidationResult validationResult = excelMandatoryFieldValidator.validate(importParameters, attributeDescriptor, new HashMap<>()); // then assertThat(validationResult.hasErrors()).isTrue(); assertThat(validationResult.getValidationErrors()).hasSize(1); assertThat(validationResult.getValidationErrors().get(0).getMessageKey()).isEqualTo(VALIDATION_MANDATORY_FIELD_MESSAGE_KEY); assertThat(validationResult.getValidationErrors().get(0).getParams()).isEmpty(); } }
package com.tencent.mm.app; import android.content.Context; import android.content.Intent; import android.os.Process; import com.tencent.mm.booter.CoreService; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.x; class e$5 implements Runnable { final /* synthetic */ e byl; private int byo = 0; e$5(e eVar) { this.byl = eVar; } public final void run() { int i = 0; try { e.b(this.byl).lock(); boolean z = e.c(this.byl) != null && e.c(this.byl).isBinderAlive(); x.i("MicroMsg.CoreServiceConnection", "mZombieWaker run serviceBinder: %s, binderAlive: %b", new Object[]{e.c(this.byl), Boolean.valueOf(z)}); if (z) { x.w("MicroMsg.CoreServiceConnection", "mZombieWaker run binderAlive return directly."); return; } e.b(this.byl).unlock(); x.e("MicroMsg.CoreServiceConnection", String.format("CoreService started but not responding, possibly zombie. Use step %d to restart CoreService.", new Object[]{Integer.valueOf(this.byo)})); if (this.byo == 1) { int cM = e.cM("com.tencent.mm:push"); if (cM != -1) { x.i("MicroMsg.CoreServiceConnection", String.format("Push Process %d killed.", new Object[]{Integer.valueOf(cM)})); x.chR(); Process.killProcess(cM); } else { x.i("MicroMsg.CoreServiceConnection", "Push Process not found."); } } Context context = ad.getContext(); Intent intent = new Intent(context, CoreService.class); try { x.i("MicroMsg.CoreServiceConnection", "unbinding CoreService..."); context.unbindService(this.byl); } catch (Exception e) { } finally { context.stopService(intent); i = this.byl; context.bindService(intent, i, 1); context.startService(intent); } if (this.byo == 1) { this.byo = i; } else { this.byo++; } ah.i(this, 10000); x.i("MicroMsg.CoreServiceConnection", String.format("ZombieWaker posted again with step %d", new Object[]{Integer.valueOf(this.byo)})); } finally { e.b(this.byl).unlock(); } } }