text
stringlengths
10
2.72M
package com.example.testapp.entity; public class School { private Integer id; private String schoolName; private String schoolDes; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName == null ? null : schoolName.trim(); } public String getSchoolDes() { return schoolDes; } public void setSchoolDes(String schoolDes) { this.schoolDes = schoolDes == null ? null : schoolDes.trim(); } @Override public String toString() { return "School{" + "id=" + id + ", schoolName='" + schoolName + '\'' + ", schoolDes='" + schoolDes + '\'' + '}'; } }
package com.fleet.initializr.json; import com.fleet.initializr.enums.ResultState; import java.io.Serializable; /** * @author April Han */ public class R implements Serializable { private static final long serialVersionUID = -6362815283450958495L; private Integer code; private Object data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } /** * 结果返回 * * @param code 返回码 * @param data 数据(可以是返回码说明,也可以是结果数据) * @return R */ public static R r(Integer code, Object data) { R r = new R(); r.setCode(code); r.setData(data); return r; } /** * 成功 * * @return R */ public static R ok() { return r(ResultState.SUCCESS.getCode(), ResultState.SUCCESS.getMsg()); } /** * 成功 * * @param resultState 成功枚举 * @return R */ public static R ok(ResultState resultState) { return r(resultState.getCode(), resultState.getMsg()); } /** * 成功 * * @param code 返回码 * @param data 数据(可以是返回码说明,也可以是结果数据) * @return R */ public static R ok(Integer code, Object data) { return r(code, data); } /** * 错误 * * @param resultState 成功枚举 * @param data 数据 * @return R */ public static R ok(ResultState resultState, Object data) { return r(resultState.getCode(), data); } /** * 成功 * * @param data 数据 * @return R */ public static R ok(Object data) { return r(ResultState.SUCCESS.getCode(), data); } /** * 错误 * * @return R */ public static R error() { return r(ResultState.ERROR.getCode(), ResultState.ERROR.getMsg()); } /** * 错误 * * @param resultState 错误枚举 * @return R */ public static R error(ResultState resultState) { return r(resultState.getCode(), resultState.getMsg()); } /** * 错误 * * @param code 返回码 * @param data 数据(可以是返回码说明,也可以是结果数据) * @return */ public static R error(Integer code, Object data) { return r(code, data); } /** * 错误 * * @param resultState 错误枚举 * @param data 数据 * @return R */ public static R error(ResultState resultState, Object data) { return r(resultState.getCode(), data); } /** * 错误 * * @param data 数据 * @return R */ public static R error(Object data) { return r(ResultState.ERROR.getCode(), data); } /** * 判断结果是否正确 * * @param r * @return */ public static Boolean isOk(R r) { if (r != null && r.getCode().equals(ResultState.SUCCESS.getCode())) { return true; } return false; } }
package com.javarush.task.task14.task1408; import com.javarush.task.task14.task1406.Hen; /** * Created by Rostislav on 15.03.2017. */ public class RussianHen extends Hen { @Override public int getCountOfEggsPerMonth() { return 22; } public String getDescription() { return "Моя страна" + Country.RUSSIA + " я несу " + this.getCountOfEggsPerMonth(); } }
package usta.sistemas; import java.util.Scanner; public class Main { public static void main(String[] args) { /*AUTHOR: Angel Manuel Correa Rivera DATE:28/04/2020 DESCRIPTION:This software calculate the average of number positive and negatives. */ f_menu(); } public static void f_menu() { //This method is the menu of the software System.out.println("----------------------------------------"); System.out.println("--------------OPERATIONSOFT--------------"); System.out.println("-----version:1.0------28/04/2020.-------"); System.out.println("-----Angel Manuel Correa Rivera---------"); System.out.println("----------------------------------------"); } public static void f_operation_number (){ //This method asked for ten numbers int sumatory_positives=0,sumatory_negatives=0,total_zero=0,number; for(int i=1;i<=10;i++) { number= f_user_number(i); if (number<0){ sumatory_negatives-=number; }else if (number>0){ sumatory_positives+=number; }else { total_zero++; } } public static int f_user_number(int i){ //This method return a user number Scanner keyboard= new Scanner(System.in); System.out.println("Input the number: "+i); int number=keyboard.nextInt(); return number; } } }
package LC0_200.LC50_100; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; public class LC57_Insert_Iterval { public int[][] insert(int[][] intervals, int[] newInterval) { LinkedList<int[]> list = new LinkedList<int[]>(); // sort int[][] inter = new int[intervals.length + 1][]; for (int i = 0; i < intervals.length; ++i) inter[i] = intervals[i]; inter[intervals.length] = newInterval; Collections.sort(Arrays.asList(inter), new IntervalComparator()); // merge for (int[] merge : inter) { if (list.isEmpty() || list.getLast()[1] < merge[0]) list.add(merge); else list.getLast()[1] = list.getLast()[1] > merge[1] ? list.getLast()[1] : merge[1]; } return list.toArray(new int[list.size()][]); } private class IntervalComparator implements Comparator<int[]> { @Override public int compare(int[] a, int[] b) { return a[0] < b[0] ? -1 : a[0] == b[0] ? 0 : 1; } } }
package org.firstinspires.ftc.teamcode; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.robotcore.eventloop.opmode.OpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.IntegratingGyroscope; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.hardware.ColorSensor; /** * Created by guus on 9/23/2017. * FTC 2017, FTCUnits * Basis motor controller, nog niet af */ @TeleOp(name = "DriverOp2", group = "Guus") public class DriverOp2 extends OpMode { private DcMotor MotorFrontRight; private DcMotor MotorFrontLeft; private DcMotor MotorBackRight; private DcMotor MotorBackLeft; private Servo BlockBoxServo; public boolean IsControlled = true; private DcMotor LiftMotor; double driveDirectionSpeed = 1 ; private ColorSensor testSensor; private float x; private float y; BNO055IMU imu; private String servomessage; @Override public void init() { MotorBackLeft = hardwareMap.dcMotor.get("MotorBackLeft"); MotorBackRight = hardwareMap.dcMotor.get("MotorBackRight"); MotorFrontLeft = hardwareMap.dcMotor.get("MotorFrontLeft"); MotorFrontRight = hardwareMap.dcMotor.get("MotorFrontRight"); LiftMotor = hardwareMap.dcMotor.get("LiftMotor"); BlockBoxServo = hardwareMap.servo.get("BlockBoxServo"); // ArmMotor = hardwareMap.dcMotor.get("ArmMotor"); // BekServo1 = hardwareMap.servo.get("BekServo1"); /// BekServo2 = hardwareMap.servo.get("BekServo2"); // BakMotor = hardwareMap.dcMotor.get("BakMotor"); // testSensor = hardwareMap.colorSensor.get("testSensor"); driveDirectionSpeed = 1; // BekServo2.setDirection(Servo.Direction.REVERSE); // BekServo1.setPosition(1); // BekServo2.setPosition(1); try { logUtils.StartLogging(1); } catch (Exception e) { } BlockBoxClose(); logUtils.Log(logUtils.logType.normal, "Started the DriverOp2 opmode", 1); logUtils.Log(logUtils.logType.normal, "Backleft,Frontleft,BackRight,Frontright", 1); } @Override public void loop() { SpeedChecks(); DriveChecks(); // ArmChecks(); //telemetry.addData("color",testSensor.alpha()); } void DriveChecks () { double BackLeft = 1 * driveDirectionSpeed * -gamepad1.left_stick_y; double FrontLeft = 1 * driveDirectionSpeed * -gamepad1.left_stick_y ; double BackRight = -1 * driveDirectionSpeed * -gamepad1.right_stick_y ; double FrontRight = -1 * driveDirectionSpeed * -gamepad1.right_stick_y; logUtils.Log(logUtils.logType.normal, BackLeft + "," + FrontLeft + "," + BackRight + "," + FrontRight, 1 ); MotorBackLeft.setPower(BackLeft); MotorFrontLeft.setPower(FrontLeft); MotorBackRight.setPower(BackRight); MotorFrontRight.setPower(FrontRight); } void SpeedChecks() { if (gamepad1.back) { double temp; temp = driveDirectionSpeed; driveDirectionSpeed = temp * -1; } if (gamepad1.x){ BLockBoxOpen(); } else { BlockBoxClose(); } if(gamepad1.left_bumper){ if(x != -1) x -= 0.05; } if (gamepad1.right_bumper){ if(x != 1) x += 0.05; } y = x*x*x; if(x < 0){ y = y * -1; } driveDirectionSpeed = y; if (gamepad1.dpad_left) { sidemoving(1); } if (gamepad1.dpad_right) { sidemoving(-1); } LiftMotor.setPower(gamepad2.left_stick_y); } public void sidemoving(int speed) { MotorBackLeft.setPower(speed); MotorFrontLeft.setPower(-speed); MotorBackRight.setPower(-speed); MotorFrontRight.setPower(speed); } /** * Opens the BlockBox, used for teammaker/game elements */ public void BLockBoxOpen () { BlockBoxServo.setPosition(0); } /** * Closes the BlockBox, used for teammarker/game elements */ public void BlockBoxClose () { BlockBoxServo.setPosition(65); } }
package com.yixin.kepler.v1.datapackage.dto.yntrust; import com.fasterxml.jackson.annotation.JsonProperty; /** * 云南信托请款银行结果查询 * Package : com.yixin.kepler.v1.datapackage.dto.yntrust * * @author YixinCapital -- wangwenlong * 2018年9月20日 上午10:44:37 * */ public class YTPaymentBankResultRequestDTO extends YTCommonRequestDTO { private static final long serialVersionUID = -8742502718757413197L; /** * 贷款唯一标示 ,和合同号字段一起只填其中一个,不能都为空 */ @JsonProperty("UniqueId") private String uniqueId = ""; public String getUniqueId() { return uniqueId; } public void setUniqueId(String uniqueId) { this.uniqueId = uniqueId; } }
package com.homepagetestcase; import java.util.List; import org.apache.poi.util.SystemOutLogger; import org.openqa.selenium.By; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class DynamicTable { public static WebDriver driver; @BeforeTest public void before() { System.setProperty("webdriver.gecko.driver", "E:\\geckodriver.exe"); //WebDriver driver =new FirefoxDriver(); DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities = DesiredCapabilities.firefox(); capabilities.setBrowserName("firefox"); capabilities.setVersion("your firefox version"); capabilities.setPlatform(Platform.WINDOWS); capabilities.setCapability("marionette", false); driver = new FirefoxDriver(capabilities); driver.manage().window().maximize(); } @Test(enabled=false) public void tablehandle() throws InterruptedException { driver.get("https://www.w3schools.com/html/html_tables.asp"); Thread.sleep(5000); List<WebElement> rows = driver.findElements(By.xpath("//table[@id = 'customers']/tbody/tr")); int row = rows.size(); System.out.println("Total rows in table : "+row); List<WebElement> cols = driver.findElements(By.xpath("//table[@id = 'customers']/tbody/tr[1]/th")); int col = cols.size(); System.out.println("Total rows in table : "+col); String header = "Country"; if(header.equalsIgnoreCase("Company")) { for(int i = 1 ;i<row;i++) { String value = driver.findElement(By.xpath("//table[@id = 'customers']/tbody/tr[1]/th[contains(text(),'"+header+"')]/parent::tr/following-sibling::tr["+i+"]/td[1]")).getText(); System.out.println(value); } } else if(header.equalsIgnoreCase("Contact")) { for(int i = 1 ;i<row;i++) { String value = driver.findElement(By.xpath("//table[@id = 'customers']/tbody/tr[1]/th[contains(text(),'"+header+"')]/parent::tr/following-sibling::tr["+i+"]/td[2]")).getText(); System.out.println(value); } } else if(header.equalsIgnoreCase("Country")) { for(int i = 1 ;i<row;i++) { String value = driver.findElement(By.xpath("//table[@id = 'customers']/tbody/tr[1]/th[contains(text(),'"+header+"')]/parent::tr/following-sibling::tr["+i+"]/td[3]")).getText(); System.out.println(value); } } else System.out.println("Enter valid header name"); } @Test public void checkboxTable() throws InterruptedException { driver.get("https://www.oracle.com/webfolder/technetwork/jet/jetCookbook.html?component=table&demo=checkboxSelectableTable"); Thread.sleep(15000); String xpath1 = "//th[@id ='table:_hdrCol2']/parent::tr/parent::thead/parent::table/tbody/tr[1]//td[4]/preceding-sibling::td[2]//input"; driver.findElement(By.xpath(xpath1)).click(); /*System.out.println(rows); for(int i=1;i<=rows;i++) { String name = driver.findElement(By.xpath("//th[@id ='table:_hdrCol2']/parent::tr/parent::thead/parent::table/tbody/tr["+i+"]//td[4]")).getText(); System.out.println(name); if(name.equalsIgnoreCase("BB")) { } }*/ } @AfterTest public void closebrowser() { driver.close(); } }
package dmoj; import java.io.*; import java.util.*; public class DMOPC_14_P3_NewStudents { public static void main(String[] args) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out)); int N = Integer.parseInt(in.readLine().trim()); double sum = 0; double avg; for (int i = 0; i < N; i++) { int original = Integer.parseInt(in.readLine().trim()); sum += original; } double x = N; int S = Integer.parseInt(in.readLine().trim()); for (int i = 0; i < S; i++) { sum += Integer.parseInt(in.readLine().trim()); x++; avg = sum/x; out.write(String.valueOf(avg)); out.newLine(); } out.close(); } }
import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Scanner; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.MatteBorder; import com.fazecast.jSerialComm.SerialPort; import javax.swing.JButton; public class Panel_Monitor extends JPanel { /** * Create the panel. */ private SerialPort serialPort; private Window_Credential tester; public Panel_Monitor(SerialPort arduinoPort) { setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 0, 0))); setBackground(Color.WHITE); setLayout(null); JLabel lblBoxConnected = new JLabel("Box Connected:"); lblBoxConnected.setFont(new Font("Calibri", Font.BOLD, 16)); lblBoxConnected.setBounds(158, 145, 115, 14); add(lblBoxConnected); JLabel label = new JLabel(""); label.setIcon(new ImageIcon("C:\\Users\\Ricky Martinez\\Documents\\GitHub\\LoadShedApplication\\images\\sensorIcon.png")); label.setBounds(182, 26, 85, 85); add(label); JLabel lblNewLabel = new JLabel("n/a"); lblNewLabel.setFont(new Font("Calibri", Font.BOLD, 16)); lblNewLabel.setBounds(273, 145, 79, 14); add(lblNewLabel); JButton cancelButton = new JButton("Cancel"); cancelButton.setFont(new Font("Calibri", Font.BOLD, 18)); cancelButton.setBackground(Color.decode("#ff6666")); cancelButton.setBounds(180, 229, 89, 29); add(cancelButton); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(tester != null) { tester.swapView("controlPanel"); tester.setSize(510, 480); } } }); // // determine which serial port to use // SerialPort ports[] = SerialPort.getCommPorts(); // System.out.println("Select a port:"); // int i = 1; // for(SerialPort port : ports) { // System.out.println(i++ + ". " + port.getSystemPortName()); // } // Scanner s = new Scanner(System.in); // int chosenPort = s.nextInt(); // // // open and configure the port // SerialPort port = ports[chosenPort - 1]; // if(port.openPort()) { // System.out.println("Successfully opened the port."); // } else { // System.out.println("Unable to open the port."); // return; // } // port.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0); // enter into an infinite loop that reads from the port and updates the GUI if(arduinoPort != null) { Scanner data = new Scanner(arduinoPort.getInputStream()); if(data.hasNextLine()) { String temp = data.nextLine(); System.out.println(temp); String temp2 = new StringBuilder().append(temp.charAt(3)).append(temp.charAt(4)).append(temp.charAt(5)).toString(); System.out.println(temp2); lblNewLabel.setText(temp2); } } //see if you can read in values } //alows for switching between cards public void setTester(Window_Credential tester) { this.tester = tester; } }
package pt.bank.ws.handler; import java.io.*; import java.util.*; import javax.xml.datatype.*; import javax.xml.namespace.QName; import javax.xml.soap.*; import javax.xml.ws.handler.*; import javax.xml.ws.handler.soap.*; public class BankHandlerResolver implements HandlerResolver { public BankHandlerResolver() { } @Override public List<Handler> getHandlerChain(PortInfo portInfo) { List<Handler> hchain = new ArrayList<Handler>(); hchain.add(new HeaderHandler()); return hchain; } }
package helloworld; /** * Created by kth919 on 2017-09-08. */ public class OneTwoFour { }
/* * Copyright 2002-2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.springframework.integration.aws.s3.core; /** * Represent one Grant for a Grantee and the associated permissions * * @author Amol Nayak * * @since 0.5 * */ public class ObjectGrant { private final Grantee grantee; private final ObjectPermissions permission; /** * Instantiate an Object grant for the given grantee and with given permissions * @param grantee * @param permission */ public ObjectGrant(Grantee grantee, ObjectPermissions permission) { super(); this.grantee = grantee; this.permission = permission; } /** * Gets the grantee for this particular object permission */ public Grantee getGrantee() { return grantee; } /** * Gets the Corresponding object permission */ public ObjectPermissions getPermission() { return permission; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((grantee == null) ? 0 : grantee.hashCode()); result = prime * result + ((permission == null) ? 0 : permission.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ObjectGrant other = (ObjectGrant) obj; if (grantee == null) { if (other.grantee != null) return false; } else if (!grantee.equals(other.grantee)) return false; if (permission != other.permission) return false; return true; } }
package com.company; public class ListElement { private final int value; private ListElement next; public ListElement(int value){ this.value=value; } public int getValue() { return value; } public ListElement getNext(){ return next; } public void setNext(ListElement next){ this.next=next; } public void showListElements(ListElement first){ if (first!=null) { System.out.println("Number: "+first.getValue()+" Remainder of dividing by 7: "+first.getValue()%7); showListElements(first.getNext()); } } }
package com.android.design; import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; public class MainActivity extends AppCompatActivity { private static String[] OS_NAME = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2", "Android", "iPhone", "WindowsMobile" }; private static String[] OS_NAME_SHORT = new String[] { "Android", "iPhone", "WindowsMobile", "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X"}; private static String[] OS_NAME_SHORT_MORE = new String[] { "Android", "iPhone", "WindowsMobile"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Chat"); setSupportActionBar(toolbar); TabLayout tabLayout = (TabLayout) findViewById(R.id.tab); ViewPager pager = (ViewPager) findViewById(R.id.pager); PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager()); pagerAdapter.addTab("Cars", new CommonFragment(), 1); pagerAdapter.addTab("Bike", new CommonFragment(), 2); pagerAdapter.addTab("HMV", new CommonFragment(), 3); pager.setAdapter(pagerAdapter); tabLayout.setupWithViewPager(pager); /* // Iterate over all tabs and set the custom view for (int i = 0; i < tabLayout.getTabCount(); i++) { TabLayout.Tab tab = tabLayout.getTabAt(i); tab.setCustomView(pagerAdapter.getTabView(i)); }*/ } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } public class PagerAdapter extends FragmentStatePagerAdapter{ private final HashMap<Integer, Fragment> mFragments; private final ArrayList<Integer> mTabNums; private final ArrayList<CharSequence> mTabTitles; @SuppressLint("UseSparseArrays") public PagerAdapter(FragmentManager fm) { super(fm); mFragments = new HashMap<Integer, Fragment>(3); mTabNums = new ArrayList<Integer>(3); mTabTitles = new ArrayList<CharSequence>(3); } public void addTab(String tabTitle, Fragment newFragment, int tabId) { mTabTitles.add(tabTitle); mFragments.put(tabId, newFragment); mTabNums.add(tabId); notifyDataSetChanged(); } public Fragment getTabFragment(int tabNum) { if (mFragments.containsKey(tabNum)) { return mFragments.get(tabNum); } return null; } @Override public CharSequence getPageTitle(int position) { return mTabTitles.get(position); } @Override public int getCount() { return mFragments.size(); } @Override public Fragment getItem(int position) { if(position == 0) { CommonFragment frag1 = (CommonFragment) mFragments.get(mTabNums.get(position)); frag1.setData(OS_NAME); return frag1; }else if(position == 1){ CommonFragment frag2 = (CommonFragment) mFragments.get(mTabNums.get(position)); frag2.setData(OS_NAME_SHORT); return frag2; }else{ CommonFragment frag3 = (CommonFragment) mFragments.get(mTabNums.get(position)); frag3.setData(OS_NAME_SHORT_MORE); return frag3; } } } public static class CommonFragment extends Fragment{ String[] data; public void setData(String[] data){ this.data = data; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.layout,container,false); ListView listView = (ListView) rootView.findViewById(R.id.list); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,data); listView.setAdapter(adapter); return rootView; } } public static class MessageFragment extends Fragment{ @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.layout,container,false); ListView listView = (ListView) rootView.findViewById(R.id.list); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,OS_NAME); listView.setAdapter(adapter); return rootView; } } public static class ContactsFragment extends Fragment{ @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.layout,container,false); ListView listView = (ListView) rootView.findViewById(R.id.list); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,OS_NAME); listView.setAdapter(adapter); return rootView; } } }
/* * Copyright (c) 2016 Mobvoi Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package ticwear.design.widget; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.ImageView; public class ProgressBarButton extends ImageView { private static final int LONG_PRESS_DELAY = 300; private static int mDefaultImageSize; private TouchListener mTouchListener; public ProgressBarButton(Context context) { super(context); } public ProgressBarButton(Context context, AttributeSet attrs) { super(context, attrs, 0); } public ProgressBarButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } public void setTouchListener(TouchListener touchListener) { if (mTouchListener == touchListener) { return; } stopLongPressUpdate(); mTouchListener = touchListener; } private void stopLongPressUpdate() { removeCallbacks(mLongPressUpdateRunnable); } @Override protected void onDetachedFromWindow() { stopLongPressUpdate(); super.onDetachedFromWindow(); } private final Runnable mLongPressUpdateRunnable = new Runnable() { @Override public void run() { if (mTouchListener != null) { mTouchListener.onLongPress(); ProgressBarButton.this.postDelayed(this, 60); } } }; @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); if (mTouchListener == null) { return true; } int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN) { mTouchListener.onDown(); postDelayed(mLongPressUpdateRunnable, LONG_PRESS_DELAY); } else { stopLongPressUpdate(); if (action == MotionEvent.ACTION_UP) { mTouchListener.onUp(); } } return true; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(heightMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); int padding = (height - mDefaultImageSize)/2; this.setPadding(padding, padding, padding, padding); setMeasuredDimension(width, height); } public void setDefaultImageSize(int size) { mDefaultImageSize = size; } public interface TouchListener { void onDown(); void onUp(); void onLongPress(); } }
package ro.ase.cts.program; import ro.ase.cts.clase.Rezervare; import ro.ase.cts.clase.RezervareBuilder; import ro.ase.cts.clase.RezervareBuilderV2; public class Main { public static void main(String[] args) { Rezervare rezervare01; Rezervare rezervare02; Rezervare rezervare03=new Rezervare(200,true,true,true,"jazz"); RezervareBuilder rezervareBuilder = new RezervareBuilder(); rezervareBuilder.setCodRezervare(100).setAreMancare(true); rezervare01 = rezervareBuilder.build(); rezervare02 = new RezervareBuilder().setCodRezervare(101).setAreMancare(true).build(); System.out.println(rezervare01.toString()); System.out.println(rezervare02.toString()); System.out.println(rezervare03.toString()); Rezervare rezervare04 = new RezervareBuilder().setGenMuzica("pop").build(); Rezervare rezervare05 = new RezervareBuilder().setGenMuzica("rock").build(); System.out.println(rezervare04.toString()); System.out.println(rezervare05.toString()); RezervareBuilderV2 rezervareBuilderV2 = new RezervareBuilderV2().setAreMancare(true).setAreScaunErgonomic(true); Rezervare rezervare100 = rezervareBuilderV2.setCodRezervare(100).build(); Rezervare rezervare101 = rezervareBuilderV2.setCodRezervare(101).build(); System.out.println(rezervare100.toString()); System.out.println(rezervare101.toString()); } }
package br.ufrgs.rmpestano.intrabundle.plugin; import br.ufrgs.rmpestano.intrabundle.i18n.MessageProvider; import br.ufrgs.rmpestano.intrabundle.model.OSGiModule; import junit.framework.Assert; import org.jboss.forge.shell.util.OSUtils; import org.junit.Test; import javax.enterprise.inject.Instance; import javax.inject.Inject; import java.io.File; import static org.junit.Assert.assertNotNull; public class BundlePluginTest extends BaseBundleTest { @Inject MessageProvider provider; @Inject Instance<OSGiModule> currentBundle; @Test public void shouldUseDeclarativeServices() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle usesDeclarativeServices"); Assert.assertTrue(getOutput().contains(provider.getMessage("yes"))); } @Test public void shouldPublishInterfaces() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle publishesInterfaces"); Assert.assertTrue(getOutput().startsWith(provider.getMessage("yes"))); } @Test public void shouldDeclarePermissions() throws Exception{ initializeOSGiProject(); resetOutput(); getShell().execute("bundle declaresPermissions"); Assert.assertTrue(getOutput().contains(provider.getMessage("yes"))); } @Test public void shouldNotUseBlueprint() throws Exception{ initializeOSGiProject(); resetOutput(); getShell().execute("bundle usesBlueprint"); Assert.assertTrue(getOutput().contains(provider.getMessage("no"))); } @Test public void shouldFindActivator() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle activator"); String activatorPath = "/module/src/br/ufrgs/rmpestano/activator/Activator.java"; if(OSUtils.isWindows()){ activatorPath = activatorPath.replaceAll("/", File.separator + File.separator); } Assert.assertTrue(getOutput().contains(activatorPath)); } @Test public void shouldGetBundleVersion() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle version"); Assert.assertTrue(getOutput().startsWith("1.0.0.qualifier")); } @Test public void shouldGetExportedPackages() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle exportedPackages"); Assert.assertTrue(getOutput().contains("br.ufrgs.rmpestano.api")); } @Test public void shouldGetImportedPackages() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle importedPackages"); Assert.assertTrue(getOutput().contains("org.osgi.framework")); } @Test public void shouldCountLinesOfCode() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle loc"); Assert.assertTrue(getOutput().startsWith("2")); } @Test public void shouldFindRequiredBundle() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle requiredBundles"); Assert.assertTrue(getOutput().contains("org.apache.tuscany.sdo.spec;visibility:=reexport")); } /** * lines of test code test */ @Test public void shouldCountLinesOfTest() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle lot"); Assert.assertTrue(getOutput().startsWith("1")); } @Test public void shouldContainStaleReferences() throws Exception { initializeOSGiProject(); resetOutput(); getShell().clear(); getShell().execute("bundle staleReferences"); Assert.assertTrue(getOutput().contains("HelloStaleManager.java")); } @Test public void shouldCountNumberOfClasses() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle nc"); Assert.assertTrue(getOutput().startsWith("3")); } @Test public void shouldCountNumberOfAbstractClasses() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle na"); Assert.assertTrue(getOutput().startsWith("1")); } @Test public void shouldCountNumberOfInterfaces() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle ni"); Assert.assertTrue(getOutput().startsWith("2")); } @Test public void shouldCountNumberOfPackages() throws Exception { initializeOSGiProject(); resetOutput(); getShell().execute("bundle np"); Assert.assertTrue(getOutput().startsWith("4")); } /** * test find activator command in eclipse bnd tools based OSGi project */ @Test public void shouldFindActivatorInBndProject() throws Exception { resetOutput(); initializeOSGiBNDProject(); resetOutput(); getShell().execute("bundle activator"); String expected = OSUtils.isWindows() ? "\\module1\\src\\br\\ufrgs\\rmpestano\\activator\\Activator.java" : "/module1/src/br/ufrgs/rmpestano/activator/Activator.java"; Assert.assertTrue(getOutput().contains(expected)); } /** * test find activator command in maven bnd based OSGi bundle */ @Test public void shouldFindActivatorInMavenBndBundle() throws Exception { initializeMavenOSGiBNDProject(); resetOutput(); getShell().execute("bundle activator"); String expected = OSUtils.isWindows() ? "\\module1\\src\\main\\java\\br\\ufrgs\\rmpestano\\activator\\Activator.java" : "/module1/src/main/java/br/ufrgs/rmpestano/activator/Activator.java"; Assert.assertTrue(getOutput().contains(expected)); } /** * test find activator command in eclipse bnd tools based OSGi project with bnd file in resources folder */ @Test public void shouldFindActivatorInBndProjectWithResources() throws Exception { initializeOSGiBNDProjectWithBndInResources(); resetOutput(); getShell().execute("bundle activator"); String expected = OSUtils.isWindows() ? "\\module1\\src\\br\\ufrgs\\rmpestano\\activator\\Activator.java" : "/module1/src/br/ufrgs/rmpestano/activator/Activator.java"; Assert.assertTrue(getOutput().contains(expected)); OSGiModule osGiModule = currentBundle.get(); assertNotNull(osGiModule); Assert.assertTrue(osGiModule.getActivator().getFullyQualifiedName().endsWith(expected)); } @Test public void shouldUseIpojo() throws Exception { resetOutput(); initializeOSGiProjectWithIpojoComponent(); resetOutput(); getShell().execute("bundle usesIpojo"); Assert.assertTrue(getOutput().startsWith(provider.getMessage("yes"))); } @Test public void shouldHasOneIpojoComponent() throws Exception { resetOutput(); initializeOSGiProjectWithIpojoComponent(); resetOutput(); getShell().execute("bundle numberOfIpojoComponents"); Assert.assertTrue(getOutput().startsWith("1")); } }
package shared; import java.io.*; import java.lang.*; /** Provide support for MLC++ logging. * @author James Louis Java Implementation. * @author Eric Eros 7/8/96 Added DribbleOptions. * @author Chia-Hsin Li 12/27/94 Added FLOG. * @author James Dougherty 10/10/94 * @author Ronny Kohavi 12/21/93 Initial revision (.h,.c) */ public class LogOptions { private Writer globalLogStream; //MLC++ defined in a.h, basics.h private int logLevel = 3; //default logLevel (??) -SG private Writer stream; private static int DEFAULT_LINE_NUM_WIDTH = 4; /* Options that are contained in a MLC++ MLCIOStream, here we can just reference them to write the log file, when it is written to a file, rather that to System.out */ static String newline_prefix = ""; static String err_prefix = "Err: "; // Added JWP 11-24-2001 String wrap_prefix; String WRAP_INDENT = "\n"; /** Constructor. */ public LogOptions() { logLevel = GlobalOptions.logLevel; stream = globalLogStream; } /** Constructor. * @param logOptionName The name of the log level option. */ public LogOptions(String logOptionName) { GetEnv getenv = new GetEnv(); logLevel = getenv.get_option_int(logOptionName); stream = globalLogStream; } /** Set LogOptions based on another instance as prototype. * @param opt The LogOptions instance copied. */ public void set_log_options(LogOptions opt) { set_log_level(opt.get_log_level()); set_log_stream(opt.get_log_stream()); } /** Sets the log level. Negative log levels are turned into 0. This * allows calls such as set_log_level(get_log_level() - 3). * @param level The new log level. */ public void set_log_level(int level) { logLevel = Math.max(0,level); } /** Returns the log level. * @return The log level. */ public int get_log_level() { return logLevel; } /** Sets the display stream. * @param strm The stream to be written to. */ public void set_log_stream(Writer strm) { stream = strm; } /** Returns the stream used for display. * @return The stream used for display. */ public Writer get_log_stream() { return stream; } /** Sets prefixes displayed before log message. * @param file The name of the file containing this log message. * @param line Line number of log message. */ public void set_log_prefixes(String file, int line) { if(GlobalOptions.showLogOrigin) { String adjFile = file; newline_prefix = adjFile + "::"+line+": "; } else newline_prefix = ""; wrap_prefix = newline_prefix+ WRAP_INDENT; } /** Sets prefixes displayed before log message. * @param file The name of the file containing this log message. * @param line Line number of log message. * @param stmtLogLevel The log level of the log message statement. * @param lgLevel The current log level being displayed. */ public void set_log_prefixes(String file, int line, int stmtLogLevel, int lgLevel) { if(GlobalOptions.showLogOrigin) { String adjFile = file; newline_prefix = "["+stmtLogLevel+"<="+logLevel+ "] "+adjFile+"::"+line+": "; } else newline_prefix = ""; wrap_prefix = newline_prefix + WRAP_INDENT; } /** Returns this LogOptions. * @return This LogOptions object. */ public LogOptions get_log_options() { return this; } /** Displays a log message. * @param logNumber The log number of the message. * @param logMessage The message being displayed. */ public void LOG(int logNumber, String logMessage) { if(logNumber <= logLevel) { System.out.print(newline_prefix + logMessage); System.out.flush(); } } /** Displays a log message. * @param logNumber The log number of the message. * @param logChar The message being displayed. */ public void LOG(int logNumber, char logChar) { if(logNumber <= logLevel){ System.out.print(newline_prefix + logChar); System.out.flush(); } } /** Displays an error message. * @param logNumber The log level of the error message. * @param errMessage The error message. */ public void ERR(int logNumber, String errMessage) { if (logNumber <= logLevel) { System.err.print(err_prefix + errMessage); System.err.flush(); } } /** Displays log message according to the global log level. * @param logNumber The log number of the message. * @param logMessage The message to be displayed. */ static public void GLOBLOG(int logNumber, String logMessage) { if(logNumber <= GlobalOptions.logLevel){ System.out.print(newline_prefix + logMessage); System.out.flush(); } } /** Displays log message according to the global log level. * @param logNumber The log number of the message. * @param logChar The message to be displayed. */ static public void GLOBLOG(int logNumber, char logChar) { if(logNumber <= GlobalOptions.logLevel){ // System.out.print("LOG-->"+logChar); System.out.print(newline_prefix + logChar); System.out.flush(); } } /** If the dribble is set to TRUE, this method displays the given message. * @param dribbleMessage The message to be displayed. * @see GlobalOptions#dribble */ public void DRIBBLE(String dribbleMessage) { if(GlobalOptions.dribble){ System.out.println("DRIBBLE-->"+dribbleMessage); System.out.flush(); } } }
package com.beiyelin.projectportal.controller; import com.beiyelin.common.resbody.ResultBody; import com.beiyelin.commonsql.bean.*; import com.beiyelin.projectportal.entity.SettleDetailWorkloadTicket; import com.beiyelin.projectportal.service.SettleDetailWorkloadService; import com.beiyelin.projectportal.service.SettleDetailWorkloadTicketService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /** * @Description: * @Author: newmann * @Date: Created in 9:26 2018-02-25 */ @RestController @RequestMapping("/api/project/settle-detail-workload-ticket") public class SettleDetailWorkloadTicketController { public final static String PERMISSION_PROJECT_SETTLE_DETAIL_WORKLOAD_TICKET_MODULE_NAME ="结算单的考勤单清单"; private SettleDetailWorkloadTicketService settleDetailWorkloadTicketService; @Autowired public void setSettleDetailWorkloadTicketService(SettleDetailWorkloadTicketService service){ this.settleDetailWorkloadTicketService = service; } @PostMapping("/add-detail") public ResultBody<ItemAdd<SettleDetailWorkloadTicket>> addDetail(@RequestBody ItemAdd<SettleDetailWorkloadTicket> itemAdd) { return new ResultBody<>(settleDetailWorkloadTicketService.addItem(itemAdd)); } @PostMapping("/batch-add-detail") public ResultBody<ItemBatchAdd<SettleDetailWorkloadTicket>> batchAddDetail(@RequestBody ItemBatchAdd<SettleDetailWorkloadTicket> itemBatchAdd) { return new ResultBody<>(settleDetailWorkloadTicketService.batchAddItem(itemBatchAdd)); } @PostMapping("/update-detail") public ResultBody<ItemUpdate<SettleDetailWorkloadTicket>> updateDetail(@RequestBody ItemUpdate<SettleDetailWorkloadTicket> itemUpdate) { return new ResultBody<>(settleDetailWorkloadTicketService.updateItem(itemUpdate)); } @PostMapping("/delete-detail") public ResultBody<ItemDelete<SettleDetailWorkloadTicket>> deleteDetail(@RequestBody ItemDelete<SettleDetailWorkloadTicket> itemDelete) { return new ResultBody<>(settleDetailWorkloadTicketService.deleteItem(itemDelete)); } @PostMapping("/move-detail") public ResultBody<ItemMove> moveDetail(@RequestBody ItemMove moveDetail) { return new ResultBody<>(settleDetailWorkloadTicketService.moveItem(moveDetail)); } @GetMapping("/fetch-detail-by-masterid/{masterid}") public ResultBody<List<SettleDetailWorkloadTicket>> fetchDetailByMasterId(@PathVariable String masterid) { return new ResultBody<>(settleDetailWorkloadTicketService.findByMasterId(masterid)); } @GetMapping("/find-by-masterid/{id}") public ResultBody<List<SettleDetailWorkloadTicket>> findByMasterId(@PathVariable("id") String masterId){ return new ResultBody<>(settleDetailWorkloadTicketService.findByMasterId(masterId)); } @GetMapping("/find-by-id/{id}") public ResultBody<SettleDetailWorkloadTicket> findById(@PathVariable("id") String id) { return new ResultBody<>(settleDetailWorkloadTicketService.findById(id)); } // @PostMapping("/find-available-employee-pools") // public ResultBody<PageResp<Employee>> findAvailableEmployeePools(@RequestBody EntityRelationAvailablePoolsReqBody<EmployeeQuery> reqBody){ // // return new ResultBody<>(settleDetailWorkloadTicketService.findEmployeeAvailablePools(reqBody.getMasterId(),reqBody.getQueryReq(),reqBody.getPageReq())); // // } // // @PostMapping("/find-available-outsource-employee-pools") // public ResultBody<PageResp<OutsourceEmployee>> findAvailableOutsourceEmployeePools(@RequestBody EntityRelationAvailablePoolsReqBody<OutsourceEmployeeQuery> reqBody){ // // return new ResultBody<>(settleDetailWorkloadTicketService.findOutsourceEmployeeAvailablePools(reqBody.getMasterId(),reqBody.getQueryReq(),reqBody.getPageReq())); // // } }
package com.example.ktc.DataBase; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.example.ktc.Model.GiaoVien; import com.example.ktc.Model.MonHoc; import java.util.ArrayList; public class DBGiaoVien { DBHelper dbHelper; public DBGiaoVien(Context context) { dbHelper= new DBHelper(context); } public void Them(GiaoVien GiaoVien) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("MaGV",GiaoVien.getMagv()); values.put("TenGV",GiaoVien.getTengv()); values.put("SDT",GiaoVien.getSdt()); db.insert("GiaoVien",null,values); } public void Sua(GiaoVien GiaoVien) { SQLiteDatabase db = dbHelper.getWritableDatabase(); ContentValues values = new ContentValues(); values.put("MaGV",GiaoVien.getMagv()); values.put("TenGV",GiaoVien.getTengv()); values.put("SDT",GiaoVien.getSdt()); db.update("GiaoVien",values,"MaGV ='"+ GiaoVien.getMagv() +"'",null); } public void Xoa(GiaoVien GiaoVien) { SQLiteDatabase db = dbHelper.getWritableDatabase(); String sql ="Delete from GiaoVien where magv= '"+GiaoVien.getMagv()+"'"; db.execSQL(sql); } public ArrayList<GiaoVien> LayDL() { ArrayList<GiaoVien> data = new ArrayList<>(); String sql="select * from GiaoVien"; SQLiteDatabase db= dbHelper.getReadableDatabase(); Cursor cursor = db.rawQuery(sql,null); cursor.moveToFirst(); do { GiaoVien GiaoVien = new GiaoVien(); GiaoVien.setMagv(cursor.getString(0)); GiaoVien.setTengv(cursor.getString(1)); GiaoVien.setSdt(cursor.getString(2)); data.add(GiaoVien); } while (cursor.moveToNext()); return data; } public ArrayList<GiaoVien> LayDL(String ma) { ArrayList<GiaoVien> data = new ArrayList<>(); String sql="select * from GiaoVien where MaGV = '" + ma +"'"; SQLiteDatabase db= dbHelper.getReadableDatabase(); Cursor cursor = db.rawQuery(sql,null); cursor.moveToFirst(); do { GiaoVien GiaoVien = new GiaoVien(); GiaoVien.setMagv(cursor.getString(0)); GiaoVien.setTengv(cursor.getString(1)); GiaoVien.setSdt(cursor.getString(2)); data.add(GiaoVien); } while (cursor.moveToNext()); return data; } public ArrayList<String> LayDLMGV() { ArrayList<String> data = new ArrayList<>(); String sql="select * from GiaoVien"; SQLiteDatabase db= dbHelper.getReadableDatabase(); Cursor cursor = db.rawQuery(sql,null); cursor.moveToFirst(); do { data.add(cursor.getString(0)); } while (cursor.moveToNext()); return data; } public ArrayList<GiaoVien> layTenGiaoVien(String ma) { ArrayList<GiaoVien> data = new ArrayList<>(); String sql = "select DISTINCT GiaoVien.MaGV, GiaoVien.TenGV, GiaoVien.SDT from MonHoc INNER JOIN TTChamBai ON MonHoc.mamonhoc = TTChamBai.mamonhoc INNER JOIN PhieuChamBai\n" + " ON TTChamBai.sophieu = PhieuChamBai.SoPhieu INNER JOIN GiaoVien ON PhieuChamBai.MaGV = GiaoVien.MaGV WHERE MonHoc.mamonhoc = '" + ma + "' ORDER BY MonHoc.tenmonhoc ASC"; SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.rawQuery(sql, null); cursor.moveToFirst(); do { GiaoVien giaoVien = new GiaoVien(); giaoVien.setMagv(cursor.getString(0)); giaoVien.setTengv(cursor.getString(1)); giaoVien.setSdt(cursor.getString(2)); data.add(giaoVien); } while (cursor.moveToNext()); return data; } }
package chapter08; import java.util.Scanner; public class Exercise08_05 { // m1 1 2 3 4 5 6 7 8 9 // m2 0 2 4 1 4,5 2,2 1,1 4,3 5,2 public static void main(String[] args) { double m1[][] = new double[3][3]; double m2[][] = new double[3][3]; Scanner input = new Scanner(System.in); System.out.println("Enter matrix1:"); for (int i = 0; i < m1.length; i++) { for (int j = 0; j < m1[i].length; j++) { m1[i][j] = input.nextDouble(); } } System.out.println("Enter matrix2:"); for (int i = 0; i < m2.length; i++) { for (int j = 0; j < m2[i].length; j++) { m2[i][j] = input.nextDouble(); } } double sumOfMatrix[][] = addMatrix(m1, m2); System.out.println("The matrices are added as follows"); for (int i = 0; i < sumOfMatrix.length; i++) { for (int j = 0; j < sumOfMatrix[i].length; j++) { System.out.print(sumOfMatrix[i][j] + " "); } System.out.println(); } } public static double[][] addMatrix(double[][] m1, double[][] m2) { double sum[][] = new double[3][3]; for (int i = 0; i < sum.length; i++) { for (int j = 0; j < sum[i].length; j++) { sum[i][j] = m1[i][j] + m2[i][j]; } } return sum; } }
package com.cn.jingfen.mapper; import java.util.List; import java.util.Map; public interface GridkdMapper { //流量出账收入日报 public List selctkd1Grid1(Map<String,Object> map); public List selctkd1Grid2(Map<String,Object> map); public List selctkd1Grid3(Map<String,Object> map); public List selctkd1Grid4(Map<String,Object> map); //魔百和发展日报 public List selctkd2Grid1(Map<String,Object> map); public List selctkd2Grid2(Map<String,Object> map); public List selctkd2Grid3(Map<String,Object> map); public List selctkd2Grid4(Map<String,Object> map); //宽带装机日报 public List selctkd3Grid1(Map<String,Object> map); public List selctkd3Grid2(Map<String,Object> map); public List selctkd3Grid3(Map<String,Object> map); public List selctkd3Grid4(Map<String,Object> map); //宽带装机日报 public List selctkd4Grid1(Map<String,Object> map); public List selctkd4Grid2(Map<String,Object> map); public List selctkd4Grid3(Map<String,Object> map); public List selctkd4Grid4(Map<String,Object> map); //宽带装机日报 public List selctkd5Grid1(Map<String,Object> map); public List selctkd5Grid2(Map<String,Object> map); public List selctkd5Grid3(Map<String,Object> map); public List selctkd5Grid4(Map<String,Object> map); }
package com.codezjsos.base.utils; import com.google.gson.GsonBuilder; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; /** * Created by zhufang on 2017/2/28. */ public class ScriptUtils { public static ScriptEngineManager scriptEngineManager=new ScriptEngineManager(); public static ScriptEngine engine=scriptEngineManager.getEngineByName("JavaScript"); public static Object invoke(String script,Object obj) throws Exception { String jsonstr=JsonUtils.toJson(obj); String functionname=script.replaceAll(".*function([^(]+).*","$1").trim(); engine.eval(script); Invocable invocable=(Invocable) engine; return invocable.invokeFunction(functionname,jsonstr); } public static void main(String[] args) throws Exception { //Object obj= ScriptUtils.invoke("function conver(jsonstr){ var jsonobj=JSON.parse(jsonstr); var v=jsonobj['msg']; if(v==null){ return \"{\\\"success\\\":false,\\\"msg\\\":\\\"msg字段未录入\\\"}\"; } var vv=v.match(/\\d+/)[0]; var vvv=jsonobj['date']; if(vvv==null){ return \"{\\\"success\\\":false,\\\"msg\\\":\\\"date字段未录入\\\"}\"; } var dates=vvv.split(/[-\\s]+/g); var year=parseInt(dates[0])+parseInt(vv); var month=dates[1]; var day=dates[2]; return \"{\\success\\\":true,\\\"msg\\\":\\\"转换成功\\\",\\\"data\\\":\\\"\"+year+\"-\"+month+\"-\"+day+\"\\\"}\"; }",MessageFactory.create().put("date","2013-01-01").put("msg","有效期2年").build()); //System.out.println(obj); } }
package com.example.myreadproject8.widget.search_view; public interface ICallBack { void SearchAction(String string); }
package controller.service.impl; import controller.exception.ServiceLayerException; import domain.User; import model.dao.impl.UserDAOImpl; import model.exception.DAOException; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; public class UserServiceImplTest { private UserDAOImpl userDAO; private UserServiceImpl userService; @Before public void setUp() throws Exception { userDAO = mock(UserDAOImpl.class); userService = new UserServiceImpl(userDAO); } @After public void tearDown() throws Exception { } @Test public void findUserByLoginData() throws DAOException, ServiceLayerException { when(userDAO.findUserByLoginData(any())).thenReturn(new User.UserBuilder().setLogin("login").createUser()); assertEquals("login", userService.findUserByLoginData(any()).getLogin()); assertNotNull(userService.findUserByLoginData(any())); verify(userDAO, atLeast(1)).findUserByLoginData(any()); } @Test public void isElementValid() { } }
package searching; public class TwoRepeatedElement { public static void main(String[] args) { int arr[] = { 1, 2, 1, 3, 4, 3 }; int res[] = twoRepeatedElement(arr); for (int e : res) { System.out.print(e + " "); } System.out.println(); } static int[] twoRepeatedElement(int arr[]) { int count[] = new int[arr.length - 1]; int res[] = new int[2]; int cnt = 0; for (int i = 0; i < arr.length; i++) { count[arr[i]]++; if (count[arr[i]] == 2) { if (cnt > 1) { break; } res[cnt++] = arr[i]; } } return res; } }
/* * Copyright (c) 2011. Peter Lawrey * * "THE BEER-WARE LICENSE" (Revision 128) * As long as you retain this notice you can do whatever you want with this stuff. * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return * There is no warranty. */ package com.google.code.java.core.parser; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; public class ByteBufferLongWriter implements LongWriter { private final ByteBuffer buffer; public ByteBufferLongWriter(ByteBuffer buffer) { this.buffer = buffer; } @Override public void write(long num) throws BufferOverflowException { buffer.putLong(num); } @Override public void close() { } }
import java.io.*; import java.util.*; import java.math.*; public class Main1 { static BigInteger C[][] = new BigInteger[110][110]; public static void main(String[] args) throws IOException { /*C[0][0] = BigInteger.ONE; for (int i = 1; i < 110; i++) { C[i][i] = C[i][0] = BigInteger.ONE; for (int j = 1; j < i; j++) C[i][j] = C[i-1][j].add(C[i-1][j-1]); } Scanner cin = new Scanner(System.in); BigInteger n; int k; BigInteger A[] = new BigInteger[110]; while (cin.hasNext()) { n = cin.nextBigInteger(); k = cin.nextInt(); A[0] = n; for (int i = 1; i <= k; i++) { A[i]=n.add(BigInteger.ONE).pow(i+1); A[i] = A[i].subtract(BigInteger.ONE); for (int j = 2; j <= i+1; j++) A[i] = A[i].subtract(C[i+1][j].multiply(A[i-j+1])); A[i] = A[i].divide(BigInteger.valueOf(i+1)); } System.out.println(A[k]); }*/ Scanner cin = new Scanner(System.in); BigDecimal a; BigDecimal b; BigDecimal c; BigInteger n; while (cin.hasNext()) { a = cin.nextBigDecimal(); b = cin.nextBigDecimal(); //b = cin.nextBigDecimal(); //c = a.mod(b); /*if (a.compareTo(b) == -1) c = a; else c = b;*/ c = a.divide(b); if (c.compareTo(BigDecimal.ZERO) == -1) c = c.multiply(new BigDecimal(-1)); System.out.println(c.toPlainString()); } } }
package br.com.mbreno.banco; public class Principal2 { public static void main(String[] args) { Pessoa p = new Pessoa(); p.nome = "Márcio"; } }
package com.smxknife.java2.bitset; /** * @author smxknife * 2021/7/14 */ public class BitMove { public static void main(String[] args) { int num = 5; num |= num >>> 1; System.out.println(num); num |= num >>> 2; System.out.println(num); num |= num >>> 4; System.out.println(num); num |= num >>> 8; System.out.println(num); num |= num >>> 16; System.out.println(num); System.out.println(num + 1); System.out.println(5 % 3); System.out.println(5 & num); } }
/* * Copyright (c) 2013 University of Tartu */ package org.jpmml.evaluator; import java.util.*; import org.dmg.pmml.*; import com.google.common.collect.*; abstract public class EvaluationContext { private Deque<Map<FieldName, ?>> stack = Queues.newArrayDeque(); public EvaluationContext(){ } public EvaluationContext(Map<FieldName, ?> arguments){ pushFrame(arguments); } abstract public DerivedField resolveField(FieldName name); abstract public DefineFunction resolveFunction(String name); public Map<FieldName, ?> getArguments(){ Map<FieldName, Object> result = Maps.newLinkedHashMap(); Deque<Map<FieldName, ?>> stack = getStack(); // Iterate from last (ie. oldest) to first (ie. newest) Iterator<Map<FieldName, ?>> it = stack.descendingIterator(); while(it.hasNext()){ Map<FieldName, ?> frame = it.next(); result.putAll(frame); } return result; } public Object getArgument(FieldName name){ Deque<Map<FieldName, ?>> stack = getStack(); // Iterate from first to last Iterator<Map<FieldName, ?>> it = stack.iterator(); while(it.hasNext()){ Map<FieldName, ?> frame = it.next(); if(frame.containsKey(name)){ return frame.get(name); } } return null; } public Map<FieldName, ?> popFrame(){ return getStack().pop(); } public void pushFrame(Map<FieldName, ?> frame){ getStack().push(frame); } Deque<Map<FieldName, ?>> getStack(){ return this.stack; } }
import org.json.JSONObject; import java.io.Serializable; import java.util.Date; public class Message implements Serializable { private MessageType type; private String data; private String roomId; private String sender; public Message() { type = null; data = null; roomId = null; } public String getSender() { return sender; } public void setSender(String sender) { this.sender = sender; } public MessageType getType() { return type; } public String getData() { return data; } public String getRoomId() { return roomId; } public void setType(MessageType type) { this.type = type; } public void setData(String data) { this.data = data; } public void setRoomId(String roomId) { this.roomId = roomId; } public JSONObject createJSON(Date date){ JSONObject messageJSON = new JSONObject(); messageJSON.put("type", type); if(data == null){ }else { messageJSON.put("data", data); } messageJSON.put("sender", sender); messageJSON.put("date", date.getTime()); return messageJSON; } }
import com.dimple.evaluation.service.EamsRecordService; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * @className: Test * @description: * @auther: Dimple * @Date: 2019/4/18 * @Version: 1.0 */ @SpringBootTest @RunWith(SpringRunner.class) public class Test { @Autowired EamsRecordService recordService; @org.junit.Test public void test() { } }
package it.unibz.testhunter; import it.unibz.testhunter.shared.TException; public interface IStatusResolver { boolean isStatusFailed(Long testStatusId) throws TException; }
/** * */ package com.goodhealth.design.demo.AbstractFactoryMethod; /** * @author 24663 * @date 2019年2月24日 * @Description */ public class BWM implements Car { /* (non-Javadoc) * @see com.goodhealth.design.demo.FactoryMethod.Car#run() */ @Override public void run() { // TODO Auto-generated method stub System.out.println("100迈的宝马"); } /* (non-Javadoc) * @see com.goodhealth.design.demo.FactoryMethod.Car#staop() */ @Override public void singing() { // TODO Auto-generated method stub System.out.println("叭叭"); } }
package com.base; import java.util.List; public interface BaseDao { <T extends BaseEntity> List<T> getList(String sql,Class<T> clazz,BaseEntity baseEntity); <T extends BaseEntity> T getOne(String sql,Class<T> clazz,BaseEntity baseEntity); int update (String sql,BaseEntity baseEntity); int delete (String sql,BaseEntity baseEntity); }
package com.oasisfeng.island.util; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.AssetManager; import android.os.Environment; import android.os.IBinder; import android.os.PowerManager; import android.os.RemoteException; import android.os.UserHandle; import android.os.UserManager; import android.print.PrintManager; import android.util.Log; import com.oasisfeng.android.annotation.UserIdInt; import com.oasisfeng.hack.Hack; import com.oasisfeng.hack.Hack.Unchecked; import com.oasisfeng.island.analytics.Analytics; import com.oasisfeng.island.shared.BuildConfig; import java.io.File; import java.net.InetAddress; import java.util.List; import java.util.Map; import javax.annotation.ParametersAreNonnullByDefault; import androidx.annotation.Keep; import androidx.annotation.Nullable; import androidx.annotation.RequiresApi; import androidx.annotation.RequiresPermission; import static android.os.Build.VERSION.PREVIEW_SDK_INT; import static android.os.Build.VERSION.SDK_INT; import static android.os.Build.VERSION_CODES.M; import static android.os.Build.VERSION_CODES.N; import static android.os.Build.VERSION_CODES.O_MR1; import static android.os.Build.VERSION_CODES.P; /** * All reflection-based hacks should be defined here * * Created by Oasis on 2016/8/10. */ public class Hacks { static { Hack.setAssertionFailureHandler(e -> { Log.e("Compatibility", e.getDebugInfo()); if (BuildConfig.DEBUG) throw new IllegalStateException("Incompatibility", e); if (Users.isOwner()) Analytics.$().report(e); }); } private static final int MATCH_ANY_USER = 0x00400000; // Requires INTERACT_ACROSS_USERS since Android P. /** * When used in @ApplicationInfoFlags or @PackageInfoFlags: * For owner user, GET_UNINSTALLED_PACKAGES implicitly set MATCH_ANY_USER. * For managed profile, MATCH_ANY_USER requires permission INTERACT_ACROSS_USERS since Android P. * When used in @ComponentInfoFlags or @ResolveInfoFlags: MATCH_ANY_USER is always allowed. * * See PackageManagerService.updateFlagsForPackage() */ public static final int GET_ANY_USER_AND_UNINSTALLED = PackageManager.GET_UNINSTALLED_PACKAGES | (Users.isOwner() ? 0 : MATCH_ANY_USER); public static final int RESOLVE_ANY_USER_AND_UNINSTALLED = PackageManager.GET_UNINSTALLED_PACKAGES | MATCH_ANY_USER; public static final Hack.HackedField<ApplicationInfo, Integer> ApplicationInfo_privateFlags = Hack.onlyIf(SDK_INT >= M).into(ApplicationInfo.class).field("privateFlags").fallbackTo(null); public static final Hack.HackedField<ApplicationInfo, Integer> ApplicationInfo_versionCode = Hack.into(ApplicationInfo.class).field("versionCode").fallbackTo(0); public static final Hack.HackedTargetField<String> PrintManager_PRINT_SPOOLER_PACKAGE_NAME = Hack.onlyIf(SDK_INT >= N && SDK_INT <= O_MR1).into(PrintManager.class) .staticField("PRINT_SPOOLER_PACKAGE_NAME").fallbackTo("com.android.printspooler"); public static final Hack.HackedField<PowerManager, Object> PowerManager_mService = Hack.into(PowerManager.class).field("mService").fallbackTo(null); public static final Hack.HackedTargetField<Object> InetAddress_addressCache = SDK_INT >= N ? Hack.into("java.net.Inet6AddressImpl").staticField("addressCache").fallbackTo(null) : Hack.into(InetAddress.class).staticField("addressCache").fallbackTo(null); public static final Hack.HackedField<Object, Object> AddressCache_cache = Hack.into("java.net.AddressCache").field("cache").fallbackTo(null); public static final Hack.HackedField<Object, Map> BasicLruCache_map = Hack.into("libcore.util.BasicLruCache").field("map").fallbackTo(null); public static final Hack.HackedField<Object, Object> AddressCacheKey_mHostname = Hack.into("java.net.AddressCache$AddressCacheKey").field("mHostname").fallbackTo(null); public static final Hack.HackedField<Object, Object> AddressCacheEntry_expiryNanos = Hack.into("java.net.AddressCache$AddressCacheEntry").field("expiryNanos").fallbackTo(null); public static final Hack.HackedMethod2<Boolean, Void, Unchecked, Unchecked, Unchecked, String, Boolean> SystemProperties_getBoolean = Hack.into("android.os.SystemProperties").staticMethod("getBoolean") .returning(boolean.class).fallbackReturning(false).withParams(String.class, boolean.class); public static final Hack.HackedMethod2<Integer, Void, Unchecked, Unchecked, Unchecked, String, Integer> SystemProperties_getInt = Hack.into("android.os.SystemProperties").staticMethod("getInt") .returning(int.class).fallbackReturning(null).withParams(String.class, int.class); static final Hack.HackedMethod0<ComponentName, DevicePolicyManager, IllegalArgumentException, Unchecked, Unchecked> DevicePolicyManager_getProfileOwner = Hack.into(DevicePolicyManager.class).method("getProfileOwner") .returning(ComponentName.class).fallbackReturning(null).throwing(IllegalArgumentException.class).withoutParams(); static final Hack.HackedMethod1<ComponentName, DevicePolicyManager, IllegalArgumentException, Unchecked, Unchecked, Integer> DevicePolicyManager_getProfileOwnerAsUser = Hack.onlyIf(! isAndroidQ()).into(DevicePolicyManager.class).method("getProfileOwnerAsUser") .returning(ComponentName.class).fallbackReturning(null).throwing(IllegalArgumentException.class).withParam(int.class); static final Hack.HackedMethod0<String, DevicePolicyManager, Unchecked, Unchecked, Unchecked> DevicePolicyManager_getDeviceOwner = Hack.into(DevicePolicyManager.class).method("getDeviceOwner") .returning(String.class).fallbackReturning(null).withoutParams(); public static final Hack.HackedMethod4<Boolean, Context, Unchecked, Unchecked, Unchecked, Intent, ServiceConnection, Integer, UserHandle> Context_bindServiceAsUser = Hack.into(Context.class).method("bindServiceAsUser").returning(boolean.class) .fallbackReturning(false).withParams(Intent.class, ServiceConnection.class, int.class, UserHandle.class); @RequiresApi(N) public static final @Nullable Hack.HackedMethod2<int[], UserManager, Unchecked, Unchecked, Unchecked, Integer, Boolean> UserManager_getProfileIds = SDK_INT < N || SDK_INT > O_MR1 ? null : Hack.into(UserManager.class).method("getProfileIds") .returning(int[].class).withParams(int.class, boolean.class); public static final Hack.HackedMethod3<Context, Context, NameNotFoundException, Unchecked, Unchecked, String, Integer, UserHandle> Context_createPackageContextAsUser = Hack.into(Context.class).method("createPackageContextAsUser").returning(Context.class) .fallbackReturning(null).throwing(NameNotFoundException.class).withParams(String.class, int.class, UserHandle.class); static final Hack.HackedMethod2<Context, Context, NameNotFoundException, Unchecked, Unchecked, ApplicationInfo, Integer> Context_createApplicationContext = Hack.into(Context.class).method("createApplicationContext").returning(Context.class) .fallbackReturning(null).throwing(NameNotFoundException.class).withParams(ApplicationInfo.class, int.class); public static final @Nullable Hack.HackedMethod1<IBinder, Void, Unchecked, Unchecked, Unchecked, String> ServiceManager_getService = Hack.into("android.os.ServiceManager").staticMethod("getService") .returning(IBinder.class).withParam(String.class); private static final String IWebViewUpdateService = "android.webkit.IWebViewUpdateService"; public static final @Nullable Hack.HackedMethod1<?, Void, Unchecked, Unchecked, Unchecked, IBinder> IWebViewUpdateService$Stub_asInterface = Hack.into(IWebViewUpdateService + "$Stub").staticMethod("asInterface") .returning(Hack.ANY_TYPE).withParam(IBinder.class); @RequiresApi(N) public static final @Nullable Hack.HackedMethod0<String, Object, RemoteException, Unchecked, Unchecked> IWebViewUpdateService_getCurrentWebViewPackageName = SDK_INT < N ? null : Hack.into(IWebViewUpdateService).method("getCurrentWebViewPackageName") .returning(String.class).throwing(RemoteException.class).withoutParams(); public static final @Nullable Hack.HackedMethod0<File, Void, Unchecked, Unchecked, Unchecked> Environment_getDataSystemDirectory = Hack.into(Environment.class) .staticMethod(SDK_INT < N ? "getSystemSecureDirectory" : "getDataSystemDirectory").returning(File.class).withoutParams(); public static final @Nullable Hack.HackedMethod0<AssetManager, Void, Unchecked, Unchecked, Unchecked> AssetManager_constructor = Hack.into(AssetManager.class).constructor().withoutParams(); public static final @Nullable Hack.HackedMethod1<Integer, AssetManager, Unchecked, Unchecked, Unchecked, String> AssetManager_addAssetPath = Hack.into(AssetManager.class).method("addAssetPath").returning(int.class).withParam(String.class); public static final @Nullable Hack.HackedMethod3<Void, Object, Hack.Unchecked, Hack.Unchecked, Hack.Unchecked, String, Integer, InetAddress[]> AddressCache_put = Hack.onlyIf(SDK_INT <= P).into("java.net.AddressCache").method("put") .withParams(String.class, int.class, InetAddress[].class); @Keep @ParametersAreNonnullByDefault public interface AppOpsManager extends Hack.Mirror<android.app.AppOpsManager> { @Keep interface PackageOps extends Hack.Mirror { String getPackageName(); int getUid(); List<OpEntry> getOps(); } @Keep interface OpEntry extends Hack.Mirror { int getOp(); int getMode(); } @Hack.Fallback(-1) int checkOpNoThrow(final int op, final int uid, final String pkg); @Nullable List<PackageOps> getOpsForPackage(int uid, String pkg, @Nullable int[] ops); @Nullable List<PackageOps> getPackagesForOps(@Nullable int[] ops); void setMode(int code, int uid, String packageName, int mode); /** Retrieve the default mode for the operation. */ @Hack.Fallback(-1) int opToDefaultMode(final int op); } public interface UserManagerHack extends Hack.Mirror<UserManager> { @Hack.SourceClass("android.content.pm.UserInfo") interface UserInfo extends Hack.Mirror { int getId(); UserHandle getUserHandle(); } /** Requires permission MANAGE_USERS only if userHandle is not current user */ List<UserInfo> getProfiles(int userHandle); @RequiresPermission("android.permission.MANAGE_USERS") List<UserInfo> getUsers(); boolean removeUser(@UserIdInt int userHandle); } static { if (BuildConfig.DEBUG) Hack.verifyAllMirrorsIn(Hacks.class); } private static boolean isAndroidQ() { return SDK_INT > O_MR1 + 1/* P */|| (SDK_INT > O_MR1 && PREVIEW_SDK_INT > 0); } }
package com.decrypt.beeglejobsearch.data.network; public interface RestService { }
package cn.bs.zjzc.presenter; import android.widget.TextView; import cn.bs.zjzc.App; import cn.bs.zjzc.base.IBasePresenter; import cn.bs.zjzc.model.IOrderDetailModel; import cn.bs.zjzc.model.callback.HttpTaskCallback; import cn.bs.zjzc.model.impl.OderDetailModer; import cn.bs.zjzc.model.response.BaseResponse; import cn.bs.zjzc.model.response.OrderDetail; import cn.bs.zjzc.net.GsonCallback; import cn.bs.zjzc.net.PostHttpTask; import cn.bs.zjzc.net.RequestUrl; import cn.bs.zjzc.ui.view.IOrderDetailView; import cn.bs.zjzc.util.CheckCodeTimer; /** * Created by Administrator on 2016/6/29. */ public class OrderDetailPresenter implements IBasePresenter { private IOrderDetailView mOrderDetailView; private IOrderDetailModel mOrderDetailModel; public OrderDetailPresenter(IOrderDetailView mOrderDetailView) { this.mOrderDetailView = mOrderDetailView; mOrderDetailModel = new OderDetailModer(); } public void getOrderDetail(String orderType, String order_id) { mOrderDetailView.showLoading("数据加载中..."); mOrderDetailModel.getOrderDetail(orderType, order_id, new HttpTaskCallback<OrderDetail>() { @Override public void onTaskFailed(String errorInfo) { mOrderDetailView.showMsg(errorInfo); mOrderDetailView.hideLoading(); } @Override public void onTaskSuccess(OrderDetail data) { mOrderDetailView.showData(data); mOrderDetailView.hideLoading(); } }); } public void confirmTakeGoogs(String orderType, String order_id) { mOrderDetailView.showLoading("确认中..."); mOrderDetailModel.confirmTakeGoods(orderType, order_id, new HttpTaskCallback<BaseResponse>() { @Override public void onTaskFailed(String errorInfo) { mOrderDetailView.showMsg(errorInfo); mOrderDetailView.hideLoading(); } @Override public void onTaskSuccess(BaseResponse data) { mOrderDetailView.confirmTakeSuccess(); mOrderDetailView.hideLoading(); } }); } /** * 验证完成订单,获取验证码 * * @param order_id 订单id * @param phone 接收验证码的手机 * @param v 倒计时的TextView */ public void getCode(String order_id, String phone, final TextView v) { String url = RequestUrl.getRequestPath(RequestUrl.SubPaths.sendCode); PostHttpTask<BaseResponse> httpTask = new PostHttpTask<BaseResponse>(url); httpTask.addParams("token", App.LOGIN_USER.getToken()) .addParams("order_id", order_id) .addParams("phone", phone) .execute(new GsonCallback<BaseResponse>() { @Override public void onFailed(String errorInfo) { mOrderDetailView.showMsg(errorInfo); } @Override public void onSuccess(BaseResponse response) { new CheckCodeTimer(v).start(); } }); } /** * 完成订单验证 * * @param order_id 订单id * @param isWaimai 是否是外卖(如果为外卖,则code可以为空) * @param code 验证码 */ public void orderCompleted(String order_id, boolean isWaimai, String code) { String url = RequestUrl.getRequestPath(RequestUrl.SubPaths.finishOrder); PostHttpTask<BaseResponse> httpTask = new PostHttpTask<BaseResponse>(url); if (!isWaimai) { //不是外卖 httpTask.addParams("token", App.LOGIN_USER.getToken()) .addParams("order_id", order_id) .addParams("code", code) .execute(new GsonCallback<BaseResponse>() { @Override public void onFailed(String errorInfo) { mOrderDetailView.showMsg(errorInfo); mOrderDetailView.orderCompletedSuccess(); } @Override public void onSuccess(BaseResponse response) { mOrderDetailView.showMsg(response.errinfo); mOrderDetailView.orderCompletedSuccess(); } }); } else { httpTask.addParams("token", App.LOGIN_USER.getToken()) .addParams("order_id", order_id) .execute(new GsonCallback<BaseResponse>() { @Override public void onFailed(String errorInfo) { mOrderDetailView.showMsg(errorInfo); mOrderDetailView.orderCompletedSuccess(); } @Override public void onSuccess(BaseResponse response) { mOrderDetailView.showMsg(response.errinfo); mOrderDetailView.orderCompletedSuccess(); } }); } } }
package stack; import java.util.Stack; public class Programmars_2 { public static void main(String[] args){ Programmars_2 s = new Programmars_2(); String arrangement = "()(((()())(())()))(())"; System.out.println(s.solution(arrangement)); } public int solution(String arrangement){ int answer = 0; int sticks = 0; int lazer = 0; Stack<Character> stack = new Stack<>(); for(int i=0; i < arrangement.length(); i++){ char curr = arrangement.charAt(i); if(stack.isEmpty()){ stack.push(curr); continue; } if(stack.peek() == '(' && curr == ')'){ lazer++; answer += sticks; } else if(stack.peek() == '(' && curr == '('){ sticks++; answer++; } else if(stack.peek() == ')' && curr == '('){ if(lazer > 0){ lazer--; } else { sticks--; } } else { sticks--; } stack.push(curr); } return answer; } }
package com.example.graphqldemo.entity; import java.util.List; import jakarta.persistence.Entity; import jakarta.persistence.FetchType; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.ManyToMany; import lombok.Data; @Data @Entity public class Book { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private int pageCount; private Long authorId; @ManyToMany(fetch = FetchType.EAGER) private List<Genre> genres; }
package Task2; import Task2.Fruit.Fruit; import Task1.ArrayScroll; public class Box<T extends Fruit> { private ArrayScroll<T> elements; private float totalWeight; public Box() { elements = new ArrayScroll<>(); } public Box<T> add(T fruit) { elements.add(fruit); this.totalWeight += fruit.getWeight(); return this; } public void remove(T fruit) { elements.remove(fruit); this.totalWeight -= fruit.getWeight(); } float getWeight() { return this.totalWeight; } public boolean compare(Box box) { return this.getWeight() == box.getWeight(); } public void mergeToBox(Box<T> box) { while (this.elements.size() != 0) { box.add(this.elements.get(0)); remove(this.elements.get(0)); } } }
package createLogin; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Set; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ReadExcelFile { public static String filePath = "C:\\Others\\workspace\\RestAssuredAPI\\testSelVal\\src\\test\\java\\createLogin"; String colval1; ArrayList<String> ar = new ArrayList<String>(); @SuppressWarnings("resource") public ArrayList<String> readExcel(String filePath, String fileName, String sheetName) throws IOException { File file = new File(filePath + "\\" + fileName); FileInputStream inputStream = new FileInputStream(file); Workbook Workbook = null; String fileExtensionName = fileName.substring(fileName.indexOf(".")); if (fileExtensionName.equals(".xlsx")) { Workbook = new XSSFWorkbook(inputStream); } else if (fileExtensionName.equals(".xls")) { Workbook = new HSSFWorkbook(inputStream); } Sheet Sheet = Workbook.getSheet(sheetName); int rowCount = Sheet.getLastRowNum() - Sheet.getFirstRowNum(); for (int i = 0; i < rowCount; i++) { Row row = Sheet.getRow(i + 1); int j = 0; colval1 = row.getCell(j).getStringCellValue(); ar.add(colval1); } return ar; } public static void main(String... strings) throws IOException { ReadExcelFile objExcelFile = new ReadExcelFile(); ArrayList<String> finalList = objExcelFile.readExcel(filePath, "ExportExcel.xlsx", "ExcelDemo"); for (String val1 : finalList) { System.out.println(val1); } } }
package com.ld.baselibrary.base; import android.app.Application; import android.os.Handler; import androidx.annotation.NonNull; import androidx.databinding.ObservableArrayList; import androidx.databinding.ObservableList; import com.scwang.smartrefresh.layout.api.RefreshLayout; import com.scwang.smartrefresh.layout.constant.RefreshState; import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener; import java.lang.ref.WeakReference; import java.util.List; import me.tatarka.bindingcollectionadapter2.BindingRecyclerViewAdapter; import me.tatarka.bindingcollectionadapter2.ItemBinding; import me.tatarka.bindingcollectionadapter2.collections.MergeObservableList; /** * @author: liangduo * @date: 2021/4/13 2:44 PM */ public abstract class BaseListViewModel<M extends AbsRepository, T, VM extends MultiItemViewModel> extends BaseViewModel<M>{ // 当前页数 public int pageSize = 10; // 当前页数 public int pageNo = 1; // 下拉刷新控件 protected WeakReference<RefreshLayout> mRefreshLayout; // 是否在刷新/加载中 public boolean isLoadAndRefresh = false; // 数据源 public MergeObservableList<T> mList = new MergeObservableList<>(); // databing public ItemBinding<VM> itemBinding = initItemBinding(); // 多布局数据源(多数据源) public MergeObservableList<VM> observableList = new MergeObservableList<>(); // adapter private BindingRecyclerViewAdapter<VM> adapter; // 刷新,加载更多监听 public OnRefreshLoadMoreListener onRefreshLoadMoreListener; public BaseListViewModel(@NonNull Application application) { super(application); // 刷新,加载更多监听 initRefreshLoadMoreListener(); } protected abstract ItemBinding initItemBinding(); protected abstract void conversionItemViewModel(ObservableList<T> list); protected void addList(VM itemViewModel) { observableList.insertItem(itemViewModel); } public void delItem(VM item) { observableList.removeItem(item); } /** * 填充数据 */ public void setData(List<T> data) { this.setData(data, false); } /** * 填充数据 */ public void setData(List<T> data, boolean isShow) { if (data != null && data.size() > 0) { if (pageNo == 1 || (mRefreshLayout != null && mRefreshLayout.get().getState() == RefreshState.Refreshing)) { mList.removeAll(); // 先移除监听,防止闪烁占位图 // observableList.removeOnListChangedCallback(onListChangedCallback); observableList.removeAll(); // observableList.addOnListChangedCallback(onListChangedCallback); } // 转变类型 ObservableList observableList = new ObservableArrayList(); observableList.addAll(data); conversionItemViewModel(observableList); initItemBinding(); // if (isShow && data.size() < getPageSize()) { // setNoMoreData(true); // } else { // setNoMoreData(false); // if (mRefreshLayout != null && (mRefreshLayout.get().getState() == RefreshState.Refreshing // || mRefreshLayout.get().getState() == RefreshState.Loading)) { // onFinishRefreshLoadMore(); // } // } // if (mStatus != PageStatus.SUCCSE) { // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // showSuccessView(); // } // }, 1000); // } } else { if (mRefreshLayout != null && mRefreshLayout.get().getState() == RefreshState.Loading) { pageNo--; // if (isShow) { // setNoMoreData(true); // } else { // setNoMoreData(false); // onFinishRefreshLoadMore(); // showToast(getString(R.string.all_information_loaded)); // } } else { mList.removeAll(); observableList.removeAll(); // showModelEmptyView(); // setNoMoreData(false); } } onFinishRefreshLoadMore(); } public void initRefreshLoadMoreListener(){ onRefreshLoadMoreListener = new OnRefreshLoadMoreListener() { @Override public void onLoadMore(RefreshLayout refreshLayout) { pageNo++; isLoadAndRefresh = true; setRefresh(refreshLayout); onRefreshLoadMore(); } @Override public void onRefresh(RefreshLayout refreshLayout) { pageNo = 1; isLoadAndRefresh = true; setRefresh(refreshLayout); onRefreshLoadMore(); } }; } public void setRefresh(RefreshLayout refreshLayout) { if (mRefreshLayout == null) { this.mRefreshLayout = new WeakReference<>(refreshLayout); } } public int getPageNo() { return pageNo; } public void setPageNo(int pageNo) { this.pageNo = pageNo; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } /** * 刷新动作 */ public abstract void onRefreshLoadMore(); /** * 执行结束动作 */ protected void onFinishRefreshLoadMore() { if (mRefreshLayout != null) { if (mRefreshLayout.get().getState() == RefreshState.Refreshing) { mRefreshLayout.get().finishRefresh(); } else { mRefreshLayout.get().finishLoadMore(); } } } }
package com.ai.lovejoy777.ant; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.pm.ComponentInfo; import android.util.Log; public class OnAlarmReceiver extends BroadcastReceiver { private static final String TAG = ComponentInfo.class.getCanonicalName(); @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "Received wake up from alarm manager."); long rowid = intent.getExtras().getLong(TimerDbAdapter.KEY_ROWID); String name = intent.getExtras().getString(TimerDbAdapter.KEY_NAME); String swname = intent.getExtras().getString(TimerDbAdapter.KEY_SWNAME); WakeTimerIntentService.acquireStaticLock(context); Intent i = new Intent(context, TimerService.class); i.putExtra(TimerDbAdapter.KEY_ROWID, rowid); i.putExtra(TimerDbAdapter.KEY_NAME, name); i.putExtra(TimerDbAdapter.KEY_SWNAME, swname); context.startService(i); } }
package com.mimi.mimigroup.model; public class DM_Province { private int Provinceid; private String ZoneCode; private String Province; private String ProvinceCode; public DM_Province(){} public DM_Province(Integer Provinceid,String ZoneCode,String Province,String ProvinceCode){ this.Provinceid=Provinceid; this.ZoneCode=ZoneCode; this.Province=Province; this.ProvinceCode=ProvinceCode; } public Integer getProvinceid(){return this.Provinceid;} public void setProvinceid(Integer Provinceid){this.Provinceid=Provinceid;} public String getProvince(){return this.Province;} public void setProvince(String Province){this.Province=Province;} public String getZoneCode(){return this.ZoneCode;} public void setZoneCode(String ZoneCode){this.ZoneCode=ZoneCode;} public String getProvinceCode(){return this.ProvinceCode;} public void setProvinceCode(String ProvinceCode){this.ProvinceCode=ProvinceCode;} }
package mouse.server; import mouse.server.network.MouseServer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; /** * This class is intended to run without a client. Mainly for dev and debug purposes. * * User: Simon * Date: 26.03.14 */ public class StandaloneServer { private static final Logger log = LoggerFactory.getLogger(StandaloneServer.class); public static void main(String[] args) { log.info("Starting mouse server in standalone version"); MouseServer server = new MouseServer(); if (!server.start()) return; log.info("Press any key to shutdown the standalone server"); try { System.in.read(); server.stop(); } catch (IOException ex) { log.warn("Exception while listening on System.in.", ex); } } }
package temakereso.service; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import temakereso.entity.Topic; import temakereso.helper.AttachmentDto; import temakereso.helper.StudentDto; import temakereso.helper.TopicDto; import temakereso.helper.TopicFilters; import temakereso.helper.TopicInputDto; import temakereso.helper.TopicListerDto; import java.util.List; import java.util.Set; public interface TopicService { /** * Returns a topic by identifier * * @param id identifier of topic * @return topic with the given identifier */ TopicDto getOneById(Long id); /** * Returns a page of topics filtered by parameters * * @param pageable page data * @param filters filters * @return a page of topic dtos */ Page<TopicListerDto> getFilteredOnesByPage(TopicFilters filters, Pageable pageable); /** * Creates a new topic * * @param supervisorId identifier of the supervisor * @param topic topic to be saved * @return the saved topic */ Long createTopic(Long supervisorId, TopicInputDto topic); /** * Modifies a topic * * @param id identifier of topic * @param topicDto topic to be modified * @return the modified topic */ Long modifyTopic(Long id, TopicInputDto topicDto); /** * Archives the topic selected by the given id * * @param id identifier of topic */ void archiveTopic(Long id); /** * Unarchives the topic selected by the given id * * @param id identifier of topic */ void unarchiveTopic(Long id); /** * Adds an attachment to the topic selected by its identifier. * * @param topicId identifier of topic * @param attachmentDto attachment data */ void addAttachment(Long topicId, AttachmentDto attachmentDto); /** * Removes the selected attachment to the topic selected by its identifier. * * @param topicId identifier of topic * @param attachmentId id of attachment */ void removeAttachment(Long topicId, Long attachmentId); /** * Saves a student's application. * * @param topicId identifier of topic the student applied to * @param studentId identifier of student */ void applyStudent(Long topicId, Long studentId); /** * Removes a student's application. * * @param topicId identifier of topic the student applied to * @param studentId identifier of student */ void removeApplication(Long topicId, Long studentId); /** * Finds students applied to the topic. * * @param topicId identifier of topic * @return collection of student data */ Set<StudentDto> getAppliedStudents(Long topicId); /** * Finds topics the student applied to. * * @param studentId identifier of student * @return collection of topic data */ Set<TopicDto> getTopicsAssignedToStudent(Long studentId); /** * Finds the supervisor's topics. * * @param supervisorId identifier of supervisor * @return collection of topic data */ List<TopicDto> getSupervisorTopics(Long supervisorId); /** * Supervisor accepts application of student. * * @param topicId identifier of topic * @param studentId identifier of student */ void acceptApplication(Long topicId, Long studentId); /** * Sets topic status done. * * @param topicId identifier of topic */ void setTopicDone(Long topicId); /** * Finds topics. * * @param filters filters * @return a collection of topics */ List<Topic> getFilteredOnes(TopicFilters filters); /** * Finds topics to archive. * * @return a collection of topics */ List<Topic> findTopicsToArchive(); }
package com.keeptrack.web.serve.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.keeptrack.domain.entity.DummyEntity; import com.keeptrack.web.dao.DummyDao; import com.keeptrack.web.service.DummyService; @Transactional @Service("dummyService") public class DummyServiceImpl implements DummyService { private DummyDao dummyDao; public void createNewEntity(DummyEntity entityModel) { getDummyDao().save(entityModel); } public DummyDao getDummyDao() { return dummyDao; } @Autowired public void setDummyDao(DummyDao dummyDao) { this.dummyDao = dummyDao; } }
package controllers; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import models.FootballClub; import play.libs.Json; import models.Match; import play.mvc.Controller; import play.mvc.Http; import play.mvc.Result; import services.MatchService; import utils.ApplicationUtil; import java.util.ArrayList; public class MatchController extends Controller { public Result getAllMatches(){ ArrayList<Match> matches = new ArrayList<>(); MatchService.getInstance().setMatches(ApplicationUtil.loadMatch(matches)); ArrayList<Match> allMatches = (ArrayList<Match>) MatchService.getInstance().getMatches(); ObjectMapper mapper = new ObjectMapper(); JsonNode jsonData = mapper.convertValue(allMatches,JsonNode.class); return ok(jsonData); } public Result addMatch(Http.Request request){ /** * POST request * # resource link * https://www.playframework.com/documentation/2.8.x/JavaJsonActions */ JsonNode jsonNode = request.body().asJson(); if (jsonNode == null){ return badRequest("Error"); } Match match = Json.fromJson(jsonNode, Match.class); System.out.println(match); ArrayList<FootballClub> footballClubs = new ArrayList<>(); MatchService.getInstance().setFootballClubs(ApplicationUtil.loadClub(footballClubs)); ArrayList<Match> matches = new ArrayList<>(); MatchService.getInstance().setMatches(ApplicationUtil.loadMatch(matches)); MatchService.getInstance().addMatch(match); ApplicationUtil.saveData(footballClubs,matches); JsonNode jsonObject = Json.toJson(match); return created(ApplicationUtil.createResponse(jsonObject,true)); } }
package nl.jtosti.hermes.location.advice; import nl.jtosti.hermes.location.exception.LocationNotFoundException; import nl.jtosti.hermes.util.ErrorDTO; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; @ControllerAdvice public class LocationNotFoundAdvice { @ResponseBody @ExceptionHandler(LocationNotFoundException.class) @ResponseStatus(HttpStatus.NOT_FOUND) ErrorDTO locationNotFoundHandler(LocationNotFoundException ex) { return new ErrorDTO(ex.getMessage()); } }
execute(des, src, registers, memory) { Calculator calculator = new Calculator(registers, memory); int desSize = 0; int srcSize = 0; if( des.isRegister() ) { desSize = registers.getBitSize(des); } if( src.isRegister() ) { srcSize = registers.getBitSize(src); } else { srcSize = memory.getBitSize(src); } if( des.isRegister() ) { if( src.isRegister() ) { if( (desSize == srcSize) && checkSizeOfRegister(registers, desSize) ) { String source = registers.get(src); String destination = registers.get(des); storeResultToRegister(registers, calculator, des, source, destination, desSize); } } else if( src.isMemory() ) { if( checkSizeOfRegister(registers, desSize) ) { String source = memory.read(src, desSize); String destination = registers.get(des); storeResultToRegister(registers, calculator, des, source, destination, desSize); } } } } storeResultToRegister(registers, calculator, des, source, destination, desSize) { String result = ""; Token token = new Token(Token.REG, "EAX"); BigInteger biDes = new BigInteger("0", 16); BigInteger dwordpos = new BigInteger("7FFF", 16); BigInteger neg = new BigInteger("8000", 16); Long dwordneg = calculator.convertToSignedInteger(neg, 16); if( desSize == 64 ) { for(int i = 0; i <= 8; i+=8) { if( i == 8 ) { biDes = new BigInteger(source.substring(i), 16); } else { biDes = new BigInteger(source.substring(i, i + 8), 16); } String temp = calculator.hexToBinaryString(biDes.toString(16), token); String sign = temp.charAt(0) + ""; if( sign.equals("0") ) { if( biDes.compareTo(dwordpos) == 1 ) { result += "7FFF"; } else { if( i == 8 ) { result += source.substring(i + 4); } else { result += source.substring(i + 4, i + 8); } } } else if( sign.equals("1") ) { Long signedInt = calculator.convertToSignedInteger(biDes, 16); if( signedInt < dwordneg ) { result += "8000"; } else { if( i == 8 ) { result += source.substring(i + 4); } else { result += source.substring(i + 4, i + 8); } } } } for(int i = 0; i <= 8; i+=8) { if( i == 8 ) { biDes = new BigInteger(destination.substring(i), 16); } else { biDes = new BigInteger(destination.substring(i, i + 8), 16); } String temp = calculator.hexToBinaryString(biDes.toString(16), token); String sign = temp.charAt(0) + ""; if( sign.equals("0") ) { if( biDes.compareTo(dwordpos) == 1 ) { result += "7FFF"; } else { if( i == 8 ) { result += destination.substring(i + 4); } else { result += destination.substring(i + 4, i + 8); } } } else if( sign.equals("1") ) { Long signedInt = calculator.convertToSignedInteger(biDes, 16); if( signedInt < dwordneg ) { result += "8000"; } else { if( i == 8 ) { result += destination.substring(i + 4); } else { result += destination.substring(i + 4, i + 8); } } } } } else if( desSize == 128 ) { for(int i = 0; i <= 24; i+=8) { if( i == 24 ) { biDes = new BigInteger(source.substring(i), 16); } else { biDes = new BigInteger(source.substring(i, i + 8), 16); } String temp = calculator.hexToBinaryString(biDes.toString(16), token); String sign = temp.charAt(0) + ""; if( sign.equals("0") ) { if( biDes.compareTo(dwordpos) == 1 ) { result += "7FFF"; } else { if( i == 24 ) { result += source.substring(i + 4); } else { result += source.substring(i + 4, i + 8); } } } else if( sign.equals("1") ) { Long signedInt = calculator.convertToSignedInteger(biDes, 16); if( signedInt < dwordneg ) { result += "8000"; } else { if( i == 24 ) { result += source.substring(i + 4); } else { result += source.substring(i + 4, i + 8); } } } } for(int i = 0; i <= 24; i+=8) { if( i == 24 ) { biDes = new BigInteger(destination.substring(i), 16); } else { biDes = new BigInteger(destination.substring(i, i + 8), 16); } String temp = calculator.hexToBinaryString(biDes.toString(16), token); String sign = temp.charAt(0) + ""; if( sign.equals("0") ) { if( biDes.compareTo(dwordpos) == 1 ) { result += "7FFF"; } else { if( i == 24 ) { result += destination.substring(i + 4); } else { result += destination.substring(i + 4, i + 8); } } } else if( sign.equals("1") ) { Long signedInt = calculator.convertToSignedInteger(biDes, 16); if( signedInt < dwordneg ) { result += "8000"; } else { if( i == 24 ) { result += destination.substring(i + 4); } else { result += destination.substring(i + 4, i + 8); } } } } } registers.set(des, result); } boolean checkSizeOfRegister(registers, desSize) { boolean checkSize = false; if( 128 == desSize || 64 == desSize ) { checkSize = true; } return checkSize; }
package com.dev.nathan.socialblock; import java.util.Date; public class BlogPost extends BlogPostId { public String user_id, image_url, desc, image_thumb; public Date dhUpload; public BlogPost() {} public BlogPost(String user_id, String image_url, String desc, String image_thumb, Date dhUpload) { this.user_id = user_id; this.image_url = image_url; this.desc = desc; this.image_thumb = image_thumb; this.dhUpload= dhUpload; } public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getImage_url() { return image_url; } public void setImage_url(String image_url) { this.image_url = image_url; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getImage_thumb() { return image_thumb; } public void setImage_thumb(String image_thumb) { this.image_thumb = image_thumb; } public Date getDhUpload() { return dhUpload; } public void setDhUpload(Date dhUpload) { this.dhUpload = dhUpload; } }
package com.wentongwang.mysports.base; import android.content.Context; /** * Created by Wentong WANG on 2016/8/18. */ public interface BaseView { void showProgressBar(); void hideProgressBar(); }
package com.sky.grpc.spring.event; import org.springframework.context.ApplicationContext; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.ContextRefreshedEvent; /** * DESCRIPTION: * <P> * </p> * * @author WangMin * @since 2019/12/12 8:50 下午 */ public class ClosedEvent extends ContextClosedEvent { /** * Create a new ContextRefreshedEvent. * * @param source the {@code ApplicationContext} that has been initialized * or refreshed (must not be {@code null}) */ public ClosedEvent(ApplicationContext source) { super(source); } }
package com.example.gayashan.limbcare; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import static java.sql.Types.BLOB; public class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "limbCare11"; public static final String TABLE_NAME = "employee"; public static final String EMP_ID = "emp_id"; public static final String EMP_FNAME = "emp_fname"; public static final String EMP_LNAME = "emp_lname"; public static final String EMP_NIC = "emp_nic"; public static final String EMP_JOB = "emp_job"; public static final String EMP_EMAIL = "emp_email"; public static final String EMP_BDAY = "emp_birthday"; public static final String EMP_PHOTO = "emp_photo"; public static final String NOTICE = "notice"; public static final String NOTICE_ID = "notice_id"; public static final String TOPIC = "topic"; public static final String VENUE = "venue"; public static final String DATE = "date"; public static final String TIME = "time"; public static final String DESCRIPTION = "description"; public static final String NOTICE_PHOTO = "notice_photo"; public static final String GALLERY = "GALLERY"; public static final String GALLERY_ID = "id"; public static final String GALLERY_TOPIC = "topic"; public static final String GALLERY_DESCRIPTION = "description"; public static final String GALLERY_PHOTO = "photo"; public static final String SERVICE = "service"; public static final String SERVICE_ID = "id"; public static final String SERVICE_TOPIC = "topic"; public static final String SERVICE_TYPE = "type"; public static final String SERVICE_DESCRIPTION = "description"; public static final String SERVICE_PRICE = "price"; public static final String SERVICE_PHOTO = "photo"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 12); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(" create table "+TABLE_NAME+" (" + EMP_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + EMP_FNAME + " TEXT, " + EMP_LNAME + " TEXT, " + EMP_NIC + " TEXT, " + EMP_JOB + " TEXT, " + EMP_EMAIL + " TEXT, " + EMP_BDAY + " DATE, " + EMP_PHOTO + " BLOB)"); db.execSQL(" create table "+NOTICE+" (" + NOTICE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + TOPIC + " TEXT, " + VENUE + " TEXT, " + DATE + " TEXT, " + TIME + " TEXT, " + DESCRIPTION + " TEXT, " + NOTICE_PHOTO + " BLOB)"); db.execSQL(" create table "+GALLERY+" (" + GALLERY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + GALLERY_TOPIC + " TEXT, " + GALLERY_DESCRIPTION + " TEXT, " + GALLERY_PHOTO + " BLOB)"); db.execSQL(" create table "+SERVICE+" (" + SERVICE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + SERVICE_TOPIC + " TEXT, " + SERVICE_TYPE + " TEXT, " + SERVICE_DESCRIPTION + " TEXT, " + SERVICE_PRICE + " TEXT, " + SERVICE_PHOTO + " BLOB)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public Cursor getData(String sql){ SQLiteDatabase database = getReadableDatabase(); return database.rawQuery(sql, null); } }
/* * 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 math; /** * Lets classes to performs a simple computation * @author fabio */ public interface Computable { /** * Performs a generic computation between two operands and one operator * @param op1 * @param op2 * @param operator * @return the result of this computation */ public String computation(String op1, String op2, String operator); }
package com.szcinda.express; import com.szcinda.express.dto.CreateCarrierDto; import com.szcinda.express.dto.CreateClientDto; import com.szcinda.express.dto.ModifyCarrierDto; import com.szcinda.express.dto.ModifyClientDto; import com.szcinda.express.persistence.Carrier; import com.szcinda.express.persistence.Client; import java.util.List; public interface CarrierService { List<Carrier> getAll(); void create(CreateCarrierDto clientDto); void modify(ModifyCarrierDto clientDto); Carrier getById(String id); void delete(String id); }
package day28_arrays_Lab; public class Question17 { public static void main(String[] args) { int[] x = {10,2,5,89}; System.out.println(difference(x)); } public static int difference(int[] x) { int biggest=0; int smallest=x[0]; for(int i=0; i<x.length; i++) { if(biggest<x[i]) { biggest=x[i]; } if(smallest>=x[i]) { smallest=x[i]; } } return biggest-smallest; } }
package com.zznode.opentnms.isearch.routeAlgorithm.api.model; import java.util.List; public class CaculatorResult { private String resultCode ; private String resultMessage ; private Long timecost ; private List<CaculatorResultWay> ways ; public String getResultCode() { return resultCode; } public void setResultCode(String resultCode) { this.resultCode = resultCode; } public String getResultMessage() { return resultMessage; } public void setResultMessage(String resultMessage) { this.resultMessage = resultMessage; } public Long getTimecost() { return timecost; } public void setTimecost(Long timecost) { this.timecost = timecost; } public List<CaculatorResultWay> getWays() { return ways; } public void setWays(List<CaculatorResultWay> ways) { this.ways = ways; } @Override public String toString() { return "CaculatorResult [resultCode=" + resultCode + ", resultMessage=" + resultMessage + ", timecost=" + timecost + ", ways=" + ways + "]"; } }
package com.sound.bytes.asynchdownloader; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; /** * Created by goodbytes on 6/11/2016. */ public class JsonDownloader extends AsyncTask<String, Void, String> { JsonDataHandler handler; //ProgressDialog pdLoading; public String data; Context appCtxt; public JsonDownloader(JsonDataHandler handlerFromMainActivity, Context mainAppCtxt){ handler = handlerFromMainActivity; appCtxt = mainAppCtxt; //pdLoading = new ProgressDialog(appCtxt); } @Override protected void onPreExecute() { super.onPreExecute(); //this method will be running on UI thread //pdLoading.setMessage("\tLoading..."); //pdLoading.show(); } @Override protected String doInBackground(String... params) { try { data = downloadUrl(params[0]); } catch (IOException e) { System.out.println("doInBackGround exception :"+e.getMessage()); } return data; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); //pdLoading.dismiss(); handler.onJsonDownloadCompleted(result,appCtxt); } // Reads an InputStream and converts it to a String. public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException { Reader reader = null; reader = new InputStreamReader(stream, "UTF-8"); char[] buffer = new char[len]; reader.read(buffer); return new String(buffer); }//readIt // Given a URL, establishes an HttpUrlConnection and retrieves // the web page content as a InputStream, which it returns as // a string. private String downloadUrl(String myurl) throws IOException { InputStream is = null; // Only display the first 500 characters of the retrieved // web page content. int len = 5000; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect();//culprit int response = conn.getResponseCode(); is = conn.getInputStream(); // Convert the InputStream into a string String contentAsString = readIt(is, len); return contentAsString; // Makes sure that the InputStream is closed after the app is // finished using it. } finally { if (is != null) { is.close(); } } }//downloadUrl /*making LoadImage class*/ }/* class made */
package ru.mail.chatserver.shared.util; import org.json.JSONException; import org.json.JSONObject; import ru.mail.chatserver.shared.BufferDecoder; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; /** * User: magic2k * Date: 22.09.12 */ public class InboundMessageReceiver { private int inboundMessageLength = 0; private ByteBuffer inMessageByteBuffer; private CharBuffer inCharBuffer; private BufferDecoder bufferDecoder; public InboundMessageReceiver() { bufferDecoder = new BufferDecoder(); inMessageByteBuffer = ByteBuffer.allocate(2048); } public JSONObject checkInboundBuffer(ByteBuffer inByteBuffer) throws JSONException { if (inboundMessageLength == 0) { if (inByteBuffer.position() < 4) { return null; } else { inboundMessageLength = getInboundMessageSize(inByteBuffer); processInBuffer(inByteBuffer); return convertToJson(); } } else { processInBuffer(inByteBuffer); return convertToJson(); } } private void processInBuffer(ByteBuffer inByteBuffer) throws JSONException { if (inboundMessageLength > inByteBuffer.position()) { return; } else { inMessageByteBuffer.put(inByteBuffer.array(), 0, inboundMessageLength); decodeReceivedMessage(inMessageByteBuffer); inByteBuffer.flip(); inByteBuffer.position(inboundMessageLength); inByteBuffer.compact(); inMessageByteBuffer.clear(); inboundMessageLength = 0; } } private int getInboundMessageSize(ByteBuffer inByteBuffer) { inByteBuffer.flip(); int messageSize = inByteBuffer.getInt(); inByteBuffer.compact(); return messageSize; } private void decodeReceivedMessage(ByteBuffer inboundMessageByteBuffer) { try { inboundMessageByteBuffer.flip(); inCharBuffer = bufferDecoder.byteBufferToCharBuffer(inboundMessageByteBuffer); // System.out.println("msg: " + new String(inCharBuffer.toString()) ); } catch (CharacterCodingException e) { throw new IllegalStateException(e); } } private JSONObject convertToJson() throws JSONException { if (inCharBuffer == null) { return null; } JSONObject jsonReceivedMsg = new JSONObject(inCharBuffer.toString()); inCharBuffer.clear(); return jsonReceivedMsg; } }
//This file is part of JPACS. // // JPACS is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // JPACS 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 JPACS. If not, see <http://www.gnu.org/licenses/>. package br.pucminas.dcc.jpacs.gui; import br.pucminas.dcc.jpacs.Internacionalizacao; import br.pucminas.dcc.jpacs.core.ItemRelatorio; import javax.swing.table.DefaultTableModel; import java.util.Vector; /** * Modelo de tabela padrão, onde as células não são editáveis */ class ModeloTabela extends DefaultTableModel { public ModeloTabela(Object[][] data, Object[] columnNames) { super(data,columnNames); } public ModeloTabela(Vector data, Vector columnNames) { super(data,columnNames); } @Override public boolean isCellEditable(int row, int column){ //redefinição do metodo para que a tabela não possa ser editada return false; } @Override public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } }; /** * Modelo de tabela para relatório */ class ModeloTabelaRelatorio extends DefaultTableModel { public ModeloTabelaRelatorio(Vector Acessos) { super(); Object[][] Dados=new Object[Acessos.size()][7]; int i, j; for(i=0; i<Acessos.size(); i++) Dados[i]=((ItemRelatorio)Acessos.get(i)).toArray(); String Titulo[]={Internacionalizacao.get("Report.Number"), Internacionalizacao.get("Report.Position"), Internacionalizacao.get("Report.Nature"), Internacionalizacao.get("Report.Block"), Internacionalizacao.get("Report.Time"), Internacionalizacao.get("Report.Result"), Internacionalizacao.get("Report.Substitution")}; super.setDataVector(Dados,Titulo); } @Override public boolean isCellEditable(int row, int column) { return false; } @Override public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } }; /** * Modelo de tabela para a memória cache */ class ModeloTabelaCache extends DefaultTableModel { public ModeloTabelaCache(Object[][] data, Object[] columnNames) { super(data,columnNames); } @Override public boolean isCellEditable(int row, int column) { return false; } @Override public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } };
package net.minecraft.block.state; import java.util.List; import javax.annotation.Nullable; import net.minecraft.block.material.EnumPushReaction; import net.minecraft.block.material.MapColor; import net.minecraft.block.material.Material; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.EnumBlockRenderType; import net.minecraft.util.EnumFacing; import net.minecraft.util.Mirror; import net.minecraft.util.Rotation; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.RayTraceResult; import net.minecraft.util.math.Vec3d; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; public interface IBlockProperties { Material getMaterial(); boolean isFullBlock(); boolean canEntitySpawn(Entity paramEntity); int getLightOpacity(); int getLightValue(); boolean isTranslucent(); boolean useNeighborBrightness(); MapColor getMapColor(IBlockAccess paramIBlockAccess, BlockPos paramBlockPos); IBlockState withRotation(Rotation paramRotation); IBlockState withMirror(Mirror paramMirror); boolean isFullCube(); boolean func_191057_i(); EnumBlockRenderType getRenderType(); int getPackedLightmapCoords(IBlockAccess paramIBlockAccess, BlockPos paramBlockPos); float getAmbientOcclusionLightValue(); boolean isBlockNormalCube(); boolean isNormalCube(); boolean canProvidePower(); int getWeakPower(IBlockAccess paramIBlockAccess, BlockPos paramBlockPos, EnumFacing paramEnumFacing); boolean hasComparatorInputOverride(); int getComparatorInputOverride(World paramWorld, BlockPos paramBlockPos); float getBlockHardness(World paramWorld, BlockPos paramBlockPos); float getPlayerRelativeBlockHardness(EntityPlayer paramEntityPlayer, World paramWorld, BlockPos paramBlockPos); int getStrongPower(IBlockAccess paramIBlockAccess, BlockPos paramBlockPos, EnumFacing paramEnumFacing); EnumPushReaction getMobilityFlag(); IBlockState getActualState(IBlockAccess paramIBlockAccess, BlockPos paramBlockPos); AxisAlignedBB getSelectedBoundingBox(World paramWorld, BlockPos paramBlockPos); boolean shouldSideBeRendered(IBlockAccess paramIBlockAccess, BlockPos paramBlockPos, EnumFacing paramEnumFacing); boolean isOpaqueCube(); @Nullable AxisAlignedBB getCollisionBoundingBox(IBlockAccess paramIBlockAccess, BlockPos paramBlockPos); void addCollisionBoxToList(World paramWorld, BlockPos paramBlockPos, AxisAlignedBB paramAxisAlignedBB, List<AxisAlignedBB> paramList, Entity paramEntity, boolean paramBoolean); AxisAlignedBB getBoundingBox(IBlockAccess paramIBlockAccess, BlockPos paramBlockPos); RayTraceResult collisionRayTrace(World paramWorld, BlockPos paramBlockPos, Vec3d paramVec3d1, Vec3d paramVec3d2); boolean isFullyOpaque(); Vec3d func_191059_e(IBlockAccess paramIBlockAccess, BlockPos paramBlockPos); boolean func_191058_s(); BlockFaceShape func_193401_d(IBlockAccess paramIBlockAccess, BlockPos paramBlockPos, EnumFacing paramEnumFacing); } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\block\state\IBlockProperties.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.axess.smartbankapi.config.restapi; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler; import com.axess.smartbankapi.exception.ApplicationException; import com.axess.smartbankapi.exception.RecordExistException; import com.axess.smartbankapi.exception.RecordNotCreatedException; import com.axess.smartbankapi.exception.RecordNotDeletedException; import com.axess.smartbankapi.exception.RecordNotFoundException; import com.axess.smartbankapi.exception.RecordNotUpdatedException; @RestControllerAdvice public class GlobalApiExceptionHandler extends ResponseEntityExceptionHandler { private Logger logger = LoggerFactory.getLogger(GlobalApiExceptionHandler.class); private ResponseEntity<Object> buildResponseEntity(ApiErrorResponse response, HttpStatus httpStatus) { return new ResponseEntity<>(response, httpStatus); } @Override @ResponseStatus(value = HttpStatus.BAD_REQUEST) protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { System.out.println("commmmme"); ApiErrorResponse response = new ApiErrorResponse(); BindingResult binding = ex.getBindingResult(); FieldError error = binding.getFieldError(); String message = error.getDefaultMessage(); response.setCause(ex.getLocalizedMessage()); response.setMessage(message); response.setHttpStatus(HttpStatus.BAD_REQUEST); response.setHttpStatusCode(400); response.setError(true); return buildResponseEntity(response, HttpStatus.BAD_REQUEST); } @ExceptionHandler(MethodArgumentTypeMismatchException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody protected ResponseEntity<Object> handleMethodArgumentTypeMismatchExceptions( final MethodArgumentTypeMismatchException ex, WebRequest request) { System.out.println("type mismatch"); ApiErrorResponse response = new ApiErrorResponse(); String message = ex.getName() + " should be of type " + ex.getRequiredType().getName(); response.setCause(ex.getLocalizedMessage()); response.setMessage(message); response.setHttpStatus(HttpStatus.BAD_REQUEST); response.setHttpStatusCode(400); response.setError(true); return buildResponseEntity(response, HttpStatus.BAD_REQUEST); } @ExceptionHandler(IllegalStateException.class) @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody protected ResponseEntity<Object> handleIllegalStateException(final MethodArgumentTypeMismatchException ex, WebRequest request) { System.out.println("type mismatch"); ApiErrorResponse response = new ApiErrorResponse(); String message = ex.getName() + " should be of type " + ex.getRequiredType().getName(); response.setCause(ex.getLocalizedMessage()); response.setMessage(message); response.setHttpStatus(HttpStatus.BAD_REQUEST); response.setHttpStatusCode(400); response.setError(true); return buildResponseEntity(response, HttpStatus.BAD_REQUEST); } @Override @ResponseStatus(value = HttpStatus.BAD_REQUEST) @ResponseBody protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) { ApiErrorResponse response = new ApiErrorResponse(); String message = ex.getParameterName() + " should be of type " + ex.getParameterType(); response.setCause(ex.getLocalizedMessage()); response.setMessage(message); response.setHttpStatus(HttpStatus.BAD_REQUEST); response.setHttpStatusCode(400); response.setError(true); return buildResponseEntity(response, HttpStatus.BAD_REQUEST); } @ExceptionHandler(Exception.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) { ApiErrorResponse response = new ApiErrorResponse(); response.setCause(ex.getLocalizedMessage()); response.setMessage(ex.getMessage()); logger.error("exception occured - "); ex.printStackTrace(); response.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR); response.setHttpStatusCode(500); response.setError(true); return buildResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(ApplicationException.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public final ResponseEntity<Object> handleApplicationExceptions(ApplicationException ex, WebRequest request) { ApiErrorResponse response = new ApiErrorResponse(); logger.error("exception occured in Handleapplicationexception - "); ex.printStackTrace(); response.setCause(ex.getLocalizedMessage()); response.setMessage(ex.getMessage()); response.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR); response.setHttpStatusCode(500); response.setError(true); return buildResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(RecordNotFoundException.class) @ResponseStatus(value = HttpStatus.NOT_FOUND) public final ResponseEntity<Object> handleRecordNotFoundExceptions(RecordNotFoundException ex, WebRequest request) { ApiErrorResponse response = new ApiErrorResponse(); if (ex.getCause() != null) { response.setCause(ex.getCause().getMessage()); } else { response.setCause(ex.getLocalizedMessage()); } response.setMessage("Something went wrong !!. Record not found."); response.setExceptionMessage(ex.getMessage()); response.setHttpStatus(HttpStatus.NOT_FOUND); response.setHttpStatusCode(404); response.setError(true); return buildResponseEntity(response, HttpStatus.NOT_FOUND); } @ExceptionHandler(RecordNotCreatedException.class) @ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY) public final ResponseEntity<Object> handleRecordNotCreatedExceptions(RecordNotCreatedException ex, WebRequest request) { ApiErrorResponse response = new ApiErrorResponse(); if (ex.getCause() != null) { response.setCause(ex.getCause().getMessage()); } else { response.setCause(ex.getLocalizedMessage()); } response.setMessage("Something went wrong !!. Record not created"); response.setExceptionMessage(ex.getMessage()); response.setHttpStatus(HttpStatus.UNPROCESSABLE_ENTITY); response.setHttpStatusCode(422); response.setError(true); return buildResponseEntity(response, HttpStatus.UNPROCESSABLE_ENTITY); } @ExceptionHandler(RecordNotDeletedException.class) @ResponseStatus(value = HttpStatus.CONFLICT) public final ResponseEntity<Object> handleRecordNotDeletedExceptions(RecordNotDeletedException ex, WebRequest request) { ApiErrorResponse response = new ApiErrorResponse(); if (ex.getCause() != null) { response.setCause(ex.getCause().getMessage()); } else { response.setCause(ex.getLocalizedMessage()); } response.setMessage("Something went wrong !!. Record was not deleted."); response.setExceptionMessage(ex.getMessage()); response.setHttpStatus(HttpStatus.CONFLICT); response.setHttpStatusCode(409); response.setError(true); return buildResponseEntity(response, HttpStatus.CONFLICT); } @ExceptionHandler(RecordNotUpdatedException.class) @ResponseStatus(value = HttpStatus.CONFLICT) public final ResponseEntity<Object> handleRecordNotUpdatedExceptions(RecordNotUpdatedException ex, WebRequest request) { ApiErrorResponse response = new ApiErrorResponse(); if (ex.getCause() != null) { response.setCause(ex.getCause().getMessage()); } else { response.setCause(ex.getLocalizedMessage()); } response.setMessage("Something went wrong !!. Record did not got update."); response.setExceptionMessage(ex.getMessage()); response.setHttpStatus(HttpStatus.CONFLICT); response.setHttpStatusCode(409); response.setError(true); return buildResponseEntity(response, HttpStatus.CONFLICT); } @ExceptionHandler(RecordExistException.class) @ResponseStatus(value = HttpStatus.CONFLICT) public final ResponseEntity<Object> handleRecordExistsExceptions(RecordExistException ex, WebRequest request) { ApiErrorResponse response = new ApiErrorResponse(); if (ex.getCause() != null) { response.setCause(ex.getCause().getMessage()); } else { response.setCause(ex.getLocalizedMessage()); } response.setMessage("Something went wrong !!. Record exists already."); response.setExceptionMessage(ex.getMessage()); response.setHttpStatus(HttpStatus.CONFLICT); response.setHttpStatusCode(409); response.setError(true); return buildResponseEntity(response, HttpStatus.CONFLICT); } @ExceptionHandler(IOException.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public final ResponseEntity<Object> handleIOException(IOException ex, WebRequest request) { ApiErrorResponse response = new ApiErrorResponse(); if (ex.getCause() != null) { response.setCause(ex.getCause().getMessage()); } else { response.setCause(ex.getLocalizedMessage()); } response.setMessage("IOException - Something went wrong"); response.setExceptionMessage(ex.getMessage()); response.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR); response.setHttpStatusCode(500); response.setError(true); return buildResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(IllegalArgumentException.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public final ResponseEntity<Object> handleIllegalArgumentException(IllegalArgumentException ex, WebRequest request) { ApiErrorResponse response = new ApiErrorResponse(); if (ex.getCause() != null) { response.setCause(ex.getCause().getMessage()); } else { response.setCause(ex.getLocalizedMessage()); } response.setMessage("IllegalArgumentException - Something went wrong"); response.setExceptionMessage(ex.getMessage()); response.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR); response.setHttpStatusCode(500); response.setError(true); return buildResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(NullPointerException.class) @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) public final ResponseEntity<Object> handleNullPointerException(NullPointerException ex, WebRequest request) { ApiErrorResponse response = new ApiErrorResponse(); if (ex.getCause() != null) { response.setCause(ex.getCause().getMessage()); } else { response.setCause(ex.getLocalizedMessage()); } logger.error("exception occured - Nullpointer- "); ex.printStackTrace(); response.setMessage("Something went wrong. Object is empty or null."); response.setExceptionMessage(ex.getMessage()); response.setHttpStatus(HttpStatus.INTERNAL_SERVER_ERROR); response.setHttpStatusCode(500); response.setError(true); return buildResponseEntity(response, HttpStatus.INTERNAL_SERVER_ERROR); } }
package org.sagebionetworks.table.query.model; /** * This matches &ltset function specification&gt in: <a href="https://github.com/ronsavage/SQL/blob/master/sql-92.bnf">SQL-92</a> */ public class SetFunctionSpecification extends SQLElement implements HasAggregate, HasFunctionReturnType { Boolean countAsterisk; SetFunctionType setFunctionType; SetQuantifier setQuantifier; ValueExpression valueExpression; OrderByClause orderByClause; Separator separator; public SetFunctionSpecification(Boolean countAsterisk) { this.countAsterisk = countAsterisk; this.setFunctionType = SetFunctionType.COUNT; } public SetFunctionSpecification(SetFunctionType setFunctionType, SetQuantifier setQuantifier, ValueExpression valueExpression, OrderByClause orderByClause, Separator separator) { this.setFunctionType = setFunctionType; this.setQuantifier = setQuantifier; this.valueExpression = valueExpression; this.orderByClause = orderByClause; this.separator = separator; } public Boolean getCountAsterisk() { return countAsterisk; } public SetFunctionType getSetFunctionType() { return setFunctionType; } public SetQuantifier getSetQuantifier() { return setQuantifier; } public ValueExpression getValueExpression() { return valueExpression; } public OrderByClause getOrderByClause() { return orderByClause; } public Separator getSeparator() { return separator; } @Override public void toSql(StringBuilder builder, ToSqlParameters parameters) { if (countAsterisk != null) { builder.append("COUNT(*)"); } else { builder.append(setFunctionType.name()); builder.append("("); if (setQuantifier != null) { builder.append(setQuantifier.name()); builder.append(" "); } valueExpression.toSql(builder, parameters); if(orderByClause != null) { builder.append(" "); orderByClause.toSql(builder, parameters); } if(separator != null) { builder.append(" "); separator.toSql(builder, parameters); } builder.append(")"); } } @Override public Iterable<Element> getChildren() { return SQLElement.buildChildren(valueExpression, orderByClause, separator); } @Override public boolean isElementAggregate() { return true; } @Override public FunctionReturnType getFunctionReturnType() { return this.setFunctionType.getFunctionReturnType(); } }
package com.kgitbank.spring.domain.model.mapper; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import com.kgitbank.spring.domain.follow.mapper.FollowMapper; import com.kgitbank.spring.domain.model.FollowVO; import lombok.extern.log4j.Log4j; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration({ "file:src/main/webapp/WEB-INF/spring/root-context.xml", "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml" }) @Log4j public class FollowMapperTests { @Autowired FollowMapper mapper; @Test public void createDemoData() { int followId = 107; FollowVO vo = new FollowVO(); for (int i = 2; i < 32; i++) { vo.setFollowerId(i); vo.setFollowId(followId); mapper.following(vo); } log.info("Finish"); } }
package com.simplite.orm.interfaces; import java.util.List; public interface BackgroundTaskCallBack { void onSuccess(String result, List<Object> data); void onError(String error); }
package edu.hust.se.seckill.controller; import edu.hust.se.seckill.domain.MiaoshaUser; import edu.hust.se.seckill.redis.GoodsKey; import edu.hust.se.seckill.redis.RedisService; import edu.hust.se.seckill.result.Result; import edu.hust.se.seckill.service.GoodsService; import edu.hust.se.seckill.service.MiaoshaUserService; import edu.hust.se.seckill.service.MiaoshaUserServiceImpl; import edu.hust.se.seckill.vo.GoodsDetailVo; import edu.hust.se.seckill.vo.GoodsVo; import edu.hust.se.seckill.vo.LoginVo; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.thymeleaf.context.WebContext; import org.thymeleaf.spring5.view.ThymeleafViewResolver; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; @Controller @RequestMapping("goods") public class GoodsController { private static Logger logger = LoggerFactory.getLogger(GoodsController.class); @Autowired private MiaoshaUserService userService; @Autowired private GoodsService goodsService; @Autowired private RedisService redisService; @Autowired ThymeleafViewResolver thymeleafViewResolver; @RequestMapping(value = "/to_list", produces="text/html") @ResponseBody public String toList(HttpServletRequest request, HttpServletResponse response, Model model, MiaoshaUser user){ // if(StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken)) { // return "login"; // } // // String token = StringUtils.isEmpty(paramToken)?cookieToken:paramToken; // MiaoshaUser user = userService.getUserByToken(response,token); model.addAttribute("user", user); String html = redisService.get(GoodsKey.getGoodsList, "", String.class); if(!StringUtils.isEmpty(html)) { return html; } logger.info(user.toString()); List<GoodsVo> goodsVos = goodsService.listGoodsVo(); model.addAttribute("goodsList",goodsVos); // return "goods_list"; WebContext ctx = new WebContext (request,response, request.getServletContext(),request.getLocale(), model.asMap()); //手动渲染 html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx); if(!StringUtils.isEmpty(html)) { redisService.set(GoodsKey.getGoodsList, "", html); } return html; } @RequestMapping("/detail/{goodsId}") @ResponseBody public Result<GoodsDetailVo> toDetail(MiaoshaUser user, @PathVariable("goodsId") long goodsId){ GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId); long startAt = goods.getStartDate().getTime(); long endAt = goods.getEndDate().getTime(); long now = System.currentTimeMillis(); int miaoshaStatus = 0; int remainSeconds = 0; if(now < startAt ) {//秒杀还没开始,倒计时 miaoshaStatus = 0; remainSeconds = (int)((startAt - now )/1000); }else if(now > endAt){//秒杀已经结束 miaoshaStatus = 2; remainSeconds = -1; }else {//秒杀进行中 miaoshaStatus = 1; remainSeconds = 0; } GoodsDetailVo vo = new GoodsDetailVo(); vo.setGoods(goods); vo.setUser(user); vo.setMiaoshaStatus(miaoshaStatus); vo.setRemainSeconds(remainSeconds); return Result.success(vo); } }
package org.fuserleer.ledger.atoms; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.Objects; import java.util.TreeMap; import java.util.function.Consumer; import java.util.function.Function; import org.apache.commons.io.IOUtils; import org.fuserleer.crypto.Hash; import org.fuserleer.exceptions.ValidationException; import org.fuserleer.ledger.StateKey; import org.fuserleer.ledger.StateMachine; import org.fuserleer.ledger.StateOp; import org.fuserleer.serialization.DsonOutput; import org.fuserleer.serialization.Serialization; import org.fuserleer.serialization.SerializerId2; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.Value; import org.json.JSONObject; import org.fuserleer.serialization.DsonOutput.Output; import org.fuserleer.serialization.mapper.JacksonCodecConstants; import org.fuserleer.utils.Bytes; import org.fuserleer.utils.Numbers; import org.fuserleer.utils.UInt256; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; @SerializerId2("ledger.particle.polyglot") public final class PolyglotParticle extends AutomataParticle { public final static int MAX_CODE_SIZE = 65535; public static final PolyglotParticle from(Language language, InputStream stream, Map<String, Object> fields) throws IOException { String code = IOUtils.toString(stream, StandardCharsets.UTF_8.name()); return new PolyglotParticle(language, code, fields); } public static enum Language { JAVASCRIPT, PYTHON; @JsonValue @Override public String toString() { return this.name(); } } private Map<String, Object> fields; private transient Context context; private transient String code; private transient Language language; private transient Value eval; private transient Value instance; private PolyglotParticle() { super(); this.fields = new TreeMap<>(); } private PolyglotParticle(final Language language, final String code, final Map<String, Object> fields) { this(); this.context = Context.newBuilder("js").allowAllAccess(true).build(); if (fields != null) this.fields.putAll(fields); this.language = Objects.requireNonNull(language, "Language is null"); Objects.requireNonNull(code, "Code is null"); Numbers.greaterThan(code.length(), PolyglotParticle.MAX_CODE_SIZE, "Code size "+code.length()+" is greater than max "+PolyglotParticle.MAX_CODE_SIZE); this.code = code; } @JsonProperty("fields") @DsonOutput(Output.ALL) private byte[] getJsonFields() { JSONObject fieldsJSON = Serialization.getInstance().toJsonObject(this.fields, Output.WIRE); byte[] bytes = fieldsJSON.toString().getBytes(StandardCharsets.UTF_8); return bytes; } @JsonProperty("fields") private void setJsonFields(byte[] fields) { // TODO Serializer limitations hack. Loses type info on Object maps. Easier to patch with JSON than binary JSONObject fieldsJSON = new JSONObject(new String(fields, StandardCharsets.UTF_8)); for (String key : fieldsJSON.keySet()) { Object value = fieldsJSON.get(key); if (value instanceof JSONObject) { String typed = ((JSONObject)value).getString("typed"); Class<?> clazz = Serialization.getInstance().getClassForId(typed); this.fields.put(key, Serialization.getInstance().fromJsonObject((JSONObject)value, clazz)); } else if (value instanceof String) { if (((String)value).startsWith(JacksonCodecConstants.BYTE_STR_VALUE) == true) this.fields.put(key, Bytes.fromBase64String(((String)value).substring(JacksonCodecConstants.STR_VALUE_LEN))); else if (((String)value).startsWith(JacksonCodecConstants.HASH_STR_VALUE) == true) this.fields.put(key, new Hash(((String)value).substring(JacksonCodecConstants.STR_VALUE_LEN))); else if (((String)value).startsWith(JacksonCodecConstants.U256_STR_VALUE) == true) this.fields.put(key, UInt256.from(((String)value).substring(JacksonCodecConstants.STR_VALUE_LEN))); else this.fields.put(key, value); } else this.fields.put(key, value); } } public <T> T get(final String field) { return (T) this.fields.get(field); } public Language getLanguage() { return this.language; } @Override public boolean isConsumable() { return false; } @Override public void prepare(StateMachine stateMachine) throws ValidationException, IOException { } @Override public void execute(StateMachine stateMachine) throws ValidationException, IOException { } @Override public void prepare(final StateMachine stateMachine, String method, final Object ... arguments) throws ValidationException, IOException { Objects.requireNonNull(stateMachine, "State machine is null"); this.context.enter(); try { if (this.eval == null) { // Bridges to state machine Function<Object, Object> get = (t) -> { if (t instanceof String) return get((String)t); throw new IllegalArgumentException("Key is not of type String"); }; Function<Object, Object> input = (t) -> { if (t instanceof StateKey) return stateMachine.getInput((StateKey<?, ?>)t); throw new IllegalArgumentException("Key is not of type StateAddress"); }; Function<Object, Object> output = (t) -> { if (t instanceof StateKey) return stateMachine.getOutput((StateKey<?, ?>)t); throw new IllegalArgumentException("Key is not of type StateAddress"); }; Consumer<StateOp> sop = (s) -> { stateMachine.sop(s, PolyglotParticle.this); }; Consumer<Hash> associate = (t) -> { stateMachine.associate(Hash.from(t), PolyglotParticle.this); }; this.context.getBindings("js").putMember("get", get); this.context.getBindings("js").putMember("input", input); this.context.getBindings("js").putMember("output", output); this.context.getBindings("js").putMember("sop", sop); this.context.getBindings("js").putMember("associate", associate); this.eval = this.context.eval("js", code); this.instance = this.eval.execute().newInstance(); } this.instance.invokeMember("prepare", arguments); } finally { this.context.leave(); } } @Override public void execute(final StateMachine stateMachine, String method, final Object ... arguments) throws ValidationException, IOException { this.context.enter(); try { this.instance.invokeMember("execute", arguments); } finally { this.context.leave(); } } }
package org.tools.dbunit.rules; import org.junit.AssumptionViolatedException; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * ProgressWatcher * */ public class ProgressWatcher extends TestWatcher { private static final Logger logger = LoggerFactory.getLogger(ProgressWatcher.class); @Override protected void succeeded(Description description) { logger.info("[{}]のテストが成功しました.", description.getMethodName()); } @Override protected void failed(Throwable e, Description description) { logger.info("[{}]のテストが失敗しました", description.getMethodName()); } @Override protected void skipped(AssumptionViolatedException e, Description description) { logger.info("[{}]をスキップします.", description.getMethodName()); } @Override protected void starting(Description description) { logger.info("[{}]のテストを開始します.", description.getMethodName()); } @Override protected void finished(Description description) { logger.info("[{}]のテストを終了します", description.getMethodName()); } }
package com.example.runnable; import com.example.entity.Account; import com.example.service.AccountService; import com.example.service.TransactionService; import lombok.extern.slf4j.Slf4j; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @Slf4j public class TransactingRunnable implements Runnable { private static final int TOTAL_COUNT_OF_ACCOUNTS = AccountService.getTotalCountOfAccounts(); private static final int TOTAL_COUNT_OF_TRANSACTIONS = 1_000; private static final AtomicInteger currentCountOfTransactions = new AtomicInteger(0); private final Random random = new Random(); private final TransactionService transactionService = new TransactionService(); private final Logger logger = LoggerFactory.getLogger("file-logger"); private final AccountService accountService; public TransactingRunnable(AccountService accountService) { this.accountService = accountService; } @Override public void run() { long fromId; long toId; long amount; Account fromAccount; Account toAccount; Account firstLock; Account secondLock; while (currentCountOfTransactions.getAndAdd(1) < TOTAL_COUNT_OF_TRANSACTIONS) { do { fromId = this.random.nextInt(TOTAL_COUNT_OF_ACCOUNTS) + 1L; toId = this.random.nextInt(TOTAL_COUNT_OF_ACCOUNTS) + 1L; } while (fromId == toId); fromAccount = this.accountService.getById(fromId); toAccount = this.accountService.getById(toId); if (fromAccount.getId() < toAccount.getId()) { firstLock = fromAccount; secondLock = toAccount; } else { firstLock = toAccount; secondLock = fromAccount; } firstLock.getLock().lock(); secondLock.getLock().lock(); amount = this.random.nextInt(fromAccount.getBalance()); this.transactionService.transact( fromAccount, toAccount, amount ); secondLock.getLock().unlock(); firstLock.getLock().unlock(); } } }
import java.util.*; class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int T = sc.nextInt(); int[][] answer = new int[T][2]; int[] list = new int[10001]; for(int i=2;i<10001;i++){ boolean flag = false; for(int j=2;j<=Math.sqrt(i);j++){ if(i%j==0){ flag = true; break; } } if(!flag){ list[i] = 1; }else{ list[i] =0; } } for(int t =0;t<T;t++){ int N = sc.nextInt(); int min = Integer.MAX_VALUE; for(int i=1;i<N;i++){ if(list[i]==1&&list[N-i]==1){ if(min>Math.abs(i-(N-i))){ answer[t][0]=i; answer[t][1]=N-i; min = Math.abs(i-(N-i)); } } } } for(int i=0;i<T;i++){ System.out.println(answer[i][0]+" "+answer[i][1]); } } }
package com.beiyelin.common.i18n; import java.util.Locale; /** * @ClassName QueryDSLUtils * @Description 语言工具类 * @author Newmann * @Date 2018/01/01. * @version */ public class SessionLocale { private final static ThreadLocal<Locale> tlLocale = new ThreadLocal<Locale>() { protected Locale initialValue() { // 语言的默认值 return Locale.CHINESE; }; }; public static final String KEY_LANG = "lang"; public static void setLocale(String locale) { setLocale(new Locale(locale)); } public static void setLocale(Locale locale) { tlLocale.set(locale); } public static Locale getLocale() { return tlLocale.get(); } public static void clearLocalInfo() { tlLocale.remove(); } }
package com.tencent.mm.plugin.sns.ui; import com.tencent.mm.plugin.sns.model.af; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.ui.r.a; class SnsMsgUI$15 implements a { final /* synthetic */ SnsMsgUI nYl; SnsMsgUI$15(SnsMsgUI snsMsgUI) { this.nYl = snsMsgUI; } public final void Xa() { } public final void Xb() { x.v("MicroMsg.SnsMsgUI", "total count:" + SnsMsgUI.e(this.nYl).edl + " unread:" + af.byt().axd() + " showcount:" + SnsMsgUI.e(this.nYl).hFO); if (SnsMsgUI.e(this.nYl).getCount() == 0) { SnsMsgUI.c(this.nYl).setVisibility(8); SnsMsgUI.d(this.nYl).setVisibility(0); this.nYl.enableOptionMenu(false); } else { SnsMsgUI.c(this.nYl).setVisibility(0); SnsMsgUI.d(this.nYl).setVisibility(8); this.nYl.enableOptionMenu(true); } if ((SnsMsgUI.e(this.nYl).ayQ() && af.byt().axd() == 0) || af.byt().axd() == af.byt().bAQ()) { SnsMsgUI.f(this.nYl).setVisibility(8); } } }
package com.nks.whatsapp; import java.util.List; public interface WhatsAppStorage { public void initStorage() throws StorageException; public void addIdentity(String phoneNumber,String identity) throws StorageException; public void deleteIdentity(String phoneNumber) throws StorageException; public String getIdentity(String phoneNumber) throws StorageException; public void addCredentials(Credentials credentials) throws StorageException; public Credentials getCredentials(Contact contact) throws StorageException; public void deleteCredentials(Contact contact) throws StorageException; public List<Contact> getRegisteredContacts() throws StorageException; public void saveMyContact(Contact myContact)throws StorageException; public void removeMyContact(Contact myContact)throws StorageException; public String getNextMessageId(Contact contact) throws StorageException; public String getNextGroupId(Contact contact) throws StorageException; public List<Member> getContacts(Contact myContact) throws StorageException; public void addMember(Contact myContact,Member member)throws StorageException; public void addContactToGroup(Contact myContact,Group group,Contact another)throws StorageException; public void removeMember(Contact myContact,Member member)throws StorageException; public void removeContactFromGroup(Contact myContact,Group group,Contact another)throws StorageException; public List<Chat> getChats(Contact myContact)throws StorageException; public void addChat(Contact myContact,Chat chat)throws StorageException; public void addMessageToChat(Contact myContact,Chat chat,Message message)throws StorageException; public void removeMessageFromChat(Contact myContact,Chat chat,Message message)throws StorageException; }
package com.hesoyam.pharmacy.util.search; public class QueryMatchResult { private boolean matches; private double grade; public QueryMatchResult(boolean matches, double grade) { this.matches = matches; this.grade = grade; } public QueryMatchResult(boolean matches) { if(!matches){ this.matches = false; this.grade = 0.0; } } public QueryMatchResult() { } public boolean getMatches() { return matches; } public void setMatches(boolean matches) { this.matches = matches; } public double getGrade() { return grade; } public void setGrade(double grade) { this.grade = grade; } }
package com.fun.ms.account; import com.fun.ms.account.controller.AccountController; import com.fun.ms.common.verticle.BaseVerticle; import io.vertx.core.Future; import lombok.extern.slf4j.Slf4j; import org.jboss.resteasy.plugins.server.vertx.VertxResteasyDeployment; @Slf4j public class AccountServer extends BaseVerticle { private static final Integer DEFAULT_PORT = 8090 ; private static String DEFAULT_HOST = "localhost"; private static final String SERVICE_NAME = "account-api"; @Override public void start(Future<Void> future) throws Exception { Future<Void> superFuture = Future.future(); super.start(superFuture); // Build the Jax-RS hello world deployment VertxResteasyDeployment deployment = new VertxResteasyDeployment(); deployment.start(); deployment.getRegistry().addPerInstanceResource(AccountController.class); superFuture.compose(discoverFuture-> createListenerOnPortForRestDeployment(SERVICE_NAME,config().getInteger("account.http.port",DEFAULT_PORT),deployment)) .compose(actualport -> publishHttpEndpoint(SERVICE_NAME, config().getString("account.http.address",DEFAULT_HOST),actualport)) .compose(some -> deployverticles()) .setHandler(future.completer()); } private Future<Void> deployverticles() { Future<Void> result = Future.future(); vertx.deployVerticle(new AccountVerticle(),handler->{ if(handler.failed()){ result.fail("Failed to deploy verticle "); }else{ log.info("Deployed account verticle with id {}",handler.result()); } }); return result; } }
package com.jxqdwh.erp.service.Impl; import com.jxqdwh.erp.entity.Users; import com.jxqdwh.erp.mapper.UsersMapper; import com.jxqdwh.erp.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Autowired private UsersMapper userMapper; @Override public Users findUserById(int userId) { return userMapper.findById(userId) ; } }
package net.sourceforge.vrapper.vim.commands; import net.sourceforge.vrapper.platform.Configuration; import net.sourceforge.vrapper.utils.ContentType; import net.sourceforge.vrapper.utils.TextRange; import net.sourceforge.vrapper.vim.EditorAdaptor; public class MultipliedTextObject implements TextObject { private final int count; private final TextObject textObject; public MultipliedTextObject(int count, TextObject textObject) { this.count = count; this.textObject = textObject; } public ContentType getContentType(Configuration configuration) { return textObject.getContentType(configuration); } public TextRange getRegion(EditorAdaptor editorMode, int count) throws CommandExecutionException { return textObject.getRegion(editorMode, count); } public TextObject withCount(int count) { return new MultipliedTextObject(count, textObject); } public int getCount() { return count; } }
package com.selesgames.weave.ui.main; import com.selesgames.weave.ui.BaseFragment; public class ShareFragment extends BaseFragment { public static ShareFragment newInstance() { return new ShareFragment(); } }
package org.melayjaire.boimela.utils; import android.content.Context; import org.melayjaire.boimela.R; import org.melayjaire.boimela.model.SearchType; import java.util.HashMap; import java.util.Map; public class SearchCategoryMap { Map<String, SearchType> nameCategoryMap; public SearchCategoryMap(Context context) { nameCategoryMap = new HashMap<String, SearchType>(); createMap(context); } private void createMap(Context context) { nameCategoryMap.put(context.getString(R.string.title), SearchType.Title); nameCategoryMap.put(context.getString(R.string.author), SearchType.Author); nameCategoryMap.put(context.getString(R.string.publisher), SearchType.Publisher); nameCategoryMap.put(context.getString(R.string.category), SearchType.Category); nameCategoryMap.put(context.getString(R.string.new_book), SearchType.NewBook); nameCategoryMap.put(context.getString(R.string.favorite_books), SearchType.Favorites); } public SearchType obtain(String categoryName) { return nameCategoryMap.get(categoryName); } }
package leetcode; // 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。 // //比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下: // //L C I R //E T O E S I I G //E D H N //之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。 public class Z字形变换 { public static void main(String[] args) { // String str = "LEETCODEISHIRING"; String str ="ABCD"; // StringBuilder[] sb = new StringBuilder[2]; // char ch = str.charAt(0); // sb[0].append(ch); // System.out.println(sb[0]); System.out.println(convert(str,4)); } public static String convert(String s, int numRows) { if("".equals(s)) return ""; // 注意下这里的判断 StringBuilder[] sb = new StringBuilder[numRows]; for (int i = 0; i < numRows; i++) { sb[i] = new StringBuilder(); } int len = s.length(); int index = 0; int sb_index = 0; String res = ""; while(true) { for (sb_index = 0; sb_index < numRows && index<len; sb_index++) { sb[sb_index].append(s.charAt(index++)); if (index == len) break; } for (sb_index -= 2; sb_index > 0 && index<len; sb_index--) { sb[sb_index].append(s.charAt(index++)); if (index == len) break; } if(index == len) break; } for(int i = 0; i < numRows; i++) { res +=sb[i].toString(); } return res; } }
package 手撕; /** * @Author: Mr.M * @Date: 2019-05-06 16:52 * @Description: **/ public class 两数之和 { }
package Second; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; public class DragandDrop { public static void main(String[] args) { // Set the property for webdriver.chrome.driver to be the location to your local download of chromedriver System.setProperty("webdriver.chrome.driver", "C:\\Users\\bkudupudi\\Desktop\\Bhagya\\Selenium\\chromedriver_win32\\chromedriver.exe"); // Create new instance of ChromeDriver WebDriver driver = new ChromeDriver(); // And now use this to visit webpage driver.get("https://formy-project.herokuapp.com/dragdrop"); WebElement src = driver.findElement(By.id("image")); WebElement dest = driver.findElement(By.id("box")); Actions a = new Actions(driver); a.dragAndDrop(src, dest).build().perform(); System.out.println(driver.findElement(By.xpath("//div[@id='box']/p")).getText()); driver.quit(); } }
package com.jst.mapper.course; import java.util.List; import org.apache.ibatis.annotations.Param; import com.jst.model.EduCourseFavorites; public interface EduCourseFavoritesMapper { int deleteByPrimaryKey(Integer id); int insert(EduCourseFavorites record); int insertSelective(EduCourseFavorites record); EduCourseFavorites selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(EduCourseFavorites record); int updateByPrimaryKey(EduCourseFavorites record); }
package ericlwan_CSCI201_FinalProject; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.Vector; import javax.swing.JFrame; import ericlwan_CSCI201_FinalProject.HistoricalData.Averages; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Locale; import jxl.CellView; import jxl.Workbook; import jxl.WorkbookSettings; import jxl.format.UnderlineStyle; import jxl.write.Formula; import jxl.write.Label; import jxl.write.Number; import jxl.write.WritableCellFormat; import jxl.write.WritableFont; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; // Class used for exporting data to comma delimitted form as well as Excel file class ExportData implements ActionListener{ //Variables to store Data Vector<Car> cars; public ExportData(Vector<Car> cars){ this.cars=cars; } public void actionPerformed(ActionEvent ae) { WriteExcel test = new WriteExcel(cars); test.setOutputFile("exportedData.xls"); try { test.write(); } catch (WriteException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Please refresh the project and" + "check the result file under exportedData.xls"); System.out.println("Please refresh the project and" + "check the result file under ExportedCommaDelimitedData.cvs"); } } class WriteExcel { private GenerateCsv cvs=new GenerateCsv(); private WritableCellFormat timesBoldUnderline; private WritableCellFormat times; private String inputFile; private Vector<Car> cars; public WriteExcel(Vector<Car> cars2){ this.cars=cars2; } public void setOutputFile(String inputFile) { this.inputFile = inputFile; } public void write() throws IOException, WriteException { File file = new File(inputFile); WorkbookSettings wbSettings = new WorkbookSettings(); wbSettings.setLocale(new Locale("en", "EN")); WritableWorkbook workbook = Workbook.createWorkbook(file, wbSettings); workbook.createSheet("Report", 0); WritableSheet excelSheet = workbook.getSheet(0); createLabel(excelSheet); createContent(excelSheet); cvs.generateCsvFile("ExportedCommaDelimitedData.cvs",ProjectGUI.hours); workbook.write(); workbook.close(); } private void createLabel(WritableSheet sheet) throws WriteException { // Lets create a times font WritableFont times10pt = new WritableFont(WritableFont.TIMES, 10); // Define the cell format times = new WritableCellFormat(times10pt); // Lets automatically wrap the cells times.setWrap(true); // create create a bold font with unterlines WritableFont times10ptBoldUnderline = new WritableFont(WritableFont.TIMES, 10, WritableFont.BOLD, false, UnderlineStyle.SINGLE); timesBoldUnderline = new WritableCellFormat(times10ptBoldUnderline); // Lets automatically wrap the cells timesBoldUnderline.setWrap(true); CellView cv = new CellView(); cv.setFormat(times); cv.setFormat(timesBoldUnderline); cv.setAutosize(true); // Write a few headers addCaption(sheet, 1, 0, "405 Average Speed"); addCaption(sheet, 2, 0, "101 Average Speed"); addCaption(sheet, 3, 0, "105 Average Speed"); addCaption(sheet, 4, 0, "10 Average Speed"); for(int i=0;i<ProjectGUI.hours.size();i++){ addCaption(sheet, 0, (i+1), "Hour"+(i+1)); if((i)<12){ if((i)==0) addCaption(sheet, 0, (i+1), "12 AM"); else addCaption(sheet, 0, (i+1), (i)+"AM"); } else if((i)>=12){ if((i)==12) addCaption(sheet, 0, (i+1), "12 PM"); else addCaption(sheet, 0, (i+1), ((i)-12)+"PM"); } } } private void createContent(WritableSheet sheet) throws WriteException, RowsExceededException { // Write a few number Vector<Averages> hours=new Vector<Averages>(); hours=ProjectGUI.hours; for (int i = 1; i < hours.size()+1; i++) { // First column addNumber(sheet, 1, i, (int)hours.get(i-1).fouroavg); addNumber(sheet, 2, i, (int)hours.get(i-1).oneOoneavg); addNumber(sheet, 3, i, (int)hours.get(i-1).oneOfiveavg); addNumber(sheet, 4, i, (int)hours.get(i-1).tenavg); } } private void addCaption(WritableSheet sheet, int column, int row, String s) throws RowsExceededException, WriteException { Label label; label = new Label(column, row, s, timesBoldUnderline); sheet.addCell(label); } private void addNumber(WritableSheet sheet, int column, int row, Integer integer) throws WriteException, RowsExceededException { Number number; number = new Number(column, row, integer, times); sheet.addCell(number); } private void addLabel(WritableSheet sheet, int column, int row, String s) throws WriteException, RowsExceededException { Label label; label = new Label(column, row, s, times); sheet.addCell(label); } } class GenerateCsv { void generateCsvFile(String sFileName, Vector<Averages> hours) { try { FileWriter writer = new FileWriter(sFileName); writer.append("Times"); writer.append(','); writer.append("405 Average Time"); writer.append(','); writer.append("101 Average Time"); writer.append(','); writer.append("105 Average Time"); writer.append(','); writer.append("10 Average Time"); writer.append('\n'); for(int i=0;i<hours.size();i++){ //writer.append(String.valueOf(i+1)); if((i)<12){ if((i)==0) writer.append("12 AM"); else writer.append((i)+" AM"); } else if((i)>=12){ if((i)==12) writer.append("12 PM"); else writer.append(((i)-12)+" PM"); } writer.append(','); writer.append(Double.toString(hours.get(i).fouroavg)); writer.append(','); writer.append(Double.toString(hours.get(i).oneOoneavg)); writer.append(','); writer.append(Double.toString(hours.get(i).oneOfiveavg)); writer.append(','); writer.append(Double.toString(hours.get(i).tenavg)); writer.append('\n'); } writer.flush(); writer.close(); } catch(IOException e) { e.printStackTrace(); } } }
package jp.co.logacy.dto.search; /** * DVD/Blu-ray検索用の検索条件保持DTO * * @author y_someya * */ public class KensakuJokenDto { /** タイトル */ public String title; /** 出演者名 */ public String artistName; /** 販売元名 */ public String label; /** JANコード */ public String jan; /** 楽天ブックジャンルID */ public String booksGenreId; /** アフェリエイトID */ public String affiliateId; /** 出力パラメータ指定 */ public String elements; /** 出力フォーマットバージョン */ public String formatVersion; /** 1ページあたりの取得件数 */ public String hits; /** 取得ページ */ public String page; /** 在庫状況 */ public String availability; /** 品切れ等、購入不可商品表示フラグ */ public String outOfStockFlag; /** ソート */ public String sort; /** 限定フラグ */ public String limitedFlag; /** キャリア */ public String carrier; /** ジャンルごとの商品数取得フラグ */ public String genreInformationFlag; }
package net.xekr.xkdeco.itemgroup; import net.xekr.xkdeco.block.MayaChiseledStonebricksBlock; import net.xekr.xkdeco.XkdecoModElements; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.api.distmarker.Dist; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemGroup; @XkdecoModElements.ModElement.Tag public class XkDecoMoreAncientCivilizationsItemGroup extends XkdecoModElements.ModElement { public XkDecoMoreAncientCivilizationsItemGroup(XkdecoModElements instance) { super(instance, 463); } @Override public void initElements() { tab = new ItemGroup("tabxk_deco_more_ancient_civilizations") { @OnlyIn(Dist.CLIENT) @Override public ItemStack createIcon() { return new ItemStack(MayaChiseledStonebricksBlock.block, (int) (1)); } @OnlyIn(Dist.CLIENT) public boolean hasSearchBar() { return false; } }; } public static ItemGroup tab; }
package pt.ipbeja.estig.po2.boulderdash.model.pieces; import javafx.scene.image.Image; /** * @author Tomás Jorge, 20436 * @author Luiz Felhberg, 20347 * @version 13/07/2021 */ public class ImmovableEnemy { public ImmovableEnemy() { } /** * @return Immovable Enemy image to set in the scene */ public static Image getImoEnemyImage() { return new Image("resources/images/imoEnemy.png"); } }
package net4game.ctx; import ctx.AbstractResponse; import ser.netty.websocket.WssResponse; public class NetResponse extends AbstractResponse<WssResponse> { }
package com.tencent.mm.ui.conversation.a; import android.content.Context; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.bg.d; import com.tencent.mm.model.bc; import com.tencent.mm.plugin.report.service.h; class k$5 implements OnClickListener { final /* synthetic */ int bpX; final /* synthetic */ int tiP; final /* synthetic */ k usq; k$5(k kVar, int i, int i2) { this.usq = kVar; this.bpX = i; this.tiP = i2; } public final void onClick(View view) { bc.Ig().ba(this.bpX, this.tiP); Context context = (Context) this.usq.qJS.get(); Intent intent = new Intent(); intent.putExtra("preceding_scence", 17); d.b(context, "emoji", ".ui.v2.EmojiStoreV2UI", intent); h.mEJ.h(11002, new Object[]{Integer.valueOf(10), Integer.valueOf(1)}); h.mEJ.h(12065, new Object[]{Integer.valueOf(2)}); } }
package com.libedi.demo.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.libedi.demo.domain.Academy; /** * AcademyRepository * * @author Sang-jun, Park * @since 2019. 02. 07 */ public interface AcademyRepository extends JpaRepository<Academy, Long>, AcademyRepositoryCustom { }
package com.lizikj.tracker; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ImportResource; import com.lizikj.tracker.annotation.EnableTraceAutoConfigurationProperties; /** * * @auth zone * @date 2017-10-18 */ @SpringBootApplication @ImportResource({ "classpath:xml/xxxxxx.xml" }) @ComponentScan(basePackages = { "com.lizikj.tracker" }) @EnableTraceAutoConfigurationProperties public class Bootstrap { public static void main(String[] args) { ApplicationContext ctx = new SpringApplicationBuilder().sources(Bootstrap.class).web(false).run(args); } }
package com.tencent.mm.plugin.appbrand.debugger; import android.webkit.ValueCallback; public final class a { public String bHA; public ValueCallback<String> fsu; public long fsv; public int size; }
package Grant_Application_page; import helper.Wait.WaitHelper; import helper.genericHelper.GenericHelper; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import configreader.ObjectRepo; public class Contact_details_page { WebDriver driver; //private final Logger log = LoggerHelper.getLogger(Create_new_account_page.class); WaitHelper waitHelper; Actions actions; @FindBy(xpath=".//span[text()='Contact Details']") WebElement Contact_Details; @FindBy(xpath=".//input[@id='react-contact_info-name']") WebElement Name_field; @FindBy(xpath=".//input[@id='react-contact_info-designation']") WebElement Job_Title; @FindBy(xpath=".//input[@id='react-contact_info-phone']") WebElement Job_phone; @FindBy(xpath=".//input[@id='react-contact_info-primary_email']") WebElement Job_Email; @FindBy(xpath=".//input[@id='react-contact_info-correspondence_address-copied']") WebElement Mailing_Address; @FindBy(xpath=".//input[@id='react-contact_info-copied']") WebElement offer_address; @FindBy(xpath=".//input[@id='react-contact_info-correspondence_address-postal']") WebElement Postal_code; @FindBy(xpath=".//input[@id='react-contact_info-name']") WebElement Names_fields; @FindBy(xpath=".//input[@id='react-contact_info-offeree_name']") WebElement Letter_offer_Name_field; public Contact_details_page(WebDriver driver) { this.driver = driver; PageFactory.initElements(driver, this); waitHelper = new WaitHelper(driver); pattern=Pattern.compile(zipcodePattern); // } final static String zipcodePattern="\\b[0-9]{5}(?:-[0-9]{4})?\\b"; private static Pattern pattern; private static Matcher matcher; public boolean validate (String ZipCode) { matcher=pattern.matcher(ZipCode); return matcher.matches(); } public String Same_as_main_contact_person() { //return new GenericHelper().isDisplayed(successMsgObject); return new GenericHelper().getElementTexts(Letter_offer_Name_field); } public boolean Letter_offer_Name_field() { //return new GenericHelper().isDisplayed(successMsgObject); return new GenericHelper().isDisplayed(Letter_offer_Name_field); } public String Names_fields() { //return new GenericHelper().isDisplayed(successMsgObject); return new GenericHelper().getElementTexts(Names_fields); } public String verify_postalcode_results() { //return new GenericHelper().isDisplayed(successMsgObject); return new GenericHelper().getElementTexts(Postal_code); } public void offer_address() throws InterruptedException { waitHelper.waitForElement(driver, offer_address,ObjectRepo.reader.getPageLoadTimeOut()); waitHelper.waitForElement(driver, offer_address,ObjectRepo.reader.getExplicitWait()); actions = new Actions(driver); actions.moveToElement(offer_address); actions.click().build().perform(); } public void Mailing_Address() throws InterruptedException { waitHelper.waitForElement(driver, Mailing_Address,ObjectRepo.reader.getPageLoadTimeOut()); waitHelper.waitForElement(driver, Mailing_Address,ObjectRepo.reader.getExplicitWait()); actions = new Actions(driver); actions.moveToElement(Mailing_Address); actions.click().build().perform(); } public void Job_Email(String Job_Email) throws InterruptedException { //log.info("entering sigin_password." + sigin_password); this.Job_Email.clear(); this.Job_Email.sendKeys(Job_Email); } public void Job_phone(String Job_phone) throws InterruptedException { //log.info("entering sigin_password." + sigin_password); this.Job_phone.clear(); this.Job_phone.sendKeys(Job_phone); } public void Job_Title(String Job_Title) throws InterruptedException { //log.info("entering sigin_password." + sigin_password); this.Job_Title.clear(); this.Job_Title.sendKeys(Job_Title); } public void Name_field(String Name_field) throws InterruptedException { //log.info("entering sigin_password." + sigin_password); this.Name_field.clear(); this.Name_field.sendKeys(Name_field); } public void Contact_Details() throws InterruptedException { waitHelper.waitForElement(driver, Contact_Details,ObjectRepo.reader.getPageLoadTimeOut()); waitHelper.waitForElement(driver, Contact_Details,ObjectRepo.reader.getExplicitWait()); actions = new Actions(driver); actions.moveToElement(Contact_Details); actions.click().build().perform(); } }
package com.globomart.catalog.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import com.globomart.catalog.dao.ProductRepository; import com.globomart.catalog.dao.ProductSpecification; import com.globomart.catalog.defs.SearchType; import com.globomart.catalog.exceptions.GloboMartException; import com.globomart.catalog.models.Product; import com.globomart.catalog.service.CatalogService; @Component @Service public class CatalogServiceImpl implements CatalogService{ private ProductRepository productRepo; public CatalogServiceImpl() { } public CatalogServiceImpl(ProductRepository productRepo) { this.productRepo=productRepo; } public ProductRepository getProductRepo() { return productRepo; } @Autowired public void setProductRepo(ProductRepository productRepo) { this.productRepo = productRepo; } @Override public Product addProduct(Product product) { productRepo.save(product); return product; } @Override public void removeProduct(Long productId) { productRepo.deleteById(productId); } @Override public List<Product> searchProducsts(String queryString, SearchType searchType) throws GloboMartException { List<Product> products=null; if(SearchType.BY_PRODUCT_NAME.equals(searchType)) { products=productRepo.findAll(ProductSpecification.productNameIsLike(queryString)); }else if(SearchType.BY_PRODUCT_DESCRIPTION.equals(searchType)){ products=productRepo.findAll(ProductSpecification.productDescIsLike(queryString)); } return products; } @Override public Page<Product> searchProducts(String queryString, SearchType searchType, int page_no, int page_size) { // TODO Auto-generated method stub return null; } @Override public List<Product> listProducts() { return productRepo.findAll(); } }
package specification; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; import java.util.ArrayList; import java.util.List; /** * Created by Tomas Hanus on 2/21/2015. */ @XmlAccessorType(XmlAccessType.NONE) public class Listeners { @XmlElements({ @XmlElement(name = "listener", type = Listener.class) }) private List<Listener> listeners; public Listeners() { } public Listeners(List<Listener> listeners) { this.listeners = listeners; } public void addNewListener(String ref) { if (this.listeners == null) this.listeners = new ArrayList<Listener>(); this.listeners.add(new Listener(ref)); } public void removeListener(Listener listener) { if (this.listeners == null) return; this.listeners.remove(listener); } public void removeAllListeners() { this.listeners.clear(); } public List<Listener> getListeners() { return listeners; } public void setListeners(List<Listener> listeners) { this.listeners = listeners; } }
package com.example.passin.encryption; import lombok.Getter; import lombok.Setter; @Getter @Setter public class InitializationVector { private byte[] iv; private byte[] nonce; }