blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
7
332
content_id
stringlengths
40
40
detected_licenses
listlengths
0
50
license_type
stringclasses
2 values
repo_name
stringlengths
7
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
557 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
684M
star_events_count
int64
0
77.7k
fork_events_count
int64
0
48k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
82 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
5.41M
extension
stringclasses
11 values
content
stringlengths
7
5.41M
authors
listlengths
1
1
author
stringlengths
0
161
0caebc31de38b7b61b7564745386313d741bcc19
e28e312289a0f5b928b8bbd6112f08c7313c9f61
/app/src/main/java/com/example/accountingapplication/MainActivity.java
332e637ae51d63e399008d6abe020dc8c933a195
[]
no_license
Leon020498/CS4084MADGroup11
a78f001b02efddeb870ddc0f75a4f2dd9a1c5a4f
27ab8660c04e42ed0a6c4a6f1eb5b5320998ea3c
refs/heads/master
2021-02-18T09:39:18.703178
2020-04-04T08:24:46
2020-04-04T08:24:46
245,182,502
0
0
null
null
null
null
UTF-8
Java
false
false
4,979
java
package com.example.accountingapplication; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ListView; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private List<CostBean> mCostBeanList; private DatabaseHelper mDatabaseHelper; private CostListAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); mDatabaseHelper=new DatabaseHelper(this); mCostBeanList=new ArrayList<>(); ListView costList=(ListView)findViewById(R.id.lv_main); initCostData(); //抽象命名 mAdapter = new CostListAdapter(this, mCostBeanList); costList.setAdapter(mAdapter); FloatingActionButton fab = findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) //.setAction("Action", null).show(); AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this); LayoutInflater inflater=LayoutInflater.from(MainActivity.this); View viewDialog=inflater.inflate(R.layout.new_caost_data,null); final EditText title=(EditText) viewDialog.findViewById(R.id.et_cost_title); final EditText money=(EditText)viewDialog.findViewById(R.id.et_cost_money); final DatePicker date=(DatePicker) viewDialog.findViewById(R.id.dp_cost_date); builder.setView(viewDialog); builder.setTitle("New Cost"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { CostBean costBean = new CostBean(); costBean.costTitle = title.getText().toString(); costBean.costMoney=money.getText().toString(); costBean.costDate=date.getYear()+"-"+(date.getMonth()+1)+"-"+ date.getDayOfMonth(); mDatabaseHelper.insertCost(costBean); mCostBeanList.add(costBean); mAdapter.notifyDataSetChanged(); } }).setNegativeButton("Cancel", null); builder.create().show(); } }); } private void initCostData() { //mDatabaseHelper.deleteAllCostData(); /*for (int i=0;i<5;i++) { CostBean costBean = new CostBean(); costBean.costTitle=i+"mock"; costBean.costDate="11-11"; costBean.costMoney="20"; //mCostBeanList.add(costBean); mDatabaseHelper.insertCost(costBean); }*/ Cursor cursor=mDatabaseHelper.getAllCostData(); if(cursor!=null){ while (cursor.moveToNext()){ CostBean costBean=new CostBean(); costBean.costTitle=cursor.getString(cursor.getColumnIndex("cost_title")); costBean.costDate=cursor.getString(cursor.getColumnIndex("cost_date")); costBean.costMoney=cursor.getString(cursor.getColumnIndex("cost_money")); mCostBeanList.add(costBean); //mAdapter.notifyDataSetChanged(); } cursor.close(); } } @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) { int id = item.getItemId(); if (id == R.id.action_chart) { //! Intent intent=new Intent(MainActivity.this,ChartsActivity.class); //传递List intent.putExtra("cost_list",(Serializable)mCostBeanList); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } }
90fb3d5a024efb2b72a5e6b2c380bd3cbc61b573
de31c132730cb32c46454b168e5b682461c53516
/API/src/main/java/se/vidstige/jadb/AdbServerLauncher.java
c1031770cb71ef3c9be41830f237dabd6ed59992
[ "MIT" ]
permissive
kensoh/SikuliX1
a70c0c4d26fdcf159139ac2e8711ac612982025a
a4feaa44c83bc75ff2541dd3eaba454dd216f9bf
refs/heads/master
2020-07-31T06:49:39.935035
2019-09-17T07:08:48
2019-09-17T07:08:48
210,520,732
1
0
MIT
2019-09-24T05:41:36
2019-09-24T05:41:36
null
UTF-8
Java
false
false
1,599
java
/* * Copyright (c) 2010-2019, sikuli.org, sikulix.com - MIT license */ package se.vidstige.jadb; import java.io.IOException; import java.util.Map; /** * Launches the ADB server */ public class AdbServerLauncher { private final String executable; private Subprocess subprocess; /** * Creates a new launcher loading ADB from the environment. * * @param subprocess the sub-process. * @param environment the environment to use to locate the ADB executable. */ public AdbServerLauncher(Subprocess subprocess, Map<String, String> environment) { this(subprocess, findAdbExecutable(environment)); } /** * Creates a new launcher with the specified ADB. * * @param subprocess the sub-process. * @param executable the location of the ADB executable. */ public AdbServerLauncher(Subprocess subprocess, String executable) { this.subprocess = subprocess; this.executable = executable; } private static String findAdbExecutable(Map<String, String> environment) { String androidHome = environment.get("ANDROID_HOME"); if (androidHome == null || androidHome.equals("")) { return "adb"; } return androidHome + "/platform-tools/adb"; } public void launch() throws IOException, InterruptedException { Process p = subprocess.execute(new String[]{executable, "start-server"}); p.waitFor(); int exitValue = p.exitValue(); if (exitValue != 0) throw new IOException("adb exited with exit code: " + exitValue); } }
c6c87a30b6f0ee720d110b8b7b22b4ea7a74c70d
d3c10ec1e11acbfe20dda071a83554bebe0c916a
/src/biblioteca1/Biblioteca1.java
098a7b63b2986c4d71ee468555336e07b5b5ebed
[]
no_license
a21pablogo/Biblioteca1
63f3c38469ed5d81b30119fcaabf145999c70317
00782d937169be9f6a1ca66c063d519f1134127e
refs/heads/master
2023-08-29T13:34:35.084087
2021-10-10T15:39:59
2021-10-10T15:39:59
415,625,669
0
0
null
null
null
null
UTF-8
Java
false
false
2,959
java
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template */ package biblioteca1; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Scanner; import java.util.ArrayList; public class Biblioteca1{ /** * @param args the command line arguments */ public static void main(String[] args) throws IOException { String ficheroR= "C:\\Users\\Pablo\\Documents\\Revistas.txt"; String ficheroL= "C:\\Users\\Pablo\\Documents\\Libros.dat"; ArrayList <Libro> Libros=new ArrayList<>(); ArrayList <Revista> Revistas=new ArrayList<>(); Libro libro1 = new Libro("A12354B","La isla del tesoro",2000,false,true,"Si"); Revista resvista1 = new Revista("R784325B","cosmopolitan",2021,187); Libro libro2 = new Libro("A14634B","Tres mil leguas submarinas",2000,false,true,"Si"); Revista resvista2 = new Revista("R7248575B","Platboy",2021,187); /*Libros.add(libro2); Revistas.add(resvista1); Revistas.add(resvista2); hola */ Scanner sc = new Scanner(System.in); // IMPORTANTE PARA LECTURA DE LOS FICHEROS .TXT (instanceof) /* libro1.setPresta(false); libro1.estaPrestado(valor.estaPrestado); libro1.setDevuelve(true);*/ Libros.add(libro1); Libros.add(libro2); Revistas.add(resvista1); Revistas.add(resvista2); //Guardar registros de Libros en un fichero try { File FicheroLibros=new File(ficheroL); ObjectOutputStream ficheroSalida = new ObjectOutputStream (new FileOutputStream(ficheroL)); ficheroSalida.writeObject(libro1); ficheroSalida.flush(); ficheroSalida.close(); System.out.println("registro de libros guardos correctamente..."); } catch (FileNotFoundException fnfe) { System.out.println("Error: El fichero no existe. "); } catch (IOException ioe) { System.out.println(ioe.getMessage()); } try { ObjectOutputStream ficheroSalida = new ObjectOutputStream (new FileOutputStream(ficheroR)); ficheroSalida.writeObject(Revistas); ficheroSalida.flush(); ficheroSalida.close(); System.out.println("Registro de revista guardado correctamente..."); } catch (FileNotFoundException fnfe) { System.out.println("Error: El fichero no existe. "); } catch (IOException ioe) { System.out.println("Error: Fallo en la escritura en el fichero. "); } } }
ba1ed46da0f238e5c31c9a1ea9c13c8a8870b67d
bccb412254b3e6f35a5c4dd227f440ecbbb60db9
/hl7/character/group/NK1_TIMING_QTY_PEX_P07.java
430d35307eb19da2392a289fa800d04b47a33192
[]
no_license
nlp-lap/Version_Compatible_HL7_Parser
8bdb307aa75a5317265f730c5b2ac92ae430962b
9977e1fcd1400916efc4aa161588beae81900cfd
refs/heads/master
2021-03-03T15:05:36.071491
2020-03-09T07:54:42
2020-03-09T07:54:42
245,967,680
0
0
null
null
null
null
UTF-8
Java
false
false
210
java
package hl7.character.group; import hl7.bean.Structure; public abstract class NK1_TIMING_QTY_PEX_P07 extends hl7.bean.group.Group{ protected void setCharacter(Structure[][] components, String version){ } }
207544aa582b46ff3ecc46221439ba8777fbfc79
21790217ea5aaceb77a599f2fb99b85fd916826a
/demo/questions/IntegerArray.java
08f9f54a35da56a867f498426d5d5c2cd48d1e05
[]
no_license
toashishagarwal/JavaProblems
dcb40197fee859e5aa31e95bf6423ffa3f5d4447
e4dbabf7f8f94d6dc71f6e2e2346ee248a4c08b2
refs/heads/master
2021-01-13T02:03:24.857333
2016-01-13T13:48:45
2016-01-13T13:48:45
32,247,750
0
0
null
null
null
null
UTF-8
Java
false
false
1,530
java
package demo.questions; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /************************************************************************************* * For a given unsorted integer array, it finds out the repeats in the array * * @author agarwala * * * ************************************************************************************/ public class IntegerArray { /** * @param args */ public static void main(String[] args) { int[] input = new int[7]; input[0] = 4; input[1] = 4; input[2] = 2; input[3] = 5; input[4] = 5; input[5] = 9; input[6] = 4; printRepeats(input); } private static void printRepeats(int[] input) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i = 0; i < input.length ;i++) { Integer temp = map.get(input[i]); if( temp == null ) { map.put(input[i], 1); } else { map.put(input[i], temp + 1); } } Set<Entry<Integer, Integer>> set = map.entrySet(); for(Entry<Integer, Integer> e : set) { if((Integer)e.getValue() > 1) { System.out.println("" + e.getKey()); } } } }
7e469253609c593033da8fa78a607114024d3910
69b56436cb2f49f5a3fa22f49adba7e43534a63b
/src/main/java/com/gbiac/fams/business/construction/workapprove/service/impl/FamsWorkApproveNoPassServiceImpl.java
39466bc704295a5733de2d68093e59a04a56b2f9
[]
no_license
heshanlong/jeecg-master-danei
c72131aa4c2b8cf37afebe244b234570bb2f32da
bdd28df22074aa47fc54fe5ff172cc21e2ae6e8d
refs/heads/master
2022-12-27T07:23:24.438473
2019-10-25T09:08:56
2019-10-25T09:08:56
217,480,219
0
0
null
2022-12-06T00:44:04
2019-10-25T07:47:48
JavaScript
UTF-8
Java
false
false
1,305
java
package com.gbiac.fams.business.construction.workapprove.service.impl; import java.io.Serializable; import java.util.List; import org.jeecgframework.core.common.service.impl.CommonServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.gbiac.fams.business.construction.workapprove.dao.FamsWorkApproveNoPassDao; import com.gbiac.fams.business.construction.workapprove.entity.FamsWorkApproveNoPassEntity; import com.gbiac.fams.business.construction.workapprove.service.FamsWorkApproveNoPassServiceI; @Service("famsWorkApproveNoPassService") @Transactional public class FamsWorkApproveNoPassServiceImpl extends CommonServiceImpl implements FamsWorkApproveNoPassServiceI{ @Autowired private FamsWorkApproveNoPassDao famsWorkApproveNoPassDao; @Override public Serializable save(FamsWorkApproveNoPassEntity entity) throws Exception { Serializable t = super.save(entity); return t; } @Override public List<?> getNoPassApprove(String searchInput, Integer pageNum, Integer pageSize, String userName) throws Exception { return famsWorkApproveNoPassDao.getNoPassApprove(searchInput, pageNum, pageSize, userName); } }
2ce95acc683935e89bfd924f04ee1394de4de8aa
3756f9942a7af1f2d3bbab9034d29f588d3f6cf4
/src/main/java/com/xzp/redis/ReadRedis.java
fa94d951a526a071acb5d6afee69e7b7cb7e101c
[]
no_license
huajunge/XZPlusHBase
5eebf935b3255ed507ef949e885fe6bb2a775074
2506f85259c6f9c9d45070eb5bf29333b9a01a2e
refs/heads/master
2022-12-24T07:28:18.716809
2020-10-06T10:22:16
2020-10-06T10:22:16
289,676,326
0
1
null
null
null
null
UTF-8
Java
false
false
1,314
java
package com.xzp.redis; import com.xzp.curve.XZ2SFC; import com.xzp.curve.XZPlusSFC; import org.locationtech.sfcurve.IndexRange; import redis.clients.jedis.Jedis; import redis.clients.jedis.Pipeline; import scala.collection.Seq; import java.util.LinkedHashSet; import java.util.List; /** * @author : hehuajun3 * @description : * @date : Created in 2020-04-29 13:06 * @modified by : **/ public class ReadRedis { public static void main(String[] args) { double minLon = 116.39172; double minLat = 39.80123; double maxLon = 116.40072; double maxLat = 39.81023; double interval = 0.01; XZPlusSFC xzPlusSFC = XZPlusSFC.apply((short) 16); XZ2SFC xz2SFC = XZ2SFC.apply((short) 16); Seq<IndexRange> xzpRanges = xzPlusSFC.ranges(minLon, minLat, maxLon, maxLat); Seq<IndexRange> xzRanges = xz2SFC.ranges(minLon, minLat, maxLon, maxLat); Jedis jedis = new Jedis("127.0.0.1", 6379); Pipeline pipelined = jedis.pipelined(); pipelined.zrangeByScore("xzp_tdrive_test_hb", 4910563333L, 4910563333L); List<Object> o = pipelined.syncAndReturnAll(); LinkedHashSet<Object> oo = (LinkedHashSet<Object>) o.get(0); System.out.println(oo.size()); pipelined.close(); jedis.close(); } }
fd258c10429f95b091a1a64696121d6d55fa55ca
44e7adc9a1c5c0a1116097ac99c2a51692d4c986
/aws-java-sdk-workdocs/src/main/java/com/amazonaws/services/workdocs/model/DocumentThumbnailType.java
56f2dd83d23d9943612bc024d56e1ead0ea7c576
[ "Apache-2.0" ]
permissive
QiAnXinCodeSafe/aws-sdk-java
f93bc97c289984e41527ae5bba97bebd6554ddbe
8251e0a3d910da4f63f1b102b171a3abf212099e
refs/heads/master
2023-01-28T14:28:05.239019
2020-12-03T22:09:01
2020-12-03T22:09:01
318,460,751
1
0
Apache-2.0
2020-12-04T10:06:51
2020-12-04T09:05:03
null
UTF-8
Java
false
false
1,838
java
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.workdocs.model; import javax.annotation.Generated; /** * */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum DocumentThumbnailType { SMALL("SMALL"), SMALL_HQ("SMALL_HQ"), LARGE("LARGE"); private String value; private DocumentThumbnailType(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return DocumentThumbnailType corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static DocumentThumbnailType fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (DocumentThumbnailType enumEntry : DocumentThumbnailType.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
[ "" ]
c6fe5f1507353088dfa831f2d310b9df45ef6faa
38fcd622cb0d1a2d0970af0cbaa3e28d3a561fab
/SkynetWPILibClient/src/com/zhiquanyeo/skynet/defaultrobot/DefaultRobot.java
2adf7b9570abfef04161186d97a6d20705820328
[]
no_license
zhiquanyeo/skynet-wpilib-client
8a85201af1c0a59f9878a7ad98bda8e004638c7b
d0106d72afab6aec2bbf7599a992da7903b3c446
refs/heads/master
2021-01-10T01:49:08.727660
2016-02-15T22:00:54
2016-02-15T22:00:54
48,228,340
0
2
null
null
null
null
UTF-8
Java
false
false
1,665
java
package com.zhiquanyeo.skynet.defaultrobot; import edu.wpi.first.wpilibj.AnalogInput; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.DigitalOutput; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.RobotDrive; import edu.wpi.first.wpilibj.SampleRobot; import edu.wpi.first.wpilibj.Timer; public class DefaultRobot extends SampleRobot { private Joystick d_joystick; private RobotDrive d_drivetrain; private AnalogInput d_frontRangefinder; private AnalogInput d_rearRangefinder; private DigitalInput d_frontSwitch; private DigitalInput d_rearSwitch; private DigitalOutput d_outputLED; @Override protected void robotInit() { System.out.println("Default SkynetRobot starting up"); d_joystick = new Joystick(0); d_drivetrain = new RobotDrive(0, 1); d_frontRangefinder = new AnalogInput(0); d_rearRangefinder = new AnalogInput(1); d_frontSwitch = new DigitalInput(0); d_rearSwitch = new DigitalInput(1); d_outputLED = new DigitalOutput(2); } @Override protected void autonomous() { long lastTime = 0; boolean outputVal = false; double speed = 0.5; while (isEnabled() && isAutonomous()) { if (System.currentTimeMillis() - lastTime > 1000) { outputVal = !outputVal; speed = -speed; d_outputLED.set(outputVal); d_drivetrain.tankDrive(speed, speed); lastTime = System.currentTimeMillis(); } } } @Override protected void operatorControl() { while (isEnabled() && isOperatorControl()) { d_drivetrain.arcadeDrive(-d_joystick.getRawAxis(1), -d_joystick.getRawAxis(0), true); d_outputLED.set(d_joystick.getRawButton(1)); } } }
a42f93f6751aa4435e0f18e19142f3a691a512e5
9a8ec608da9b410baf6a4e402a9c51cd748252d8
/tokTales-chess/tokTales-chess-core/src/main/java/com/tokelon/chess/core/logic/mock/MockUCIConnector.java
3cca217f50f7e69c37b5154224913dd89df649f0
[ "MIT" ]
permissive
Tokelon/tokTales-demos
406c10a91efc3fc6c7a2daaa6db4541d38c9a9ce
25a5c72dac9e90ef48397bcbda4e9b8433af59f0
refs/heads/master
2023-03-28T13:32:14.373821
2021-03-28T16:21:56
2021-03-28T16:21:56
235,998,554
2
0
MIT
2020-10-03T14:42:17
2020-01-24T12:25:44
Java
UTF-8
Java
false
false
935
java
package com.tokelon.chess.core.logic.mock; import com.tokelon.chess.core.logic.uci.IUCIConnector; import com.tokelon.chess.core.logic.uci.IUCIConnectorFactory; import com.tokelon.chess.core.tools.ISplitterOutputStream; import java9.util.stream.Stream; public class MockUCIConnector implements IUCIConnector { @Override public void send(String input) { } @Override public Stream<String> send(String input, String until) { return null; } @Override public Stream<String> receive(String until) { return null; } @Override public Stream<String> readInput() { return null; } @Override public void close() { } public static class MockUCIConnectorFactory implements IUCIConnectorFactory { @Override public IUCIConnector create(ISplitterOutputStream splitterOut) { return new MockUCIConnector(); } } }
aa5fd2bfda35cbffb0f0e71b965ca55d99661b82
2a8dce25f382e62fae46f561b3e512c29f81621f
/library_management/src/main/java/com/tyss/library/management/librarymanagement/service/AdminServiceImpl.java
57e4c11b9042c6c393bf96e8a6b43c60dc2988c0
[]
no_license
MGuruSwamyTY/LMS
91d59ef5686900f8d733538f3f675744a193169d
e00f05990f74d3bb89ab8b28b2a4d51be00b1f01
refs/heads/master
2023-08-09T02:54:50.646138
2019-11-06T13:02:06
2019-11-06T13:02:06
219,908,434
0
0
null
null
null
null
UTF-8
Java
false
false
1,282
java
package com.tyss.library.management.librarymanagement.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.tyss.library.management.librarymanagement.dao.AdminImpl; import com.tyss.library.management.librarymanagement.dto.BooksInventory; import com.tyss.library.management.librarymanagement.dto.UserInfo; @Service public class AdminServiceImpl implements AdminService{ @Autowired private AdminImpl admin; @Override public boolean registerUser(UserInfo user, String to, String subject, String body) { return admin.registerUser(user,to,subject,body); } @Override public boolean deleteUser(String email) { return admin.deleteUser(email); } @Override public boolean updateUser(UserInfo user) { return admin.updateUser(user); } @Override public List<BooksInventory> getAllBook() { return admin.getAllBook(); } @Override public List<UserInfo> getAllUser() { return admin.getAllUser(); } @Override public UserInfo login(String email, String password) { return admin.login(email, password); } // @Override // public UserInfo searchUser(String email) { // return admin.searchuser(email); // } }
ff3ed7d42e803be4da87a94b04a2a7f54af8d51d
e659a209f86ac6b3c32e76a959cd0a6cee6bf4a4
/src/main/java/com/itt/utils/DeviceLogger.java
35687898787c002fac14c8dbb7ad7a8a80d1c872
[]
no_license
Srinivasvarmaqa/itnf-driver
711927370a8d3c88408701cbf757b0524b3551f8
421532ac9924207c3d95b7a94e64e61fac740ac4
refs/heads/master
2023-06-27T03:48:18.687024
2021-08-04T00:27:50
2021-08-04T00:27:50
392,496,498
0
0
null
null
null
null
UTF-8
Java
false
false
2,073
java
package com.itt.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.itt.common.ReadStream; public class DeviceLogger implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(DeviceLogger.class); private volatile boolean keepAlive; private Process process; private String command; private final String SHELL = "/bin/sh"; private final String SHELL_OPTS = "-c"; public DeviceLogger(String logCommand) { this.command = logCommand; } public void setKeepAlive(Boolean state) { keepAlive = state; } public synchronized void stop() { process.destroy(); LOG.info("STOPPING THE LOG FOR TEST CASE"); } @Override public void run() { LOG.info("START LOGGING FOR TEST CASE"); while (true) { try { runProcessTillAlive(); if (!keepAlive) { stop(); break; } } catch (InterruptedException ie) { ie.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } private void runProcessTillAlive() throws IOException, InterruptedException { String line = ""; String output = ""; String[] actualCommand = { SHELL, SHELL_OPTS, command }; Runtime r = Runtime.getRuntime(); process = r.exec(actualCommand); ReadStream stdErr = new ReadStream("stderr", process.getErrorStream()); ReadStream stdOut = new ReadStream("stdin", process.getInputStream()); stdErr.start(); stdOut.start(); InputStream error = process.getErrorStream(); InputStreamReader isrerror = new InputStreamReader(error); BufferedReader bre = new BufferedReader(isrerror); try { while ((line = bre.readLine()) != null) { LOG.info(line); } LOG.info("ERROR OCCURED WHILE START LOGGING!!!"); this.keepAlive = false; } catch (Exception e) { LOG.info("No Error Stream!!!"+e.getMessage()); } finally { bre.close(); } process.waitFor(); } }
83d504a3587fea28529fbd8dbee8c337836864bb
532e2b24e7fb2b3c61d306dc044cb4df4aae97c8
/src/main/java/es/cnc/suscripciones/domain/Suscripcion.java
b73ea177e08bfdc5e83101192e9aa7c675e72f75
[]
no_license
fmerino-indra/recibos
cf77b63ad9c2c988e74673794454ee9a5d6f496d
3383ee79d23caf240a7cff5c59e30aaed690cf77
refs/heads/master
2021-01-14T08:27:36.156707
2017-12-13T11:36:32
2017-12-13T11:36:32
49,567,658
1
0
null
null
null
null
UTF-8
Java
false
false
6,895
java
package es.cnc.suscripciones.domain; import java.util.Date; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.springframework.format.annotation.DateTimeFormat; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.ObjectIdGenerators; @Entity @Table(name = "suscripcion") @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id") public class Suscripcion extends AbstractEntity<Integer> { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "IdSuscripcion") private Integer idSuscripcion; @Override public Integer getId() { return getIdSuscripcion(); } public Suscripcion() { super(Suscripcion.class); } @Override public void setId(Integer id) { setIdSuscripcion(id); } public Integer getIdSuscripcion() { return this.idSuscripcion; } public void setIdSuscripcion(Integer id) { this.idSuscripcion = id; } @OneToMany(mappedBy = "idSuscripcion", fetch = FetchType.LAZY) private Set<PSD> pSDs; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "secuenciaAdeudo", referencedColumnName = "id") private Secuenciaadeudo secuenciaAdeudo; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "persona", referencedColumnName = "id", nullable = true) private Persona persona; @Column(name = "FechaInicio") @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(style = "M-") private Date fechaInicio; @Column(name = "FechaBaja") @Temporal(TemporalType.TIMESTAMP) @DateTimeFormat(style = "M-") private Date fechaBaja; @Deprecated @Column(name = "PAGO", length = 1) private String pago; @Deprecated @Column(name = "PESETAS", precision = 22) private Double pesetas; @Column(name = "Divisa", length = 3) private String divisa; @Column(name = "PERIODO", length = 1) private String periodo; @Deprecated @Column(name = "DEVOLUCION", length = 10) private String devolucion; @Column(name = "Activo") private Boolean activo; @Deprecated @Column(name = "UltimaEmision") @Temporal(TemporalType.DATE) @DateTimeFormat(style = "M-") private Date ultimaEmision; @Deprecated @Column(name = "IdTitular") private Integer idTitular; @Column(name = "Euros", precision = 22) private Double euros; @Deprecated @Column(name = "idAntigua") private Integer idAntigua; @Column(name = "concepto", length = 140) private String concepto; public Set<PSD> getPSDs() { return pSDs; } public void setPSDs(Set<PSD> pSDs) { this.pSDs = pSDs; } public Secuenciaadeudo getSecuenciaAdeudo() { return secuenciaAdeudo; } public void setSecuenciaAdeudo(Secuenciaadeudo secuenciaAdeudo) { this.secuenciaAdeudo = secuenciaAdeudo; } public Persona getPersona() { return persona; } public void setPersona(Persona persona) { this.persona = persona; } public Date getFechaInicio() { return fechaInicio; } public void setFechaInicio(Date fechaInicio) { this.fechaInicio = fechaInicio; } public Date getFechaBaja() { return fechaBaja; } public void setFechaBaja(Date fechaBaja) { this.fechaBaja = fechaBaja; } @Deprecated public String getPago() { return pago; } @Deprecated public void setPago(String pago) { this.pago = pago; } @Deprecated public Double getPesetas() { return pesetas; } @Deprecated public void setPesetas(Double pesetas) { this.pesetas = pesetas; } public String getDivisa() { return divisa; } public void setDivisa(String divisa) { this.divisa = divisa; } public String getPeriodo() { return periodo; } public void setPeriodo(String periodo) { this.periodo = periodo; } @Deprecated public String getDevolucion() { return devolucion; } @Deprecated public void setDevolucion(String devolucion) { this.devolucion = devolucion; } public Boolean getActivo() { return activo; } public void setActivo(Boolean activo) { this.activo = activo; } @Deprecated public Date getUltimaEmision() { return ultimaEmision; } @Deprecated public void setUltimaEmision(Date ultimaEmision) { this.ultimaEmision = ultimaEmision; } @Deprecated public Integer getIdTitular() { return idTitular; } @Deprecated public void setIdTitular(Integer idTitular) { this.idTitular = idTitular; } public Double getEuros() { return euros; } public void setEuros(Double euros) { this.euros = euros; } @Deprecated public Integer getIdAntigua() { return idAntigua; } @Deprecated public void setIdAntigua(Integer idAntigua) { this.idAntigua = idAntigua; } public String getConcepto() { return concepto; } public void setConcepto(String concepto) { this.concepto = concepto; } public String toString() { return new ReflectionToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).setExcludeFieldNames("pSDs", "secuenciaAdeudo", "persona").toString(); } /** * Call only if PSD is initialized * @return */ @JsonIgnore public PSD getActivePSD() { PSD active = null; if (this.pSDs != null) { for (PSD psd : pSDs) { if (psd.getFechaBaja() == null) { active = psd; } } } return active; } public PSD getLastPSD() { PSD last = null; if (this.pSDs != null) { // pSDs.stream().map(psd -> psd.getFechaInicio()).max(Date::compareTo).get(); for (PSD psd : pSDs) { if (last == null || psd.getFechaInicio().compareTo(last.getFechaInicio()) >0 ) { last = psd; } } } return last; } }
35cd55bca5846956895cd074fc12d5f540e274af
c7b8f6610556dc0eef2988a998d7be4cb274d452
/app/src/main/java/ca/micand/w2a/W2A.java
73c7e14190ef5dd32be0db783070442dde98bfa2
[]
no_license
peevees/Animatepicture
22097ab204dcf3472218b0b9d873654bfe62200b
43391dec221d08c9cd7e06069b41a3edd2d60ed5
refs/heads/master
2021-03-19T14:23:24.254305
2017-06-01T10:37:32
2017-06-01T10:37:32
93,046,478
0
0
null
null
null
null
UTF-8
Java
false
false
1,070
java
package ca.micand.w2a; import android.app.Activity; import android.graphics.drawable.AnimationDrawable; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class W2A extends Activity { AnimationDrawable androidAnimation; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ImageView androidImage = (ImageView) findViewById(R.id.android); androidImage.setBackgroundResource(R.drawable.android_animate); androidAnimation = (AnimationDrawable) androidImage.getBackground(); final Button btnAnimate = (Button) findViewById(R.id.animate); View.OnClickListener ocl; ocl = new View.OnClickListener() { @Override public void onClick(View v) { androidAnimation.stop(); androidAnimation.start(); } }; btnAnimate.setOnClickListener(ocl); } }
a00971572178b55ae103003103529e006e37883e
4bf0c650b989fab1e2048ffb4d276ffa300032de
/src/_26/spring/aop/afterThrowing/ProductRepository.java
21aa156e0c4f0417945b0dd9d27ed8cb49be45e7
[]
no_license
berberoglucan/spring-core
c611a62248032f24eff017a0a11a8b27684ec8b3
cbcf90c93c333c392cac9c0b3446445bfa445bd7
refs/heads/master
2020-03-20T22:41:01.496756
2018-06-19T15:35:36
2018-06-19T15:35:36
137,810,322
0
0
null
null
null
null
UTF-8
Java
false
false
762
java
package _26.spring.aop.afterThrowing; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Component; @Component public class ProductRepository { private List<Product> products = new ArrayList<>(); public void saveProduct(Product product) { System.out.println("Urun eklendi"); this.products.add(product); } public void removeProduct(Product product) { System.out.println("Urun silindi"); this.products.remove(product); } public Product findProduct(int index) { if(index < 0) throw new IllegalArgumentException("Gecersiz index degeri : " + index); return this.products.get(index); } public void getProducts() { this.products.forEach(System.out::println); } }
361964703c434099af1ce0e7159b13ef8231ebfa
5f4927cb47ef2031876a0969dc34d20816c9b8ec
/hilos/Hilos/src/com/abi/ContadorRunnable.java
a5aa7286e0aa4d938dae9cc38464578daf6991f7
[]
no_license
desabi/java-se
f5e072966c3db59c103668709290dbd5107411d7
d8a8a2c90806981c9c6b2689bfbdc6d0b548c5c9
refs/heads/master
2022-12-04T12:01:39.160640
2020-08-20T15:45:20
2020-08-20T15:45:20
289,031,997
0
0
null
null
null
null
UTF-8
Java
false
false
781
java
package com.abi; import javax.swing.JLabel; import javax.swing.JOptionPane; public class ContadorRunnable implements Runnable{ private final Thread hilo; private final JLabel labelContador; public ContadorRunnable(JLabel labelContador){ this.labelContador = labelContador; hilo = new Thread(this, "HiloRunnable"); iniciar(); } @Override public void run(){ try { for (int i = 0; i < 10; i++) { labelContador.setText(""+i); Thread.sleep(1000); } } catch (InterruptedException e) { JOptionPane.showMessageDialog(null, e); } } private void iniciar(){ hilo.start(); } }
bc400dc9e70251770122ed88d3dc3ed7057bfe25
6afdb0763cd4ceb4c7698f29941980fba61609a0
/src/uk/ac/manchester/cs/owl/semspreadsheets/ui/action/SheetCellCopyAction.java
3ece58c92eb3309de62afa8eacaa792c8bd32764
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
madanska/RightField
3855be76985fe78ac28b0212333d4b2fd921ac33
328f9360da86bd3c21cd88a26f2695bbbaa2430f
refs/heads/master
2021-05-27T19:14:46.777896
2010-12-09T21:33:11
2010-12-09T21:33:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,257
java
package uk.ac.manchester.cs.owl.semspreadsheets.ui.action; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Collection; import javax.swing.JOptionPane; import org.apache.log4j.Logger; import uk.ac.manchester.cs.owl.semspreadsheets.model.Cell; import uk.ac.manchester.cs.owl.semspreadsheets.model.OntologyTermValidation; import uk.ac.manchester.cs.owl.semspreadsheets.model.Range; import uk.ac.manchester.cs.owl.semspreadsheets.model.WorkbookManager; /** * Action to handle 'copying' a cell from a sheet * * @author Stuart Owen * */ @SuppressWarnings("serial") public class SheetCellCopyAction extends SelectedCellsAction { protected int MAX_CELLS=500; private static Logger logger = Logger.getLogger(SheetCellCopyAction.class); private final Toolkit toolkit; public SheetCellCopyAction(WorkbookManager workbookManager, Toolkit toolkit) { this("Copy", workbookManager, toolkit); setAcceleratorKey(KeyEvent.VK_C); } protected SheetCellCopyAction(String name, WorkbookManager workbookManager, Toolkit toolkit) { super(name, workbookManager); this.toolkit = toolkit; } @Override public void actionPerformed(ActionEvent e) { logger.debug("Copy action invoked"); Range selectedRange = getSelectedRange(); SelectedCellDataContainerList selectedContents = new SelectedCellDataContainerList(); if (selectedRange.isCellSelection()) { if (selectedRange.count() <= MAX_CELLS) { for (int col = selectedRange.getFromColumn(); col < selectedRange .getToColumn() + 1; col++) { for (int row = selectedRange.getFromRow(); row < selectedRange .getToRow() + 1; row++) { SelectedCellDataContainer cellContent = new SelectedCellDataContainer(); cellContent.row = row - selectedRange.getFromRow(); cellContent.col = col - selectedRange.getFromColumn(); Range singleCellRange = new Range( selectedRange.getSheet(), col, row, col, row); Collection<OntologyTermValidation> containingValidations = getWorkbookManager() .getOntologyTermValidationManager() .getContainingValidations(singleCellRange); if (containingValidations.size() > 0) { cellContent.validationDescriptor = containingValidations .iterator().next() .getValidationDescriptor(); } Cell cell = selectedRange.getSheet() .getCellAt(col, row); if (cell != null) { cellContent.textValue = cell.getValue(); } else { logger.debug("Selected cell is returned as NULL"); // we assume that we are copying an empty value, // rather // than // leaving the clipboard intact cellContent.textValue = ""; } selectedContents.add(cellContent); } } Transferable tr = new CellContentsTransferable(selectedContents); Clipboard clippy = toolkit.getSystemClipboard(); clippy.setContents(tr, null); } else { JOptionPane.showMessageDialog(null, "A maximum of "+MAX_CELLS+" cells can be placed on the clipboard.","Too many cells",JOptionPane.WARNING_MESSAGE); } } else { logger.info("Nothing selected"); } } }
6de6710edc665fc2d5f68ffac1d92ac8be604f59
e94795dcb2a92cd9369c6e96c062aa525a135724
/Hito 2/src/Voraz/Principal.java
a76327ee7ee54125ed2099c970bf9643130ea371
[]
no_license
lauritajavega99/Metodologia19-20
ccc0759ad90be57de7ecb97d954d2ba8ded2362a
ec549a073bbc79feb5037356d0226a5e84ef4686
refs/heads/main
2023-02-05T03:37:58.382530
2020-12-21T21:39:03
2020-12-21T21:39:03
308,265,556
0
0
null
null
null
null
ISO-8859-1
Java
false
false
8,345
java
/* * Nombre clase: Principal * Paquetes usados: java.io.IOException, java.util.Arrays, java.util.InputMismatchException, java.util.List, java.util.Scanner, java.util.Comparator,java.util.Collections,java.util.ArrayList; * Métodos contenidos: main, Menu, VorazBecaCorta, VorazBecaMasPagada, becasSeleccionadas, Correcta, Becastotales, calcularBeneficio, ImprimirBecasSelec, ImprimirBecasFichero * Realizado por: Luis Patiño Camacho y Laura Muñoz Jávega * Fecha: Abril 2020 * Escuela Superior de Informática UCLM */ package Voraz; import java.io.IOException; import java.util.Scanner; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.InputMismatchException; import java.util.List; public class Principal { // método main public static void main(String[] args) throws IOException { Beca[] becas = Becastotales(); Menu(becas); } // Este método crea con un switch case un método menú, para que podamos // interaccionar con el usuario y elija la opción que desee. public static void Menu(Beca[] becas) throws IOException { int eleccion; Scanner teclado = new Scanner(System.in); boolean salir = false; do { try { // Visualización de las opciones para el usuario. System.out.println("\nPRÁCTICA 3: El cazador de becas"); System.out.println("*******************************"); System.out.println("Introduzca el valor correspondiente a la heurística voraz que desea probar:" + "\n 1. Mayor sueldo con las becas más cortas." + "\n 2. Mayor sueldo con las becas que paguen más al mes." + "\n 0. Salir."); eleccion = teclado.nextInt(); // switch case con las distintas opciones de nuestro menu. switch (eleccion) { // Opción para salir del bucle del menu. case 0: salir = true; System.out.println("Saliendo..."); break; // Opcion que llamara a distintos métodos para mostrar el mayor sueldo en // función de las becas más cortas. case 1: ImprimirBecasFichero(becas); Beca[] sol1 = VorazBecaCorta(becas); ImprimirBecasSelec(sol1); calcularBeneficio(sol1); break; // Opción que llamara a distintos métodos para mostrar el mayor sueldo en // función de las becas que paguen más al mes. case 2: ImprimirBecasFichero(becas); Beca[] sol2 = VorazBecaMasPagada(becas); ImprimirBecasSelec(sol2); calcularBeneficio(sol2); break; // Opción por si el usuario introduce algún tipo de valor no válido. default: System.out.println("La opción introducida no es válida, vuelva a intentarlo."); break; } } catch (InputMismatchException e) { // Excepción que controla el uso de caracteres no numéricos System.out.println("La opción debe de tener un valor numérico" + ",introduzca la opción de nuevo.\n"); teclado.next(); } } while (salir == false); } /// MÉTODOS PRÁCTICA VORAZ//// // Método que realiza la heurística en función de las becas más cortas. public static Beca[] VorazBecaCorta(Beca[] b) { List<Beca> listaBecas = Arrays.asList(b); // Creamos lista de becas. // Para ordenarlas por tiempo más corto. Collections.sort(listaBecas, new Comparator<Beca>() { public int compare(Beca b1, Beca b2) { return new Integer(b1.tTiempo()).compareTo(new Integer(b2.tTiempo())); } }); // Convertimos el la lista a un Array. Beca[] resultado = new Beca[listaBecas.size()]; listaBecas.toArray(resultado); //Imprimimos el nuevo orden de las Becas System.out.println("\nEl conjunto de becas ordenas de menor a mayor tiempo:"); System.out.println("*****************************************************\n"); ImprimirBecasOrdenadas(resultado); // Pasamos el array para que sean seleccionadas las becas correspondientes a la // heurística. Beca[] seleccionadas = becasSeleccionadas(resultado); return seleccionadas; } // Método que realiza la heurística en función de las becas más pagadas al mes. public static Beca[] VorazBecaMasPagada(Beca[] bec) { List<Beca> listaBecas = Arrays.asList(bec); // Creamos arraylist de becas. // Para ordenarlas por más sueldo al mes. Collections.sort(listaBecas, new Comparator<Beca>() { public int compare(Beca b1, Beca b2) { return new Integer(b2.getSueldo()).compareTo(new Integer(b1.getSueldo())); } }); // Convertimos la lista en array. Beca[] resultado = new Beca[listaBecas.size()]; listaBecas.toArray(resultado); //Imprimimos el nuevo orden de las Becas System.out.println("\nEl conjunto de becas ordenas de mayor a menor pagada al mes es:"); System.out.println("***************************************************************\n"); ImprimirBecasOrdenadas(resultado); // Pasamos el array para que sean seleccionadas las becas correspondientes a la // heurística. Beca[] seleccionadas = becasSeleccionadas(resultado); return seleccionadas; } // Selección de becas para la solución. public static Beca[] becasSeleccionadas(Beca[] lisBecas) { List<Beca> list = new ArrayList<Beca>(); int posSol = 0; list.add(0, lisBecas[0]); // Recorre el array de todas las becas for (int i = 1; i < lisBecas.length; i++) { if (Correcta(list, lisBecas[i])) {// Comprobar que no solapen la una con la otra y si no solapan añadirla a // la lista nueva. posSol++; list.add(posSol, lisBecas[i]); } } // Convertimos la lista en array. Beca[] becasSeleccionadas = new Beca[list.size()]; list.toArray(becasSeleccionadas); return becasSeleccionadas; } // Comprobación para que no solapen fechas una vez ordenadas. public static boolean Correcta(List<Beca> l, Beca be) { boolean siCorrecta = false; boolean aux = true; // Recorremos la lista con los elementos que han sido seleccionados // Comparando las fechas de sus elementos con la fecha de la beca candidata al // conjunto. for (int i = 0; i < l.size() && aux == true; i++) { // Comparación de los distintos extremos y posibilidades de solapación de // fechas. if ((be.getFinicio() < l.get(i).getFinicio() && be.getFfin() < l.get(i).getFinicio())) { siCorrecta = true; } else if (be.getFinicio() > l.get(i).getFfin() && siCorrecta == false) { siCorrecta = true; } else if (be.getFinicio() > l.get(i).getFfin() && siCorrecta == true) { siCorrecta = true; } else { siCorrecta = false; aux = false; } } return siCorrecta; } // Pasamos las becas del fichero a un array public static Beca[] Becastotales() throws IOException { Beca[] listaBecas = LecturaFicheros.datosBecas("src\\DatosBecas6.txt"); // "src\\DatosBecas8.txt" o // "src\\DatosBecas6.txt" return listaBecas; } // Calcular el sueldo total de las becas que han sido seleccionadas como // solución public static void calcularBeneficio(Beca[] becas) { int s = 0; for (int i = 0; i < becas.length; i++) { s = s + becas[i].tSueldo(); // Recorre el array de las becas seleccionadas y suma el beneficio total de cada // una de ellas. } System.out.println("El beneficio total obtenido es de --> " + s + " euros.\n"); } // Imprime la solución de becas con la heurística seleccionada. public static void ImprimirBecasSelec(Beca[] listaBecas) { System.out.println("La solución con la heurística elegida es:"); System.out.println("*****************************************\n"); for (int i = 0; i < listaBecas.length; i++) { System.out.println(listaBecas[i]); } } // Imprime las becas contenidas en el fichero txt. public static void ImprimirBecasFichero(Beca[] lb) throws IOException { System.out.println("\nEl conjunto de becas a contemplar son:"); System.out.println("**************************************\n"); for (int i = 0; i < lb.length; i++) { System.out.println(lb[i]); } } //Imprime las becas ordenadas public static void ImprimirBecasOrdenadas(Beca[] ord) { for (int i = 0; i < ord.length; i++) { System.out.println(ord[i]); } } }
4076b6d3346ed2676b42140dfcc8aa8c15f3c844
1cd4f560c5ce87488c93c76112d9893e932ea136
/src/p1/ListenerTest.java
c3492fcb5a49ab765527efc60da57a6881e310d6
[]
no_license
Atai-Isaev/LambdaLearning
9d5fb8632b84709d3bec645a0a94ad7938c2a431
df15db0e8c836f1cfd24207f3a69773e1bfcffde
refs/heads/master
2023-04-22T11:41:44.364940
2021-05-05T21:02:26
2021-05-05T21:02:26
364,688,122
0
0
null
null
null
null
UTF-8
Java
false
false
830
java
package p1; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class ListenerTest { public static void main(String[] args) { JButton testButton = new JButton("Test Button"); testButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae){ System.out.println("Click Detected by Anon Class"); } }); testButton.addActionListener(e -> System.out.println("Click Detected by Lambda Listner")); // Swing stuff JFrame frame = new JFrame("Listener Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(testButton, BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } }
962fc7ee6ca3d518e0d73c4ee2276a6b32680c89
e904752834df4f17ead40fadd234f4a512048a32
/Hello.java
9272d15353b2ddea11ae554200565f695d302f17
[]
no_license
kommanab/practice
23d43966c553ec0550a62b0a103de6dbd95a5175
b9aedf3cfef260e092bb9bc0d881ffb4a95f52e0
refs/heads/master
2020-08-22T05:59:23.345768
2019-10-20T08:51:50
2019-10-20T08:51:50
216,332,568
0
0
null
null
null
null
UTF-8
Java
false
false
132
java
class Hello { public static void main(String args []) { System.out.println("hello i am your lLove Bharath"); } }
3b20026c46baedd9a917e97acc1d2f9a01480b2b
fc81765970557b0b686971580098d1001e46bf08
/src/main/java/hello/hellospring/service/MemberService.java
be682fc0c56216b387c4712f8f0ba0db601bbc0d
[]
no_license
yoonho0922/hello-springboot
dadc946b43905b1de8639c985be42e866335d97b
d3e19e7ddb537946276ecf4dc93280be53cc5568
refs/heads/master
2023-08-21T10:35:50.749245
2021-10-24T15:24:16
2021-10-24T15:24:16
411,260,418
0
0
null
null
null
null
UTF-8
Java
false
false
1,320
java
package hello.hellospring.service; import hello.hellospring.domain.Member; import hello.hellospring.repository.MemberRepository; import hello.hellospring.repository.MemoryMemberRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; //@Service @Transactional public class MemberService { private final MemberRepository memberRepository; // @Autowired public MemberService(MemberRepository memberRepository) { this.memberRepository = memberRepository; } public Long join(Member member) { // 이름 중복 검사 validateDuplicateMember(member); memberRepository.save(member); return member.getId(); } private void validateDuplicateMember(Member member) { memberRepository.findByName(member.getName()) .ifPresent(m -> { throw new IllegalStateException("이미 존재하는 회원입니다."); }); } public List<Member> findMembers(){ return memberRepository.findAll(); } public Optional<Member> findOne(Long memberId) { return memberRepository.findById(memberId); } }
12b43c3289ea9677f5c549ea661c40237eeabc92
fe2836176ca940977734312801f647c12e32a297
/Google/CodeJam/2016/Preliminary Round/C. Coin Jam/Main.java
d088b71ae8c2219cfc58642c5978aa02d7dab6dd
[]
no_license
henrybear327/Sandbox
ef26d96bc5cbcdc1ce04bf507e19212ca3ceb064
d77627dd713035ab89c755a515da95ecb1b1121b
refs/heads/master
2022-12-25T16:11:03.363028
2022-12-10T21:08:41
2022-12-10T21:08:41
53,817,848
2
0
null
null
null
null
UTF-8
Java
false
false
3,282
java
import java.io.*; import java.math.BigInteger; import java.util.*; public class Main { public static void main(String[] args) { MyScanner sc = new MyScanner(); out = new PrintWriter(new BufferedOutputStream(System.out)); int ncase = sc.nextInt(), n = sc.nextInt(), target = sc.nextInt(); int cnt_ans = 0; StringBuilder st = new StringBuilder(); //for(long i = 32947/*((1L << (n - 1)) + 1)*/; i < 32950/*(1L << n)*/; i+=2L) { for(long i = ((1L << (n - 1)) + 1); i < (1L << n); i+=2L) { //System.out.println("i: " + i); boolean ok = true; StringBuilder tmp = new StringBuilder(); tmp.append(Long.toBinaryString(i)); String binary_string = Long.toBinaryString(i); //out.println("i: " + i + " " + binary_string); for(int j = 2; j <= 10; j++) { BigInteger cur = new BigInteger(binary_string, j); //out.println("j: " + j + " " + cur); if(cur.isProbablePrime(10) == false) { //System.out.println(cur); boolean in_loop = false; for(long k = 2; k < 100000; k++) { if(cur.mod(BigInteger.valueOf((int)k)) == BigInteger.ZERO) { if(k >= 100000) System.out.println(cur + " " + k); in_loop = true; tmp.append(" ").append(k); // System.out.println(tmp); break; } } if(in_loop == false) { ok = false; break; } } else { ok = false; break; } } if(ok == true) { st.append(tmp).append("\n"); //out.println(tmp); cnt_ans++; if(cnt_ans >= target) break; } } out.println("Case #1:"); out.print(st); out.close(); } // PrintWriter for faster output public static PrintWriter out; // MyScanner class for faster input public static class MyScanner { BufferedReader br; StringTokenizer st; public MyScanner() { br = new BufferedReader(new InputStreamReader(System.in)); } boolean hasNext() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (Exception e) { return false; } } return true; } String next() { if (hasNext()) return st.nextToken(); return null; } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { str = br.readLine(); } catch (IOException e) { e.printStackTrace(); } return str; } } }
49fc52bbd6eb287851eb81ec664621dc9e09bf61
cec4cc1535905c4b6cd6ca7b12706099360031cf
/demo2-common/src/main/java/cn/demo2/common/util/CookieUtils.java
e8c3255f60ac3e37356b73f114f0e46ed4c5db0a
[]
no_license
Hupeng7/demo2-parent
8996fc7b13aea66b485789f4f5eff87a532e7a7d
563b22bd132f5dc880395401422d60ef845930fa
refs/heads/master
2021-01-01T19:36:28.185517
2017-08-02T12:25:41
2017-08-02T12:25:41
98,622,885
0
0
null
null
null
null
UTF-8
Java
false
false
7,739
java
package cn.demo2.common.util; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * Cookie 工具类 * */ public final class CookieUtils { protected static final Logger logger = LoggerFactory.getLogger(CookieUtils.class); /** * 得到Cookie的值, 不编码 * * @param request * @param cookieName * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName) { return getCookieValue(request, cookieName, false); } /** * 得到Cookie的值, * * @param request * @param cookieName * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) { Cookie[] cookieList = request.getCookies(); if (cookieList == null || cookieName == null) { return null; } String retValue = null; try { for (int i = 0; i < cookieList.length; i++) { if (cookieList[i].getName().equals(cookieName)) { if (isDecoder) { retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8"); } else { retValue = cookieList[i].getValue(); } break; } } } catch (UnsupportedEncodingException e) { logger.error("Cookie Decode Error.", e); } return retValue; } /** * 得到Cookie的值, * * @param request * @param cookieName * @return */ public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) { Cookie[] cookieList = request.getCookies(); if (cookieList == null || cookieName == null) { return null; } String retValue = null; try { for (int i = 0; i < cookieList.length; i++) { if (cookieList[i].getName().equals(cookieName)) { retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString); break; } } } catch (UnsupportedEncodingException e) { logger.error("Cookie Decode Error.", e); } return retValue; } /** * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue) { setCookie(request, response, cookieName, cookieValue, -1); } /** * 设置Cookie的值 在指定时间内生效,但不编码 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage) { setCookie(request, response, cookieName, cookieValue, cookieMaxage, false); } /** * 设置Cookie的值 不设置生效时间,但编码 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, boolean isEncode) { setCookie(request, response, cookieName, cookieValue, -1, isEncode); } /** * 设置Cookie的值 在指定时间内生效, 编码参数 */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) { doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode); } /** * 设置Cookie的值 在指定时间内生效, 编码参数(指定编码) */ public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) { doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString); } /** * 删除Cookie带cookie域名 */ public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) { doSetCookie(request, response, cookieName, "", -1, false); } /** * 设置Cookie的值,并使其在指定时间内生效 * * @param cookieMaxage cookie生效的最大秒数 */ private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) { try { if (cookieValue == null) { cookieValue = ""; } else if (isEncode) { cookieValue = URLEncoder.encode(cookieValue, "utf-8"); } Cookie cookie = new Cookie(cookieName, cookieValue); if (cookieMaxage > 0) cookie.setMaxAge(cookieMaxage); if (null != request)// 设置域名的cookie //cookie.setDomain(getDomainName(request)); 引发无法设置cookie cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { logger.error("Cookie Encode Error.", e); } } /** * 设置Cookie的值,并使其在指定时间内生效 * * @param cookieMaxage cookie生效的最大秒数 */ private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) { try { if (cookieValue == null) { cookieValue = ""; } else { cookieValue = URLEncoder.encode(cookieValue, encodeString); } Cookie cookie = new Cookie(cookieName, cookieValue); if (cookieMaxage > 0) cookie.setMaxAge(cookieMaxage); if (null != request)// 设置域名的cookie cookie.setDomain(getDomainName(request)); cookie.setPath("/"); response.addCookie(cookie); } catch (Exception e) { logger.error("Cookie Encode Error.", e); } } /** * 得到cookie的域名 */ private static final String getDomainName(HttpServletRequest request) { String domainName = null; String serverName = request.getRequestURL().toString(); if (serverName == null || serverName.equals("")) { domainName = ""; } else { serverName = serverName.toLowerCase(); serverName = serverName.substring(7); final int end = serverName.indexOf("/"); serverName = serverName.substring(0, end); final String[] domains = serverName.split("\\."); int len = domains.length; if (len > 3) { // www.xxx.com.cn domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1]; } else if (len <= 3 && len > 1) { // xxx.com or xxx.cn domainName = "." + domains[len - 2] + "." + domains[len - 1]; } else { domainName = serverName; } } if (domainName != null && domainName.indexOf(":") > 0) { String[] ary = domainName.split("\\:"); domainName = ary[0]; } return domainName; } }
583d0377aa6fa6928faf5e97a2d7dc4084f758f0
c3c9ec94dc586e43098c2f3c49004f1b98b9dc67
/src/main/java/com/lt/css/shiftShp/component/viewCmp/EmpTabel.java
15346e96fa3451289a44c1201e18db1ef107225b
[]
no_license
MicrophoneBen/vaadin-shift-shop
3e22d05566c8172d498fe1dd0a389a3c1698d635
5ae28d46996cd7b06598e8831538b0ef5188bcf3
refs/heads/master
2020-04-21T20:52:00.010746
2019-02-09T11:22:56
2019-02-09T11:22:56
169,859,443
0
0
null
null
null
null
UTF-8
Java
false
false
12,663
java
package com.lt.css.shiftShp.component.viewCmp; import com.lt.css.shiftShp.component.AbstractEmpTable; import com.lt.css.shiftShp.entity.EmployeeDto; import com.vaadin.data.provider.ListDataProvider; import com.vaadin.ui.Grid; import org.springframework.stereotype.Component; import java.time.LocalDate; import java.time.temporal.TemporalAdjusters; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * @program: EmpTabel * @description: 一个部门的所有员工数据载入的表格 * @author: ben.zhang.b.q * @create: 2019-01-25 19:12 **/ @Component public class EmpTabel extends AbstractEmpTable{ private List<EmployeeDto> fromlist = new ArrayList<>(1); private List<EmployeeDto> tolist = new ArrayList<>(1); public ListDataProvider<EmployeeDto> fromProvider; public ListDataProvider<EmployeeDto> toProvider; public EmpTabel(){ setEmployee(true, getFromShiftShp(), fromlist); setEmployee(true, getToShiftShp(), tolist); } /** * @author ben.zhang.b.q * @date 2019/1/25 20:33 * 返回要调出员工部门的员工List集合 * @return java.util.List<com.lt.css.shiftShp.entity.EmployeeDto> **/ public List<EmployeeDto> getFromlist() { return fromlist; } /** * @author ben.zhang.b.q * @date 2019/1/25 20:35 * 设置要调出员工部门的远员工List集合 * @return void **/ public void setFromlist(List<EmployeeDto> fromlist) { this.fromlist = fromlist; } /** * @author ben.zhang.b.q * @date 2019/1/25 20:36 * 返回要调往部门的员工集合 * @return java.util.List<com.lt.css.shiftShp.entity.EmployeeDto> **/ public List<EmployeeDto> getTolist() { return tolist; } /** * @author ben.zhang.b.q * @date 2019/1/25 20:37 * 设置要调往部门的员工List集合 * @return void **/ public void setTolist(List<EmployeeDto> tolist) { this.tolist = tolist; } /** * 初始Grid * @param b true代表當月,false代表下一月 * @param grid * @param list */ public void setEmployee(boolean b, Grid<EmployeeDto> grid, List<EmployeeDto> list) { grid.removeAllColumns(); grid.setItems(list); grid.addColumn(EmployeeDto::getName).setCaption("名稱"); grid.setFrozenColumnCount(1); grid.addColumn(EmployeeDto::getTitle).setCaption("職稱"); grid.setSelectionMode(Grid.SelectionMode.MULTI); grid.setFrozenColumnCount(1); Map<String, String> map = getDays(b); for (Map.Entry<String, String> entry : map.entrySet()) { switch (entry.getKey()) { case "1": grid.addColumn(EmployeeDto::getDay1WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay1Backgroud(); }); break; case "2": grid.addColumn(EmployeeDto::getDay2WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay2Backgroud(); }); break; case "3": grid.addColumn(EmployeeDto::getDay3WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay3Backgroud(); }); break; case "4": grid.addColumn(EmployeeDto::getDay4WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay4Backgroud(); }); break; case "5": grid.addColumn(EmployeeDto::getDay5WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay5Backgroud(); }); break; case "6": grid.addColumn(EmployeeDto::getDay6WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay6Backgroud(); }); break; case "7": grid.addColumn(EmployeeDto::getDay7WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay7Backgroud(); }); break; case "8": grid.addColumn(EmployeeDto::getDay8WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay8Backgroud(); }); break; case "9": grid.addColumn(EmployeeDto::getDay9WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay9Backgroud(); }); break; case "10": grid.addColumn(EmployeeDto::getDay10WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay10Backgroud(); }); break; case "11": grid.addColumn(EmployeeDto::getDay11WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay11Backgroud(); }); break; case "12": grid.addColumn(EmployeeDto::getDay12WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay12Backgroud(); }); break; case "13": grid.addColumn(EmployeeDto::getDay13WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay13Backgroud(); }); break; case "14": grid.addColumn(EmployeeDto::getDay14WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay14Backgroud(); }); break; case "15": grid.addColumn(EmployeeDto::getDay15WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay15Backgroud(); }); break; case "16": grid.addColumn(EmployeeDto::getDay16WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay16Backgroud(); }); break; case "17": grid.addColumn(EmployeeDto::getDay17WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay17Backgroud(); }); break; case "18": grid.addColumn(EmployeeDto::getDay18WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay18Backgroud(); }); break; case "19": grid.addColumn(EmployeeDto::getDay19WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay19Backgroud(); }); break; case "20": grid.addColumn(EmployeeDto::getDay20WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay20Backgroud(); }); break; case "21": grid.addColumn(EmployeeDto::getDay21WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay21Backgroud(); }); break; case "22": grid.addColumn(EmployeeDto::getDay22WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay22Backgroud(); }); break; case "23": grid.addColumn(EmployeeDto::getDay23WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay23Backgroud(); }); break; case "24": grid.addColumn(EmployeeDto::getDay24WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay24Backgroud(); }); break; case "25": grid.addColumn(EmployeeDto::getDay25WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay25Backgroud(); }); break; case "26": grid.addColumn(EmployeeDto::getDay26WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay26Backgroud(); }); break; case "27": grid.addColumn(EmployeeDto::getDay27WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay27Backgroud(); }); break; case "28": grid.addColumn(EmployeeDto::getDay28WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay28Backgroud(); }); break; case "29": grid.addColumn(EmployeeDto::getDay29WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay29Backgroud(); }); break; case "30": grid.addColumn(EmployeeDto::getDay30WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay30Backgroud(); }); break; case "31": grid.addColumn(EmployeeDto::getDay31WorkLength).setCaption(entry.getValue()).setStyleGenerator(item -> { return "v-grid-cell-bgcolor-"+item.getDay31Backgroud(); }); break; default: break; } } } /** * 獲取一月日期 * @return */ public Map<String, String> getDays(boolean b){ Map<String, String> map = new LinkedHashMap<>(); LocalDate today; //当前日期 if(b) { today = LocalDate.now(); }else { today = LocalDate.now().plusMonths(1); } //本月的最后一天 int monthEnd = today.with(TemporalAdjusters.lastDayOfMonth()).getDayOfMonth(); String[][] strArray = {{"1", "一"}, {"2", "二"}, {"3", "三"}, {"4", "四"}, {"5", "五"}, {"6", "六"}, {"7", "日"}}; for (int i = 1; i <= monthEnd; i++) { LocalDate date = LocalDate.of(today.getYear(), today.getMonth(), i); String k = String.valueOf(date.getDayOfWeek().getValue()); for (String[] aStrArray : strArray) { if (k.equals(aStrArray[0])) { k = aStrArray[1]; break; } } map.put(String.valueOf(i), i+"("+"周"+k+")"); } return map; } }
e08c421f2f99ec5da67b2a93c7c328173a9e2752
df241ceeb274ecfb21cf0bbac539296921b4d576
/core/src/main/java/istory/NumberDiff.java
457249efff161ca567f2cb1f84458bff7c85c225
[]
no_license
cchantep/istory
5ebbebb00b2398e8353dbf7d4f74116a6e32fd0c
dc15ff34dc72d71e26f896274d8cb4bb4f4901b4
refs/heads/master
2021-01-22T21:13:27.900937
2021-01-05T09:41:55
2021-01-05T09:41:55
10,270,016
0
0
null
2021-01-05T09:41:18
2013-05-24T16:02:17
Java
UTF-8
Java
false
false
1,116
java
package istory; import java.io.Serializable; /** * Diff for integer. * * @author Cedric Chantepie */ public class NumberDiff<N extends Number> implements Diff<N>, Serializable { // --- Properties --- /** * Old value */ private final N oldValue; /** * New value */ private final N newValue; // --- Constructors --- /** * Bulk constructor. * * @param oldValue * @param newValue */ public NumberDiff(final N oldValue, final N newValue) { this.oldValue = oldValue; this.newValue = newValue; } // end of if // --- /** * {@inheritDoc} */ public <V extends N> N patch(final V orig) throws DiffException { if (!oldValue.equals(orig)) { throw new DiffException(); } // end of if return this.newValue; } // end of catch /** * {@inheritDoc} */ public <V extends N> N revert(final V dest) throws DiffException { if (!dest.equals(newValue)) { throw new DiffException(); } // end of if return this.oldValue; } // end of revert } // end of class NumberDiff
378f4554f7eaa439dc2fccd04e29cc7e6b265144
2f8bea09ee50d9811064ef71183faadb175bc954
/app/src/main/java/com/enfin/ofabee3/ui/module/userprofile/UserProfileFragment.java
56d783025d25df6ded37d5703de9806004b783cf
[]
no_license
vishnuaruvikkarakkaran/ofbnewApp3.0
c44a2a7bad28f7119e0a5b3320fe3e8bd92edf42
a0f67b67b04a93742aad65df032605642bf5f977
refs/heads/master
2020-09-21T04:05:25.374191
2019-11-28T14:50:15
2019-11-28T14:50:15
224,672,893
0
0
null
null
null
null
UTF-8
Java
false
false
13,590
java
package com.enfin.ofabee3.ui.module.userprofile; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.ShareCompat; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.CircularProgressDrawable; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.enfin.ofabee3.BuildConfig; import com.enfin.ofabee3.R; import com.enfin.ofabee3.data.remote.model.Response.LoginResponseModel; import com.enfin.ofabee3.data.remote.model.editprofile.response.MyProfileResponse; import com.enfin.ofabee3.data.remote.model.logout.response.LogoutBean; import com.enfin.ofabee3.ui.base.BaseFragment; import com.enfin.ofabee3.ui.module.coursecategories.MyCourseCategoryListActivity; import com.enfin.ofabee3.ui.module.explore.ExploreFragment; import com.enfin.ofabee3.ui.module.home.HomeActivity; import com.enfin.ofabee3.ui.module.inactiveuser.InActiveUserActivity; import com.enfin.ofabee3.ui.module.login.LoginActivity; import com.enfin.ofabee3.ui.module.nointernet.NoInternetActivity; import com.enfin.ofabee3.utils.AppUtils; import com.enfin.ofabee3.utils.Constants; import com.enfin.ofabee3.utils.FragmentActionListener; import com.enfin.ofabee3.utils.OBLogger; import com.enfin.ofabee3.utils.OpenSansTextView; import com.enfin.ofabee3.utils.RecyclerViewItemClickListener; import com.enfin.ofabee3.utils.errorhandler.ServerIsBrokenActivity; import com.pixplicity.easyprefs.library.Prefs; import com.thefinestartist.finestwebview.FinestWebView; import java.util.ArrayList; public class UserProfileFragment extends BaseFragment implements UserProfileContract.View, RecyclerViewItemClickListener { UserProfileContract.Presenter mPresenter; ImageView userAvatar; private TextView userName, userEmail, userContactNumber, rewardValueTV; private LinearLayout rewrardsLL; //private LinearLayout userDetailsLL, settingsLL; private ArrayList<String> settingsList; private RecyclerView settingsRecyclerView; private FragmentActionListener listener; private Dialog progressDialog; private UserSettingsListAdapter settingsListAdapter; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootview = inflater.inflate(R.layout.fragment_profile, null); mPresenter = new UserProfilePresenter(getActivity(), this); progressDialog = AppUtils.showProgressDialog(getActivity()); userAvatar = rootview.findViewById(R.id.profile_image); userName = rootview.findViewById(R.id.user_name); userEmail = rootview.findViewById(R.id.user_email); userContactNumber = rootview.findViewById(R.id.user_phone); rewrardsLL = rootview.findViewById(R.id.ll_rewards); rewardValueTV = rootview.findViewById(R.id.reward_text_value); //userDetailsLL = rootview.findViewById(R.id.user_details_ll); //settingsLL = rootview.findViewById(R.id.settings_ll); settingsRecyclerView = rootview.findViewById(R.id.settings_list_rv); mPresenter.getUserDetails(getActivity()); mPresenter.getProfileDeatails(getActivity()); return rootview; } @Override public void setPresenter(UserProfileContract.Presenter presenter) { this.mPresenter = presenter; } @Override public void setFragmentChangeListener(FragmentActionListener mListener) { super.setFragmentChangeListener(mListener); this.listener = mListener; } @Override public <T> void onSuccess(T type) { if (type instanceof LoginResponseModel.DataBean.UserBean) { updateProfile((LoginResponseModel.DataBean.UserBean) type); } else if (type instanceof LogoutBean) { Toast.makeText(getActivity(), "Logout successfully", Toast.LENGTH_SHORT).show(); mPresenter.clearLocalDB(getActivity()); Intent login = new Intent(getActivity(), LoginActivity.class); login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(login); getActivity().finish(); } else if (type instanceof MyProfileResponse) { if (getActivity() != null) { rewrardsLL.setVisibility(View.VISIBLE); rewardValueTV.setText(((MyProfileResponse) type).getData().getScore()); /*Glide.with(getActivity()) .load(((MyProfileResponse) type).getData().getUs_image()) .centerCrop() .placeholder(R.drawable-mdpi.man) .into(userAvatar);*/ //userName.setText(((MyProfileResponse) type).getData().getUs_name()); //userEmail.setText(((MyProfileResponse) type).getData().getUs_email()); //userContactNumber.setText(((MyProfileResponse) type).getData().getUs_phone()); } } else if (type instanceof String) { if (((String) type).equalsIgnoreCase(Constants.DB_CLEAR)) { Toast.makeText(getActivity(), "Logout successfully", Toast.LENGTH_SHORT).show(); Intent login = new Intent(getActivity(), LoginActivity.class); login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(login); getActivity().finish(); } } } private void updateProfile(LoginResponseModel.DataBean.UserBean user) { CircularProgressDrawable circularProgressDrawable = new CircularProgressDrawable(getActivity()); circularProgressDrawable.setStrokeWidth(5f); circularProgressDrawable.setCenterRadius(30f); circularProgressDrawable.start(); Glide.with(getActivity()) .load(user.getUs_image()) .centerCrop() .placeholder(circularProgressDrawable) .error(circularProgressDrawable) .diskCacheStrategy(DiskCacheStrategy.ALL) .into(userAvatar); userName.setText("Hi " + user.getUs_name() + " !"); userEmail.setText(user.getUs_email()); userContactNumber.setText(user.getUs_phone()); /*Remove this line of code in future while adding data in my account*/ updateLayouts(); } @Override public <T> void onFailure(T type) { } @Override public void onShowProgress() { if (progressDialog != null) { progressDialog.show(); } } @Override public void onHideProgress() { if (progressDialog != null && progressDialog.isShowing()) progressDialog.dismiss(); } @Override public void onShowAlertDialog(String message) { if (message.equalsIgnoreCase("No Internet")) { Intent noInternet = new Intent(getActivity(), NoInternetActivity.class); startActivity(noInternet); } else { onServerError(message); //AppUtils.onShowAlertDialog(getActivity(), message); } } @Override public void onServerError(String message) { Intent errorOccured = new Intent(getActivity(), ServerIsBrokenActivity.class); startActivity(errorOccured); } @Override public void onPrepareOptionsMenu(Menu menu) { MenuItem item = menu.findItem(R.id.search); MenuItem saveItem = menu.findItem(R.id.save); MenuItem settingsItem = menu.findItem(R.id.settings); if (item != null) item.setVisible(false); if (saveItem != null) saveItem.setVisible(false); if (settingsItem != null) settingsItem.setVisible(false); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.settings: updateLayouts(); return true; default: return super.onOptionsItemSelected(item); } } private void updateLayouts() { //rewrardsLL.setVisibility(View.GONE); LinearLayout.LayoutParams paramsUser = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0); LinearLayout.LayoutParams paramsBody = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 0); paramsUser.weight = 0.7f; paramsBody.weight = 1.3f; //userDetailsLL.setLayoutParams(paramsUser); //settingsLL.setLayoutParams(paramsBody); populateSettingsData(); settingsListAdapter = new UserSettingsListAdapter(getActivity(), settingsList); settingsListAdapter.setItemClickListener(this::onItemSelected); settingsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); settingsRecyclerView.setAdapter(settingsListAdapter); } private void populateSettingsData() { settingsList = new ArrayList<>(); settingsList.add("Edit Profile"); settingsList.add("Change Category"); //settingsList.add("Notifications"); //settingsList.add("Support"); settingsList.add("Privacy Policy"); settingsList.add("Terms of Use"); settingsList.add("Invite Friend"); settingsList.add("Sign Out"); } @Override public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); } @Override public void onItemSelected(int position, boolean isSelected) { switch (position) { case 0: editProfile(); break; case 1: changeCategory(); break; case 2: showPrivacyPolicy(); break; case 3: showTermsAndCondition(); break; case 4: shareApp(); break; case 5: signout(); break; } } private void showPrivacyPolicy() { new FinestWebView.Builder(getActivity()).show(BuildConfig.PRIVACY_POLICY_URL); } private void changeCategory() { Intent courseCategory = new Intent(getActivity(), MyCourseCategoryListActivity.class); courseCategory.putExtra(Constants.USER_SOURCE, "PROFILE"); startActivity(courseCategory); //getActivity().finish(); } private void showTermsAndCondition() { new FinestWebView.Builder(getActivity()).show(BuildConfig.TERMS_CONDITION_URL); } @Override public void onStart() { super.onStart(); mPresenter.start(); } @Override public void onResume() { super.onResume(); if (settingsListAdapter != null) settingsListAdapter.setCanStart(true); } @Override public void onStop() { super.onStop(); mPresenter.stop(); onHideProgress(); } private void editProfile() { /*FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.fragmentContainer, new EditProfileFragment()); fragmentTransaction.addToBackStack(Constants.EDIT_PROFILE_FRAGMENT_TAG); fragmentTransaction.commit();*/ listener.onFragmentChanged(Constants.EDIT_PROFILE_FRAGMENT_TITLE); } private void shareApp() { /*Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.putExtra(Intent.EXTRA_TEXT, "Hey check out ofabee app at: https://play.google.com/store/apps/details?id=com.enfin.ofabee3"); shareIntent.setType("text/plain"); startActivity(shareIntent);*/ ShareCompat.IntentBuilder.from(getActivity()) .setType("text/plain") .setChooserTitle("Share App") .setText("http://play.google.com/store/apps/details?id=" + getActivity().getPackageName()) .startChooser(); } private void signout() { Glide.get(getActivity()).clearMemory(); Prefs.clear(); mPresenter.clearLocalDB(getActivity()); //ExploreFragment.re //mPresenter.logout(getActivity()); /*Intent login = new Intent(getActivity(), LoginActivity.class); login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(login); getActivity().finish();*/ } @Override public void logoutAction(String message) { Intent userDeactivated = new Intent(getActivity(), InActiveUserActivity.class); userDeactivated.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(userDeactivated); getActivity().finish(); } }
ac2d9ba50530ec43953173b109a71b5f52ffa825
3101f0e51237a6fb10317438d9323b0500d15791
/src/DateTime/DateTime_30.java
b583becab4bfbe79104e10a99d230dbbaf413c05
[]
no_license
liaoxueqing/preview_work_w3resource_java
a6845a57df7d1c054f41f4dc38237e38837e1737
56b8ab5ff99dc88e190ba149eaa1330db88c9450
refs/heads/master
2020-03-20T14:31:05.684808
2018-06-16T14:26:19
2018-06-16T14:26:19
null
0
0
null
null
null
null
UTF-8
Java
false
false
509
java
package DateTime; import java.time.LocalDate; import java.time.Period; public class DateTime_30 { public static void main(String[] args) { LocalDate currentDate = LocalDate.now(); LocalDate userDate = LocalDate.of(2011,9,6); Period period = Period.between(userDate,currentDate); System.out.println("The difference between "+currentDate+" and "+userDate+" is: " +period.getYears()+" years "+period.getMonths()+" months "+period.getDays()+" days"); } }
8df8307ef632b4eed6eae3a347979f2a0cb1ab56
4b95fe95b182f602a3846c69b85b44e6a289a455
/kodilla-rest-api/src/test/java/com/kodilla/rest/controller/BookControllerTest.java
525fe2c1e30f48b593b1deec79927677d4dac7e9
[]
no_license
patrija/patrycja_derkacz-kodilla_tester
bdc8e86f23fd4b3929a21f324ebf98905afdc71d
b504f866e5c88845bf53ff75d2ce495932c95ad1
refs/heads/master
2020-12-15T00:46:17.467206
2020-05-12T14:20:39
2020-05-12T14:20:39
234,931,995
0
0
null
null
null
null
UTF-8
Java
false
false
1,647
java
package com.kodilla.rest.controller; import com.kodilla.rest.domain.BookDto; import com.kodilla.rest.service.BookService; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.util.ArrayList; import java.util.List; class BookControllerTest { @Test public void shouldFetchBooks() { //given BookService bookServiceMock = Mockito.mock(BookService.class); BookController bookController = new BookController(bookServiceMock); List<BookDto> bookList = new ArrayList<>(); bookList.add(new BookDto("author 1","title 1")); bookList.add(new BookDto("author 2", "title 2")); Mockito.when(bookServiceMock.getBooks()).thenReturn(bookList); //when List<BookDto> result = bookController.getBooks(); //then Assertions.assertEquals(2, bookList.size()); } @Test public void shouldAddBook() { //given BookService bookServiceMock = Mockito.mock(BookService.class); BookController bookController = new BookController(bookServiceMock); List<BookDto> bookList = new ArrayList<>(); BookDto book1 = new BookDto("author 1","title 1"); bookList.add(book1); BookDto book2 = new BookDto("author 2","title 2"); bookList.add(book2) ; Mockito.when(bookServiceMock.getBooks()).thenReturn(bookList); //when bookController.addBook(book1); bookController.addBook(book2); List<BookDto> result = bookController.getBooks(); //then Assertions.assertEquals(2, result.size()); } }
8bca801be4e3111b84e46f96ae6558921f73fbdc
6e5d1286b3472f77f3db33316103ca4902117b4f
/vertx-jooq-async-generate/src/main/java/io/github/jklingsporn/vertx/jooq/async/generate/rx/RXAsyncVertxGuiceGenerator.java
9637abb11b2802a6662dd3ca0aae676d02694877
[ "MIT" ]
permissive
lg906321/vertx-jooq-async
835f6ba56a8b0d05a20e2f1468ad83a1a60306e8
a30544ae28904d2331398a66f5a37fde1d1e9dac
refs/heads/master
2021-06-21T20:20:35.387353
2017-08-22T07:52:40
2017-08-22T07:52:40
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,386
java
package io.github.jklingsporn.vertx.jooq.async.generate.rx; import io.github.jklingsporn.vertx.jooq.async.generate.AbstractVertxGuiceGenerator; import org.jooq.util.JavaWriter; import java.util.List; /** * Created by jensklingsporn on 06.07.17. */ public class RXAsyncVertxGuiceGenerator extends AbstractVertxGuiceGenerator { public RXAsyncVertxGuiceGenerator() { super(RXAsyncVertxGenerator.VERTX_DAO_NAME); } public RXAsyncVertxGuiceGenerator(boolean generateJson, boolean generateGuiceModules, boolean generateInjectConfigurationMethod) { super(RXAsyncVertxGenerator.VERTX_DAO_NAME, generateJson, generateGuiceModules, generateInjectConfigurationMethod); } @Override protected void generateDAOImports(JavaWriter out) { out.println("import rx.Completable;"); out.println("import rx.Observable;"); out.println("import rx.Single;"); out.println("import io.github.jklingsporn.vertx.jooq.async.rx.util.RXTool;"); } @Override protected void generateFetchOneByMethods(JavaWriter out, String pType, String colName, String colClass, String colType, String colIdentifier) { out.tab(1).javadoc("Fetch a unique record that has <code>%s = value</code> asynchronously", colName); out.tab(1).println("public Single<%s> fetchOneBy%sAsync(%s value) {", pType,colClass, colType); out.tab(2).println("return RXTool.executeBlocking(h->h.complete(fetchOneBy%s(value)),vertx());", colClass); out.tab(1).println("}"); } @Override protected void generateFetchByMethods(JavaWriter out, String pType, String colName, String colClass, String colType, String colIdentifier) { out.tab(1).javadoc("Fetch records that have <code>%s IN (values)</code> asynchronously", colName); out.tab(1).println("public Single<List<%s>> fetchBy%sAsync(%s<%s> values) {", pType, colClass, List.class, colType); out.tab(2).println("return fetchAsync(%s,values);", colIdentifier); out.tab(1).println("}"); out.tab(1).javadoc("Fetch records that have <code>%s IN (values)</code> asynchronously", colName); out.tab(1).println("public Observable<%s> fetchBy%sObservable(%s<%s> values) {", pType, colClass, List.class, colType); out.tab(2).println("return fetchObservable(%s,values);", colIdentifier); out.tab(1).println("}"); } @Override protected void generateVertxGetterAndSetterConfigurationMethod(JavaWriter out) { out.println(); out.tab(1).println("private io.vertx.rxjava.core.Vertx vertx;"); out.println(); generateSetVertxAnnotation(out); out.tab(1).println("@Override"); out.tab(1).println("public void setVertx(io.vertx.core.Vertx vertx) {"); out.tab(2).println("this.vertx = new io.vertx.rxjava.core.Vertx(vertx);"); out.tab(1).println("}"); out.println(); out.tab(1).println("@Override"); out.tab(1).println("public void setVertx(io.vertx.rxjava.core.Vertx vertx) {"); out.tab(2).println("this.vertx = vertx;"); out.tab(1).println("}"); out.println(); out.tab(1).println("@Override"); out.tab(1).println("public io.vertx.rxjava.core.Vertx vertx() {"); out.tab(2).println("return this.vertx;"); out.tab(1).println("}"); out.println(); } }
f525738718b0a4cd395502cb47758305d093d40e
292443be311ca4adbe77cce9578be5b4b80c17bb
/inscripciones/src/main/java/ar/gob/cfp/inscripciones/dao/mappers/InscriptoMapper.java
28f0dcd45c40216342c6aa8bdfaebffd02b704f5
[]
no_license
joseyler/cfp
6dbb5be223b70ce43fa1676836256fc0e643df0b
e1dda628205b8aedd235333d7a7879949ded35e2
refs/heads/master
2023-03-13T16:45:45.635064
2020-07-18T00:31:37
2020-07-18T00:31:37
269,771,929
0
1
null
2023-02-22T07:48:49
2020-06-05T20:46:09
Java
UTF-8
Java
false
false
1,592
java
package ar.gob.cfp.inscripciones.dao.mappers; import ar.gob.cfp.commons.model.Inscripto; import ar.gob.cfp.inscripciones.dao.entities.InscriptoEntity; public class InscriptoMapper { public static InscriptoEntity mapEntity(Inscripto ins) { InscriptoEntity ie = new InscriptoEntity(); ie.setId(ins.getId()); ie.setNombre(ins.getNombre()); ie.setApellido(ins.getApellido()); ie.setDni(ins.getDni()); ie.setFecha_nacimiento(ins.getFecha_nacimiento()); ie.setNacionalidad(ins.getNacionalidad()); ie.setPais(ins.getPais()); ie.setProvincia(ins.getProvincia()); ie.setLocalidad(ins.getLocalidad()); ie.setDireccion(ins.getDireccion()); ie.setEmail(ins.getEmail()); ie.setCelular(ins.getCelular()); ie.setMayorEdad(ins.isMayorEdad()); ie.setNivelEducativo(ins.getNivelEducativo()); ie.setTelefono(ins.getTelefono()); return ie; } public static Inscripto mapInscriptoModelo(InscriptoEntity ins) { Inscripto ie = new Inscripto(); ie.setId(ins.getId()); ie.setNombre(ins.getNombre()); ie.setApellido(ins.getApellido()); ie.setDni(ins.getDni()); ie.setFecha_nacimiento(ins.getFecha_nacimiento()); ie.setNacionalidad(ins.getNacionalidad()); ie.setPais(ins.getPais()); ie.setProvincia(ins.getProvincia()); ie.setLocalidad(ins.getLocalidad()); ie.setDireccion(ins.getDireccion()); ie.setEmail(ins.getEmail()); ie.setCelular(ins.getCelular()); ie.setMayorEdad(ins.isMayorEdad()); ie.setNivelEducativo(ins.getNivelEducativo()); ie.setTelefono(ins.getTelefono()); return ie; } }
[ "alcfp654*456" ]
alcfp654*456
532b9630a297331de40bd80e17c9b5ce262346d6
60e50adf695302f75c6972f6a5588127f32eeb28
/Generics/WildCardsInGenerics.java
b58f7942c37a66bc1a127853245b7d1538efc91e
[]
no_license
vinaypathak07/Java-Code
600a8331ca8341199ab0f3d22007efaeec32eb0a
1baa4b0505d25f8ab711d6aec886b811269ae52b
refs/heads/master
2020-03-30T17:52:25.468123
2019-01-22T19:58:15
2019-01-22T19:58:15
151,473,445
0
1
null
2019-02-16T13:48:57
2018-10-03T20:05:39
Java
UTF-8
Java
false
false
1,121
java
import java.util.*; abstract class College{ abstract public void displayName(); } class DitUniversity extends College{ public void displayName(){ System.out.println("You are in Dit University"); } } class IndianInstituteOfTechnology extends College{ public void displayName(){ System.out.println("You are in Indian Institute Of Technology"); } } class NationalInstituteOfTechnology extends College{ public void displayName(){ System.out.println("You are in National Institute Of Technology"); } } public class WildCardsInGenerics{ public static void displayNames(List<? extends College> lists) { for(College c : lists){ c.displayName(); try{ Thread.sleep(3000); } catch(Exception e){ } } } public static void main(String[] args){ ArrayList<College> al = new ArrayList<College>(); al.add(new DitUniversity()); al.add(new NationalInstituteOfTechnology()); al.add(new IndianInstituteOfTechnology()); displayNames(al); } }
f220939ee3c3950be5594f1ec4d0db4b57b62f34
48c566d8ef89736ca683b22ec3d537b765821a36
/mission_weekend2/src/com/work/model/service/MemberService.java
6d5fdb5c441358b27aca677ebaf985fa0d6e379b
[ "MIT" ]
permissive
ki-yungkim/Playdata_mission_Java
a62cb8db9ef17f7e2b4ebbaebb0620ff9b6cae08
580479b17d8cb6499764b85c71f3bbb0ec8c932f
refs/heads/main
2023-06-05T05:25:25.770757
2021-06-27T12:45:16
2021-06-27T12:45:16
372,217,918
0
0
null
null
null
null
UTF-8
Java
false
false
15,286
java
package com.work.model.service; import com.work.model.dto.AdminMember; import com.work.model.dto.GeneralMember; import com.work.model.dto.Member; import com.work.model.dto.SpecialMember; /** * <pre> * 회원을 관리하기 위한 서비스 클래스 * 추상 클래스 @see {@link MemberServiceAbstract} * * 1. 회원등록 * 2. 회원상세조회 * 3. 전체조회 * 4. 전체변경 * 5. 비밀번호 변경 * 6. 회원 탈퇴 * 7. 회원 전체탈퇴(초기화) * 8. 초기 회원 등록 * 9. 로그인 * 10. 가입일 조회하여 아이디 출력 * 11. 전화번호, 이메일 조회하여 아이디 출력 * 12. 아이디, 전화번호, 이메일 조회하여 비밀번호 출력 * 13. 등급별 아이디 조회 * </pre> * * @author 김기영 * @version ver.1.0 * @since jdk1.8 */ public class MemberService extends MemberServiceAbstract { /** * 회원들을 관리하기 위한 자료 저장구조 */ private Member[] members = new Member[10]; private int count; /** * 현재 등록 인원수 조회 * @return 현재 등록 인원수 */ public int getCount() { return count; } /** * * 회원등록 메서드 * 1. 현재 등록된 회원수(count)와 현재 배열의 크기가 같은지 비교 * 2. 같으면 새로이 (현재 배열 크기 X 2) 크기의 확장배열 생성 * 3. 확장한 배열요소에 기존 배열요소 이동, 저장 * 4. 기존에 참조하고 있는 배열 대신 새로운 배열요소 변경 참조 설정 * 5. 회원수가 배열의 크기와 다르면 이미 등록된 회원 아이디와 일치하는지 확인 * 6. 일치하면 index 번호 반환, 다르면 -1 반환 * 6. -1이 반환되면 count 1 증가하고 members[count]에 아규먼트로 전달받은 회원객체 등록 * */ @Override public void addMember(Member dto) { if (count == members.length) { extendMembers(); } if (exist(dto.getMemberId()) == -1) { members[count++] = dto; } else { System.out.println("[오류]" + dto.getMemberId() + " 아이디는 사용할 수 없습니다."); } } /** * 배열구조 추가 확장해서 기존 저장정보 이동 처리 메서드 * 1. memberTemp 배열을 (members x 2} 길이로 생성 * 2. System.arraycopy로 배열 복사 * 3. members에 참조 변경 * * @see java.lang.System#arraycopy(Object, int, Object, int, int) * */ public void extendMembers() { Member[] memberTemp = new Member[members.length + members.length]; System.arraycopy(members, 0, memberTemp, 0, members.length); members = memberTemp; } /** * 초기회원 등록 메서드 */ @Override public void initMember() { super.initMember(); Member dto1 = new GeneralMember("user01", "password01", "홍길동", "01012341000", "[email protected]", "2020-12-15", "G", 50000); Member dto2 = new GeneralMember("user02", "password02", "강감찬", "01012342000", "[email protected]", "2021-01-05", "G", 950000); Member dto3 = new SpecialMember("user03", "password03", "이순신", "01012343000", "[email protected]", "2020-11-15", "S", "강동원"); Member dto4 = new SpecialMember("user04", "password04", "김유신", "01012344000", "[email protected]", "2021-01-05", "S", "김하린"); Member dto5 = new AdminMember("administrator", "admin1004", "유관순", "01012345000", "[email protected]", "2020-04-01", "A", "선임"); addMember(dto1); addMember(dto2); addMember(dto3); addMember(dto4); addMember(dto5); } /** * 회원상세조회 * 1. exist(String memberId) 수행결과 : 저장위치 반환 * 2. 저장위치 0보다 크거나 같은지 비교해서 * 3. True면 존재하니까 해당 배열요소의 객체를 return 반환 * 4. False면 (0보다 작으면) 존재하지 않음, 오류 메세지 출력 * 5. 존재하지 않으므로 객체타입의 기본 값 return null * */ @Override public Member getMember(String memberId) { int index = exist(memberId); if (index >= 0) { return members[index]; } System.out.println("[오류]" + memberId + "는 존재하지 않는 아이디입니다."); return null; } /** * CRUD 메서드에서 사용하기 위한 회원 존재유무 및 저장 위치 조회 메서드 * 1. 현재 등록된 회원수만큼 반복하면서 * 2. 배열에 저장된 순서대로 저장된 객체의 아이디와(dto.getMemberId()) 아규먼트로 전달받은 아이디가 같은지 비교해서 (Sting#equals(문자열)) * 3. 아이디가 같으면 현재 저장된 배열요소의 인덱스 번호를 반환 * 4. 반복을 다 했는데도 return 되지 않았다면 아이디 정보를 갖는 회원객체가 존재하지 않으므로 return -1 * 5. 같은 방식으로 다른 요소들도 존재 유무 확인 * @param memberId 아이디 * @param memberPw 비밀번호 * @param memberEntryDate 가입일 * @param memberMobile 전화번호 * @param memberEmail 이메일 * @param memberGrade 등급 * @return 존재시에 저장위치 번호, 미존재시 -1 */ @Override public int exist(String memberId) { for (int index = 0; index < count; index++) { if(members[index].getMemberId().equals(memberId)) { return index; } } return -1; } @Override public int existPw(String memberPw) { for (int index = 0; index < count; index++) { if(members[index].getMemberPw().equals(memberPw)) { return index; } } return -1; } @Override public int existEntryDate(String entryDate) { for (int index = 0; index < count; index++) { if(members[index].getEntryDate().equals(entryDate)) { return index; } } return -1; } @Override public int existMobile(String mobile) { for (int index = 0; index < count; index++) { if(members[index].getMobile().equals(mobile)) { return index; } } return -1; } @Override public int existEmail(String email) { for (int index = 0; index < count; index++) { if(members[index].getEmail().equals(email)) { return index; } } return -1; } @Override public int existGrade(String grade) { for (int index = 0; index < count; index++) { if(members[index].getGrade().equals(grade)) { return index; } } return -1; } @Override public int[] existGradeArray(String grade) { int[] temp = new int[count]; int index = 0; for (int i = 0; i < count; i++) { if(members[index].getGrade().equals(grade)) { temp[i] = index ; } else { temp[i] = -1; } index++; } return temp; } /** * 전체 조회 * * 1. members 길이만큼의 배열 memberPrint 만들고 * 2. members의 요소들 복사 * 3. memberPrint 배열 출력 * * checKpoint : 다른 방법 고안 중 * @see java.lang.System#arraycopy(Object, int, Object, int, int) */ @Override public Member[] getMember() { Member[] memberPrint = new Member[members.length]; System.arraycopy(members, 0, memberPrint, 0, count); for (int index = 0; index < count; index++) { System.out.println(memberPrint[index]); } return null; } /** * 전체변경 (아이디가 일치하면 정보 변경) * 1. 받은 아규먼트의 아이디를 조회하여 존재하는지 확인하고 * 2. 존재하면 요소 위치를 받아와서 * 3. 그 요소 위치에 있는 정보들을 받은 아규먼트에 있는 정보로 아이디 제외 전부 교체 * 4. 오류 발생시 메세지 처리 * checKpoint : 아이디까지 바꿀 수 있는 다른 방법 고안 중 */ @Override public void setMember(Member dto) { int index = exist(dto.getMemberId()); if (index >= 0) { members[index] = dto; System.out.println(dto); } else { System.out.println("[오류]" + dto.getMemberId() + "는 존재하지 않는 아이디입니다."); } return; } /** * 비밀번호 변경 * 1. 받은 아이디가 존재하는지 확인하고 존재하면 요소 위치 받아서 * 2. 그 위치의 비밀번호와 아규먼트로 전달받은 비밀번호가 같은지 비교하고 * 3. 같으면 전달받은 새로운 비밀번호로 변경 * 4. 오류 : 아이디가 존재하지 않는 경우, 비밀번호가 맞지 않는 경우 * */ @Override public boolean setMemberPw(String memberId, String memberPw, String newPw) { int index = exist(memberId); if (index >= 0) { if (members[index].getMemberPw().equals(memberPw) == true) { members[index].setMemberPw(newPw); System.out.println(members[index]); } else { System.out.println("[오류]" + "아이디 또는 비밀번호가 맞지 않습니다."); } } else { System.out.println("[오류]" + "아이디 또는 비밀번호가 맞지 않습니다."); } return false; } /** * 회원탈퇴 * 1. 아이디, 비밀번호 존재하는지, 요소 위치 조회 * 2. 아이디, 비밀번호 요소 위치가 동일하면 * 3. (count - 1)에 있는 요소를 그 위치로 옮기고 마지막 요소는 null 처리 * 4. 오류 : 아이디가 없는 경우, 비밀번호가 틀린 경우 * */ @Override public void removeMember(String memberId, String memberPw) { int indexId = exist(memberId); int indexPw = existPw(memberPw); if (indexId < 0) { System.out.println("[오류]" + "없는 아이디 입니다."); return; } if (indexPw < 0) { System.out.println("[오류]" + "비밀번호가 틀립니다."); return; } if (indexId == indexPw) { members[indexId] = members[(count - 1)]; members[(count - 1)] = null; count--; } else { System.out.println("[오류]" + "비밀번호가 틀립니다."); } for (int index = 0; index < count; index++) { System.out.println(members[index]); } } /** * 회원 전체탈퇴 (데이터초기화) * 1. members 배열 요소를 모두 null 만들고 * 2. count를 0으로 만듬 * */ @Override public void removeMember() { for (int index = 0; index < count; index++) { members[index] = null; System.out.println(members[index]); } count = 0; } /** * 계정 로그인 기능 * 1. 입력된 아이디, 비빌번호 존재 유무, 위치 조회 * 2. 아이디, 비밀번호 요소 위치 동일하면 로그인 메세지 출력 * 3. 오류 : 아이디가 존재하지 않는 경우, 아이디와 비밀번호 요소 위치가 다른 경우 * * 추가 고안 사항 : 로그인 시 마일리지 추가하는 기능 * getMileage를 불러오는 방식을 실패하여 막혀있음 * */ public void login(String memberId, String memberPw) { int indexId = exist(memberId); int indexPw = existPw(memberPw); if (indexId < 0) { System.out.println("[오류]" + "아이디 또는 비밀번호가 틀립니다."); return; } if (indexId == indexPw) { System.out.println(memberId + "로 로그인되었습니다."); } else { System.out.println("[오류]" + "아이디 또는 비밀번호가 틀립니다."); } } /** * 가입일 조회해서 아이디 출력 * 1. 입력된 가입일 존재 유무, 위치 조회 * 2. 가입일 요소 위치에 해당하는 아이디 출력 * 3. 오류 : 가입일이 없는 경우 * * 추가 고안 사항 : 입력한 가입일 기준 그 이후 가입 아이디 출력 기능 구현 */ @Override public void entryDateId(String entryDate) { int index = existEntryDate(entryDate); if (index >= 0) { String ID = members[index].getMemberId(); System.out.println("해당 가입일에 맞는 아이디는 : " + ID + "입니다"); } else { System.out.println("[오류] 가입일 : " + entryDate + "인 아이디는 존재하지 않습니다."); } } /** * 전화번호, 이메일 조회해서 아이디 출력 * 1. 입력된 전화번호, 이메일 존재 유무, 위치 조회 * 2. 전화번호, 이메일의 요소 위치가 동일하면 * 3. 요소 위치에 해당하는 아이디 출력 * 4. 오류 : 전화번호가 없는 경우, 이메일이 없는 경우, 요소 위치가 다른 경우 * */ @Override public void searchId(String mobile, String email) { int indexMobile = existMobile(mobile); int indexEmail = existEmail(email); if (indexMobile < 0) { System.out.println("[오류]" + "없는 전화번호입니다."); return; } if (indexEmail < 0) { System.out.println("[오류]" + "없는 이메일입니다."); return; } if (indexMobile == indexEmail) { String ID = members[indexMobile].getMemberId(); System.out.println("[오류]" + "해당 정보에 맞는 아이디는 " + ID + "입니다."); } else { System.out.println("[오류]" + "전화번호 또는 이메일 정보가 정확하지 않습니다."); } } /** * 아이디, 전화번호, 이메일 조회해서 비밀번호 출력 * 1. 입력된 아이디, 전화번호, 이메일 존재 유무, 위치 조회 * 2. 아이디, 전화번호, 이메일의 요소 위치가 동일하면 * 3. 요소 위치에 해당하는 비밀번호 출력 * 4. 오류 : 아이디가 없는 경우, 전화번호가 없는 경우, 이메일이 없는 경우, 요소 위치가 다른 경우 */ @Override public void searchPw(String memberId, String mobile, String email) { int indexId = exist(memberId); int indexMobile = existMobile(mobile); int indexEmail = existEmail(email); if (indexId < 0) { System.out.println("[오류]" + "없는 아이디입니다."); return; } if (indexMobile < 0) { System.out.println("[오류]" + "없는 전화번호입니다."); return; } if (indexEmail < 0) { System.out.println("[오류]" + "없는 이메일입니다."); return; } if ((indexId == indexMobile)&&(indexMobile == indexEmail) ) { String PW = members[indexId].getMemberPw(); System.out.println( "해당 정보에 맞는 비밀번호는 " + PW + "입니다."); } else { System.out.println("[오류]" + "정보가 정확하지 않습니다."); } } /** * 등급별 아이디 조회 * 1. 입력된 등급이 존재하면 요소 위치를, 존재하지 않으면 -1을 반환하는 existGradeArray 이용 * 2. 배열 indexGrade에 값들을 넣고 요소 값이 0 이상이면 요소에 맞는 아이디 출력 * 3. 오류 : 값이 -1이면 잘못된 등급을 입력하셨습니다 출력 * */ @Override public void gradeMember(String grade) { int[] indexGrade = existGradeArray(grade); String[] ID = new String[count]; for (int i = 0; i < count; i++) { if (indexGrade[i] >= 0) { int j = indexGrade[i]; ID[i] = members[j].getMemberId(); System.out.println("해당 등급에 해당하는 아이디는 : " + ID[i] + "입니다"); } } if (existGrade(grade) < 0) { System.out.println("[오류]" + "잘못된 등급을 입력하셨습니다."); } } }
155af65e4123ff3f35a34e6554bee4a26a546e7b
fb6d95018b82a5f43271aaf6cc5507410e90608b
/java-design/src/main/java/com/pazz/java/design/abstractFactory/color/Red.java
d5682bca235b5ed87d81433b686f69af9bac4785
[]
no_license
amakerlee/java-parent
3255833b7ec61df40cf11c3bc82db91a921233ea
b510368a6725d994d98a760fcb6162ca2f834218
refs/heads/master
2022-11-08T20:00:37.768407
2020-01-19T10:19:30
2020-01-19T10:19:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
196
java
package com.pazz.java.design.abstractFactory.color; /** * 红 */ public class Red implements Color { public void fill() { System.out.println("Inside Red::fill() method."); } }
80a5d8916b1818822590f9fbe795a7bcb792092c
356ddc1021936f483e862c7c546f5612a68b3b24
/Digimon/for Developers/Digimoid/src/com/classica/classes/Element.java
88524c86ac004318b23c050e954a597aacec7c0d
[]
no_license
stephenzjp/Digimon-OpenSource-Project
77cef7c734b9588c3921bb4b735749f1fd55fc92
d12e4c61bedf725a4e2e7049e0479f1813fe23e6
refs/heads/master
2022-06-05T04:03:06.967926
2013-05-18T21:57:03
2013-05-18T21:57:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,965
java
package com.classica.classes; import java.util.ArrayList; public class Element { private int id; private int type; private int level; private int species_power; private int min_weight; private ArrayList<Integer> next_digimons; private ArrayList<Integer> require_dps; private String dot_pattern; private int attack_type; public Element(){ this.next_digimons = new ArrayList<Integer>(); this.require_dps = new ArrayList<Integer>(); } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public int getSpecies_power() { return species_power; } public void setSpecies_power(int species_power) { this.species_power = species_power; } public int getMin_weight() { return min_weight; } public void setMin_weight(int min_weight) { this.min_weight = min_weight; } public ArrayList<Integer> getNext_digimons() { return next_digimons; } public void setNext_digimons(ArrayList<Integer> next_digimons) { this.next_digimons = next_digimons; } public ArrayList<Integer> getRequire_dps() { return require_dps; } public void setRequire_dps(ArrayList<Integer> require_dps) { this.require_dps = require_dps; } public String getDot_pattern() { return dot_pattern; } public void setDot_pattern(String dot_pattern) { this.dot_pattern = dot_pattern; } public int getAttack_type() { return attack_type; } public void setAttack_type(int attack_type) { this.attack_type = attack_type; } public String toString(){ String returndata = "id:"+id+"type:"+type+"level:"+level+"species_power"+species_power+"min_weight"+min_weight+"\n"; for(int i = 0;i<this.next_digimons.size();i++){ returndata+=i+"[id:"+next_digimons.get(i)+",dp:"+require_dps.get(i)+"]\n"; } return returndata; } }
[ "4rhH6Xhjm" ]
4rhH6Xhjm
b4a31391a8b0aa06a889a3f1fcabd64d77ab2585
d50e17ba8a79cd34d607f5edf3f6c475cbd2cccd
/camera-framework/src/test/java/org/blackdread/cameraframework/MockLibrary.java
ef9feb672a9d6b2a2cb5cc013251036673f45ad9
[ "MIT" ]
permissive
ysfgrl/canon-sdk-java
bb7282822e7a70d877ab52917d8fbde1c41fd7aa
2ead1c755fb98fbc57ca66cc48f1f72db52fbb2b
refs/heads/master
2020-06-30T04:01:16.881036
2019-07-29T06:08:33
2019-07-29T06:08:33
200,718,460
1
0
MIT
2019-08-05T19:44:20
2019-08-05T19:44:19
null
UTF-8
Java
false
false
2,094
java
/* * MIT License * * Copyright (c) 2018-2019 Yoann CAPLAIN * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package org.blackdread.cameraframework; import org.junit.jupiter.api.condition.EnabledIf; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Allow to enable tests only if library is mocked * <p>Created on 2018/10/20.</p> * * @author Yoann CAPLAIN * @deprecated not sure to keep as it might not be possible unless JNA can also be mocked */ @Target({ElementType.TYPE, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @EnabledIf("systemProperty.get('mockLibrary') == 'true' && systemProperty.get('canonCameraConnected') == 'false' && systemProperty.get('canonLibIsOnPath') == 'false'") public @interface MockLibrary { // works but is not repeatable so not very useful when need to test many things // if camera is connected then we suppose that DLL are present }
e48334941a98b77fab661de2edfa8a70877bfe95
8d719f5f4994d110c46ddcf4c9dc86320efc6969
/src/main/java/com/epam/training/tasks/stoss/services/ServiceException.java
2b825dac7ffb428b436f6ef50da5a9f380c8191b
[]
no_license
smilique/Stoss
189ced621f60bfd93835a5d7a6a2b686e09bacd1
38ea1f38dedf28931280ff72ffb5ff8c97200263
refs/heads/main
2023-06-17T17:54:44.400143
2021-07-16T10:15:40
2021-07-16T10:15:40
349,184,072
0
0
null
2021-07-16T10:15:41
2021-03-18T18:49:07
Java
UTF-8
Java
false
false
253
java
package com.epam.training.tasks.stoss.services; public class ServiceException extends Exception { public ServiceException(Throwable cause) { super(cause); } public ServiceException(String message) { super(message); } }
28fb0651b3434a5cd76b6de7d3038a5811cc30d3
54321da5d4e76b9571efdf7e60b9b6c305de3450
/Anil Personal Projects/Op_Chandra/SpringWS/WebServices_010_basicClient/src/com/jp/fin/services/FinancialServicesImpl.java
9064d19aa5e9704d9f310727b59334979963a734
[]
no_license
anilawasthi/Personal
346f3204212cca188f2b6b304273a849f1c02475
426a451cd38abe5f841aa2b4b71010ab243c8efd
refs/heads/master
2020-04-01T23:56:35.101033
2019-01-11T04:29:53
2019-01-11T04:29:53
153,780,545
0
0
null
null
null
null
UTF-8
Java
false
false
750
java
package com.jp.fin.services; import java.util.ArrayList; import com.jp.fin.exceptions.FinException; import com.jp.fin.locator.LocateServices; import com.jp.hr.entities.Employee; import com.jp.hr.exceptions.HrException; import com.jp.hr.interfaces.EmpSoapServices; public class FinancialServicesImpl implements FinancialServices { private EmpSoapServices soapServices; public FinancialServicesImpl() throws FinException{ soapServices = LocateServices.getEpServices(); } @Override public int getEmpCount() throws FinException { ArrayList<Employee> empList; try { empList = soapServices.getEmpList(); } catch (HrException e) { throw new FinException("Soap service getEmpList() failed", e); } return empList.size(); } }
4c9aa7cfc19a8fbd6686611e51511aa39a195cbd
abeb9520787cc0ebae77331d2f1297ed7b8b38d5
/quizzler-flutter/android/app/src/main/java/co/yohamgabriel/quizzler/MainActivity.java
7d022042c18afa8528241aa3bde7a05e910f12e5
[ "MIT" ]
permissive
Urbine/Flutter-Dart-Development
8cf0867cd87a6fa86682f682778c1b8480edd0fa
fba42504caec2594dcd53ee2b138c3f93f7a08c5
refs/heads/main
2023-02-14T01:44:49.265789
2021-01-08T00:47:25
2021-01-08T00:47:25
327,759,416
0
0
null
null
null
null
UTF-8
Java
false
false
369
java
package co.yohamgabriel.quizzler; import android.os.Bundle; import io.flutter.app.FlutterActivity; import io.flutter.plugins.GeneratedPluginRegistrant; public class MainActivity extends FlutterActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); GeneratedPluginRegistrant.registerWith(this); } }
dc55185b477068ae6ad62881646900ede7149f65
70f5d2fa23c3abb73493e070cf3af1e000c18d52
/src/main/java/za/ac/cput/service/physical/impl/RoomService.java
9be8764d2c085c3c9588ad4ee053556be460d5be
[]
no_license
DinelleK219089302/adp3assignment3
310d53a4abeb7ad4423346efb4d11e40e3e58fdd
4309ff0dce6760511dd89efb59ab1865f01cbb5e
refs/heads/main
2023-07-14T09:32:47.312306
2021-08-28T21:28:03
2021-08-28T21:28:03
374,974,065
0
0
null
2021-06-08T10:50:02
2021-06-08T10:50:01
null
UTF-8
Java
false
false
1,101
java
package za.ac.cput.service.physical.impl; /** * author: Llewelyn Klaase * student no: 216267072 */ import za.ac.cput.entity.physical.Room; import za.ac.cput.repository.physical.impl.RoomRepository; import za.ac.cput.service.physical.IRoomService; import java.util.Set; public class RoomService implements IRoomService { private static RoomService Roomservice = null; private RoomRepository repository; public RoomService() { this.repository = RoomRepository.getRepository(); } public static RoomService getService(){ if(Roomservice == null){ Roomservice = new RoomService(); } return Roomservice; } public Room create(Room room) { return this.repository.create(room); } public Room read(String s) { return this.repository.read(s); } public Room update(Room room) { return this.repository.update(room); } public boolean delete(String s) { return this.repository.delete(s); } public Set<Room> getAll() { return this.repository.getAll(); } }
4daabc3cc3d88b01725ca2f89b8df8b6e99e988a
85729bc67e6869f90a9af0c5a43c2f7ebec9026c
/web/src/main/java/com/qingqingmr/qqmr/web/interceptor/BackLoginInterceptor.java
d24d72b229d9f68abd506654f39e48c5fbaa5b7b
[]
no_license
A1621377453/qqmr.parent
fe2be6102c49a2cdc5ab80550fe501926760de6f
069257f3c0e0d1db25fd263967d87ada54db218a
refs/heads/master
2020-03-27T23:19:09.248778
2018-09-04T08:26:54
2018-09-04T08:26:54
147,309,179
1
0
null
null
null
null
UTF-8
Java
false
false
2,952
java
package com.qingqingmr.qqmr.web.interceptor; import com.alibaba.fastjson.JSON; import com.qingqingmr.qqmr.common.ResultInfo; import com.qingqingmr.qqmr.common.constant.SystemConstant; import com.qingqingmr.qqmr.web.annotation.CheckLogin; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.lang.annotation.Annotation; import java.util.HashMap; import java.util.Map; /** * 后台登录拦截器 * * @author crn * @datetime 2018-07-04 15:49:43 */ public class BackLoginInterceptor implements HandlerInterceptor { /** * 预处理回调方法,实现处理器的预处理 */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler instanceof HandlerMethod) { CheckLogin checkLogin = findAnnotation((HandlerMethod) handler, CheckLogin.class); if (checkLogin != null && checkLogin.isCheck()) { if (request.getSession().getAttribute(SystemConstant.SESSION_SUPERVISOR + request.getSession().getId()) == null) { Map<String, Object> map = new HashMap<>(); map.put("code", ResultInfo.EXCEPTION_CODE_1); map.put("msg", ResultInfo.EXCEPTION_MSG_1); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-type", "text/html;charset=UTF-8"); PrintWriter writer = response.getWriter(); writer.write(JSON.toJSONString(map)); writer.flush(); return false; } } } return true; } /** * 获取注解(首先获取类注解,然后获取方法注解) * * @param handler * @param annotationType * @datetime 2018/7/15 17:58 * @author crn * @return T */ private <T extends Annotation> T findAnnotation(HandlerMethod handler, Class<T> annotationType) { T annotation = handler.getBeanType().getAnnotation(annotationType); if (annotation != null) return annotation; return handler.getMethodAnnotation(annotationType); } /** * 后处理回调方法,实现处理器的后处理 */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * 整个请求处理完毕回调方法 */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
75bf243f07e4bb6f46c6e19f3b803df20ea842f4
a3e364ee0d7965fdc1d423e499c6591feb92d455
/uikit/src/com/netease/nim/uikit/team/adapter/TeamMemberListAdapter.java
618db705ee37940855a7ec8c9185bb65cc30f244
[ "MIT" ]
permissive
dusuijiang/SmartLife
ec67503cb1c02e0131a2c9c5eac398847bb7d28a
bba67671bb98917964903e6917e6b342d661fef2
refs/heads/master
2021-05-14T05:41:30.273327
2018-01-04T07:12:23
2018-01-04T07:12:23
116,227,524
1
0
null
null
null
null
UTF-8
Java
false
false
2,068
java
package com.netease.nim.uikit.team.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.netease.nim.uikit.R; import com.netease.nim.uikit.team.viewholder.TeamMemberListHolder; import com.netease.nimlib.sdk.team.model.TeamMember; import java.util.List; /** * Created by hzchenkang on 2016/12/2. */ public class TeamMemberListAdapter extends RecyclerView.Adapter<TeamMemberListHolder> implements View.OnClickListener{ public interface ItemClickListener{ void onItemClick(TeamMember member); } private Context context; private List<TeamMember> members; private ItemClickListener listener; public TeamMemberListAdapter(Context context) { this.context = context; } public void updateData(List<TeamMember> members) { this.members = members; notifyDataSetChanged(); } public void setListener(ItemClickListener listener) { this.listener = listener; } @Override public TeamMemberListHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (context == null) { return null; } LayoutInflater inflater = LayoutInflater.from(context); View v = inflater.inflate(R.layout.nim_ait_contact_team_member_item, parent, false); v.setOnClickListener(this); return new TeamMemberListHolder(v); } @Override public void onBindViewHolder(TeamMemberListHolder holder, int position) { if (members == null || members.size() <= position) { return; } TeamMember member = members.get(position); holder.refresh(member); } @Override public int getItemCount() { return members == null ? 0 : members.size(); } @Override public void onClick(View v) { TeamMember member = (TeamMember) v.getTag(); if (listener != null) { listener.onItemClick(member); } } }
[ "rd0404@rd01_protruly.com" ]
rd0404@rd01_protruly.com
5ae9589d4edee460e217f185cf808239486ad06b
5b0dd660e40a9b9d6afe9b7105bc442bc8ae4015
/kosta1200/src/kosta1200/todayroom/action/MemberSignup_Form.java
322d4739e25060d5d7576f7054b9739086c846d2
[]
no_license
kangsukyung/todaysroom_JSP_PROJECT
9c12f17ec07bca3f40ba142a58fa6bea216d3132
00df970d1f3b39f992f489386ba680a7cadba499
refs/heads/master
2023-01-01T19:18:30.205949
2020-10-27T06:24:50
2020-10-27T06:24:50
null
0
0
null
null
null
null
UTF-8
Java
false
false
480
java
package kosta1200.todayroom.action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MemberSignup_Form implements Action{ @Override public ActionForward execute(HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward forward=new ActionForward(); forward.setRedirect(false); forward.setPath("../main_views/member/member_signup.jsp"); return forward; } }
3e467116a7d5c6a23c8c649c85b0cdcdd68466a6
811831a51755b9f5d8e7823b43317d3e856b6ba6
/sandbox/src/SomeInterfaceImpl.java
a025215bcc39e3848c0fda96489f09ac96a87b1b
[]
no_license
terminatingcode/exercises
b8e1652844c455b9eda1434fb0513d8fd5d9f464
bc15ddadcb948d738fbadc52db8feaa1eca0b9ce
refs/heads/master
2021-01-15T12:28:27.981059
2016-04-04T10:19:31
2016-04-04T10:19:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
103
java
/** * Created by chris on 12/01/2016. */ public class SomeInterfaceImpl implements SomeInterface { }
5ab4b7cf91bf0f01dbda6bde67759cbc0d9076a6
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/14/14_64077e9710ac8e8df1b7c9828ea985cccb3d8446/RecipientEditTextView/14_64077e9710ac8e8df1b7c9828ea985cccb3d8446_RecipientEditTextView_s.java
92808b753c7859fe3f4147573b784db6f0df751a
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
75,328
java
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ex.chips; import android.app.Dialog; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Handler; import android.os.Message; import android.text.Editable; import android.text.InputType; import android.text.Layout; import android.text.Spannable; import android.text.SpannableString; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextWatcher; import android.text.method.QwertyKeyListener; import android.text.style.ImageSpan; import android.text.util.Rfc822Token; import android.text.util.Rfc822Tokenizer; import android.util.AttributeSet; import android.util.Log; import android.view.ActionMode; import android.view.ActionMode.Callback; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.ViewParent; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Filterable; import android.widget.ListAdapter; import android.widget.ListPopupWindow; import android.widget.ListView; import android.widget.MultiAutoCompleteTextView; import android.widget.ScrollView; import android.widget.TextView; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * RecipientEditTextView is an auto complete text view for use with applications * that use the new Chips UI for addressing a message to recipients. */ public class RecipientEditTextView extends MultiAutoCompleteTextView implements OnItemClickListener, Callback, RecipientAlternatesAdapter.OnCheckedItemChangedListener, GestureDetector.OnGestureListener, OnDismissListener, OnClickListener { private static final String TAG = "RecipientEditTextView"; // TODO: get correct number/ algorithm from with UX. private static final int CHIP_LIMIT = 2; private Drawable mChipBackground = null; private Drawable mChipDelete = null; private int mChipPadding; private Tokenizer mTokenizer; private Drawable mChipBackgroundPressed; private RecipientChip mSelectedChip; private int mAlternatesLayout; private Bitmap mDefaultContactPhoto; private ImageSpan mMoreChip; private TextView mMoreItem; private final ArrayList<String> mPendingChips = new ArrayList<String>(); private float mChipHeight; private float mChipFontSize; private Validator mValidator; private Drawable mInvalidChipBackground; private Handler mHandler; private static int DISMISS = "dismiss".hashCode(); private static final long DISMISS_DELAY = 300; private int mPendingChipsCount = 0; private static int sSelectedTextColor = -1; private static final char COMMIT_CHAR_COMMA = ','; private static final char COMMIT_CHAR_SEMICOLON = ';'; private static final char COMMIT_CHAR_SPACE = ' '; private ListPopupWindow mAlternatesPopup; private ListPopupWindow mAddressPopup; private ArrayList<RecipientChip> mTemporaryRecipients; private ArrayList<RecipientChip> mRemovedSpans; private boolean mShouldShrink = true; // Chip copy fields. private GestureDetector mGestureDetector; private Dialog mCopyDialog; private int mCopyViewRes; private String mCopyAddress; /** * Used with {@link #mAlternatesPopup}. Handles clicks to alternate addresses for a * selected chip. */ private OnItemClickListener mAlternatesListener; private int mCheckedItem; private TextWatcher mTextWatcher; private ScrollView mScrollView; private boolean mTried; private final Runnable mAddTextWatcher = new Runnable() { @Override public void run() { if (mTextWatcher == null) { mTextWatcher = new RecipientTextWatcher(); addTextChangedListener(mTextWatcher); } } }; private IndividualReplacementTask mIndividualReplacements; private Runnable mHandlePendingChips = new Runnable() { @Override public void run() { handlePendingChips(); } }; public RecipientEditTextView(Context context, AttributeSet attrs) { super(context, attrs); if (sSelectedTextColor == -1) { sSelectedTextColor = context.getResources().getColor(android.R.color.white); } mAlternatesPopup = new ListPopupWindow(context); mAddressPopup = new ListPopupWindow(context); mCopyDialog = new Dialog(context); mAlternatesListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView,View view, int position, long rowId) { mAlternatesPopup.setOnItemClickListener(null); replaceChip(mSelectedChip, ((RecipientAlternatesAdapter) adapterView.getAdapter()) .getRecipientEntry(position)); Message delayed = Message.obtain(mHandler, DISMISS); delayed.obj = mAlternatesPopup; mHandler.sendMessageDelayed(delayed, DISMISS_DELAY); clearComposingText(); } }; setInputType(getInputType() | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); setOnItemClickListener(this); setCustomSelectionActionModeCallback(this); mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == DISMISS) { ((ListPopupWindow) msg.obj).dismiss(); return; } super.handleMessage(msg); } }; mTextWatcher = new RecipientTextWatcher(); addTextChangedListener(mTextWatcher); mGestureDetector = new GestureDetector(context, this); } @Override public <T extends ListAdapter & Filterable> void setAdapter(T adapter) { super.setAdapter(adapter); if (adapter == null) { return; } } @Override public void onSelectionChanged(int start, int end) { // When selection changes, see if it is inside the chips area. // If so, move the cursor back after the chips again. Spannable span = getSpannable(); int textLength = getText().length(); RecipientChip[] chips = span.getSpans(start, textLength, RecipientChip.class); if (chips != null && chips.length > 0) { if (chips != null && chips.length > 0) { // Grab the last chip and set the cursor to after it. setSelection(Math.min(span.getSpanEnd(chips[chips.length - 1]) + 1, textLength)); } } super.onSelectionChanged(start, end); } /** * Convenience method: Append the specified text slice to the TextView's * display buffer, upgrading it to BufferType.EDITABLE if it was * not already editable. Commas are excluded as they are added automatically * by the view. */ @Override public void append(CharSequence text, int start, int end) { // We don't care about watching text changes while appending. if (mTextWatcher != null) { removeTextChangedListener(mTextWatcher); } super.append(text, start, end); if (!TextUtils.isEmpty(text) && TextUtils.getTrimmedLength(text) > 0) { final String displayString = (String) text; int seperatorPos = displayString.indexOf(COMMIT_CHAR_COMMA); if (seperatorPos != 0 && !TextUtils.isEmpty(displayString) && TextUtils.getTrimmedLength(displayString) > 0) { mPendingChipsCount++; mPendingChips.add((String)text); } } // Put a message on the queue to make sure we ALWAYS handle pending chips. if (mPendingChipsCount > 0) { postHandlePendingChips(); } mHandler.post(mAddTextWatcher); } @Override public void onFocusChanged(boolean hasFocus, int direction, Rect previous) { super.onFocusChanged(hasFocus, direction, previous); if (!hasFocus) { shrink(); } else { expand(); scrollLineIntoView(getLineCount()); } } @Override public void performValidation() { // Do nothing. Chips handles its own validation. } private void shrink() { if (mSelectedChip != null && mSelectedChip.getEntry().getContactId() != RecipientEntry.INVALID_CONTACT) { clearSelectedChip(); } else { // Reset any pending chips as they would have been handled // when the field lost focus. if (mPendingChipsCount > 0) { postHandlePendingChips(); } else { Editable editable = getText(); int end = getSelectionEnd(); int start = mTokenizer.findTokenStart(editable, end); RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); if ((chips == null || chips.length == 0)) { int whatEnd = mTokenizer.findTokenEnd(getText(), start); // In the middle of chip; treat this as an edit // and commit the whole token. if (whatEnd != getSelectionEnd()) { handleEdit(start, whatEnd); } else { commitChip(start, end, editable); } } } mHandler.post(mAddTextWatcher); } createMoreChip(); } private void expand() { removeMoreChip(); setCursorVisible(true); Editable text = getText(); setSelection(text != null && text.length() > 0 ? text.length() : 0); // If there are any temporary chips, try replacing them now that the user // has expanded the field. if (mTemporaryRecipients != null && mTemporaryRecipients.size() > 0) { new RecipientReplacementTask().execute(); mTemporaryRecipients = null; } } private CharSequence ellipsizeText(CharSequence text, TextPaint paint, float maxWidth) { paint.setTextSize(mChipFontSize); if (maxWidth <= 0 && Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Max width is negative: " + maxWidth); } return TextUtils.ellipsize(text, paint, maxWidth, TextUtils.TruncateAt.END); } private Bitmap createSelectedChip(RecipientEntry contact, TextPaint paint, Layout layout) { // Ellipsize the text so that it takes AT MOST the entire width of the // autocomplete text entry area. Make sure to leave space for padding // on the sides. int height = (int) mChipHeight; int deleteWidth = height; CharSequence ellipsizedText = ellipsizeText(contact.getDisplayName(), paint, calculateAvailableWidth(true) - deleteWidth); // Make sure there is a minimum chip width so the user can ALWAYS // tap a chip without difficulty. int width = Math.max(deleteWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0, ellipsizedText.length())) + (mChipPadding * 2) + deleteWidth); // Create the background of the chip. Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(tmpBitmap); if (mChipBackgroundPressed != null) { mChipBackgroundPressed.setBounds(0, 0, width, height); mChipBackgroundPressed.draw(canvas); paint.setColor(sSelectedTextColor); // Vertically center the text in the chip. canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, getTextYOffset((String) ellipsizedText, paint, height), paint); // Make the delete a square. mChipDelete.setBounds(width - deleteWidth, 0, width, height); mChipDelete.draw(canvas); } else { Log.w(TAG, "Unable to draw a background for the chips as it was never set"); } return tmpBitmap; } /** * Get the background drawable for a RecipientChip. */ public Drawable getChipBackground(RecipientEntry contact) { return (mValidator != null && mValidator.isValid(contact.getDestination())) ? mChipBackground : mInvalidChipBackground; } private Bitmap createUnselectedChip(RecipientEntry contact, TextPaint paint, Layout layout) { // Ellipsize the text so that it takes AT MOST the entire width of the // autocomplete text entry area. Make sure to leave space for padding // on the sides. int height = (int) mChipHeight; int iconWidth = height; String displayText = !TextUtils.isEmpty(contact.getDisplayName()) ? contact.getDisplayName() : !TextUtils.isEmpty(contact.getDestination()) ? contact.getDestination() : ""; CharSequence ellipsizedText = ellipsizeText(displayText, paint, calculateAvailableWidth(false) - iconWidth); // Make sure there is a minimum chip width so the user can ALWAYS // tap a chip without difficulty. int width = Math.max(iconWidth * 2, (int) Math.floor(paint.measureText(ellipsizedText, 0, ellipsizedText.length())) + (mChipPadding * 2) + iconWidth); // Create the background of the chip. Bitmap tmpBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(tmpBitmap); Drawable background = getChipBackground(contact); if (background != null) { background.setBounds(0, 0, width, height); background.draw(canvas); // Don't draw photos for recipients that have been typed in. if (contact.getContactId() != RecipientEntry.INVALID_CONTACT) { byte[] photoBytes = contact.getPhotoBytes(); // There may not be a photo yet if anything but the first contact address // was selected. if (photoBytes == null && contact.getPhotoThumbnailUri() != null) { // TODO: cache this in the recipient entry? ((BaseRecipientAdapter) getAdapter()).fetchPhoto(contact, contact .getPhotoThumbnailUri()); photoBytes = contact.getPhotoBytes(); } Bitmap photo; if (photoBytes != null) { photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length); } else { // TODO: can the scaled down default photo be cached? photo = mDefaultContactPhoto; } // Draw the photo on the left side. Matrix matrix = new Matrix(); RectF src = new RectF(0, 0, photo.getWidth(), photo.getHeight()); RectF dst = new RectF(width - iconWidth, 0, width, height); matrix.setRectToRect(src, dst, Matrix.ScaleToFit.CENTER); canvas.drawBitmap(photo, matrix, paint); } else { // Don't leave any space for the icon. It isn't being drawn. iconWidth = 0; } // Vertically center the text in the chip. canvas.drawText(ellipsizedText, 0, ellipsizedText.length(), mChipPadding, getTextYOffset((String)ellipsizedText, paint, height), paint); } else { Log.w(TAG, "Unable to draw a background for the chips as it was never set"); } return tmpBitmap; } private float getTextYOffset(String text, TextPaint paint, int height) { Rect bounds = new Rect(); paint.getTextBounds((String)text, 0, text.length(), bounds); int textHeight = bounds.bottom - bounds.top - (int)paint.descent(); return height - ((height - textHeight) / 2); } public RecipientChip constructChipSpan(RecipientEntry contact, int offset, boolean pressed) throws NullPointerException { if (mChipBackground == null) { throw new NullPointerException( "Unable to render any chips as setChipDimensions was not called."); } Layout layout = getLayout(); TextPaint paint = getPaint(); float defaultSize = paint.getTextSize(); int defaultColor = paint.getColor(); Bitmap tmpBitmap; if (pressed) { tmpBitmap = createSelectedChip(contact, paint, layout); } else { tmpBitmap = createUnselectedChip(contact, paint, layout); } // Pass the full text, un-ellipsized, to the chip. Drawable result = new BitmapDrawable(getResources(), tmpBitmap); result.setBounds(0, 0, tmpBitmap.getWidth(), tmpBitmap.getHeight()); RecipientChip recipientChip = new RecipientChip(result, contact, offset); // Return text to the original size. paint.setTextSize(defaultSize); paint.setColor(defaultColor); return recipientChip; } /** * Calculate the bottom of the line the chip will be located on using: * 1) which line the chip appears on * 2) the height of a chip * 3) padding built into the edit text view */ private int calculateOffsetFromBottom(int line) { // Line offsets start at zero. int actualLine = getLineCount() - (line + 1); return -((actualLine * ((int) mChipHeight) + getPaddingBottom()) + getPaddingTop()) + getDropDownVerticalOffset(); } /** * Get the max amount of space a chip can take up. The formula takes into * account the width of the EditTextView, any view padding, and padding * that will be added to the chip. */ private float calculateAvailableWidth(boolean pressed) { return getWidth() - getPaddingLeft() - getPaddingRight() - (mChipPadding * 2); } /** * Set all chip dimensions and resources. This has to be done from the * application as this is a static library. * @param chipBackground * @param chipBackgroundPressed * @param invalidChip * @param chipDelete * @param defaultContact * @param moreResource * @param alternatesLayout * @param chipHeight * @param padding Padding around the text in a chip * @param chipFontSize * @param copyViewRes */ public void setChipDimensions(Drawable chipBackground, Drawable chipBackgroundPressed, Drawable invalidChip, Drawable chipDelete, Bitmap defaultContact, int moreResource, int alternatesLayout, float chipHeight, float padding, float chipFontSize, int copyViewRes) { mChipBackground = chipBackground; mChipBackgroundPressed = chipBackgroundPressed; mChipDelete = chipDelete; mChipPadding = (int) padding; mAlternatesLayout = alternatesLayout; mDefaultContactPhoto = defaultContact; mMoreItem = (TextView) LayoutInflater.from(getContext()).inflate(moreResource, null); mChipHeight = chipHeight; mChipFontSize = chipFontSize; mInvalidChipBackground = invalidChip; mCopyViewRes = copyViewRes; } /** * Set whether to shrink the recipients field such that at most * one line of recipients chips are shown when the field loses * focus. By default, the number of displayed recipients will be * limited and a "more" chip will be shown when focus is lost. * @param shrink */ public void setOnFocusListShrinkRecipients(boolean shrink) { mShouldShrink = shrink; } @Override public void onSizeChanged(int width, int height, int oldw, int oldh) { super.onSizeChanged(width, height, oldw, oldh); if (width != 0 && height != 0 && mPendingChipsCount > 0) { postHandlePendingChips(); } // Try to find the scroll view parent, if it exists. if (mScrollView == null && !mTried) { ViewParent parent = getParent(); while (parent != null && !(parent instanceof ScrollView)) { parent = parent.getParent(); } if (parent != null) { mScrollView = (ScrollView) parent; } mTried = true; } } private void postHandlePendingChips() { mHandler.removeCallbacks(mHandlePendingChips); mHandler.post(mHandlePendingChips); } private void handlePendingChips() { if (mPendingChipsCount <= 0) { return; } if (getWidth() <= 0) { // The widget has not been sized yet. // This will be called as a result of onSizeChanged // at a later point. return; } synchronized (mPendingChips) { mTemporaryRecipients = new ArrayList<RecipientChip>(mPendingChipsCount); Editable editable = getText(); // Tokenize! for (int i = 0; i < mPendingChips.size(); i++) { String current = mPendingChips.get(i); int tokenStart = editable.toString().indexOf(current); int tokenEnd = tokenStart + current.length(); if (tokenStart >= 0) { // When we have a valid token, include it with the token // to the left. if (tokenEnd < editable.length() - 2 && editable.charAt(tokenEnd) == COMMIT_CHAR_COMMA) { tokenEnd++; } createReplacementChip(tokenStart, tokenEnd, editable); } mPendingChipsCount--; } sanitizeSpannable(); if (mTemporaryRecipients != null && mTemporaryRecipients.size() <= RecipientAlternatesAdapter.MAX_LOOKUPS) { if (hasFocus() || mTemporaryRecipients.size() < CHIP_LIMIT) { new RecipientReplacementTask().execute(); mTemporaryRecipients = null; } else { // Create the "more" chip mIndividualReplacements = new IndividualReplacementTask(); mIndividualReplacements.execute(new ArrayList<RecipientChip>( mTemporaryRecipients.subList(0, CHIP_LIMIT))); createMoreChip(); } } else { // There are too many recipients to look up, so just fall back // to // showing addresses for all of them. mTemporaryRecipients = null; createMoreChip(); } mPendingChipsCount = 0; mPendingChips.clear(); } } /** * Remove any characters after the last valid chip. */ private void sanitizeSpannable() { // Find the last chip; eliminate any commit characters after it. RecipientChip[] chips = getRecipients(); if (chips != null && chips.length > 0) { int end; ImageSpan lastSpan; if (mMoreChip != null) { lastSpan = mMoreChip; } else { lastSpan = chips[chips.length - 1]; } end = getSpannable().getSpanEnd(lastSpan); Editable editable = getText(); int length = editable.length(); if (length > end) { // See what characters occur after that and eliminate them. if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "There were extra characters after the last tokenizable entry." + editable); } editable.delete(end + 1, length); } } } /** * Create a chip that represents just the email address of a recipient. At some later * point, this chip will be attached to a real contact entry, if one exists. */ private void createReplacementChip(int tokenStart, int tokenEnd, Editable editable) { if (alreadyHasChip(tokenStart, tokenEnd)) { // There is already a chip present at this location. // Don't recreate it. return; } String token = editable.toString().substring(tokenStart, tokenEnd); int commitCharIndex = token.trim().lastIndexOf(COMMIT_CHAR_COMMA); if (commitCharIndex == token.length() - 1) { token = token.substring(0, token.length() - 1); } RecipientEntry entry = createTokenizedEntry(token); if (entry != null) { String destText = entry.getDestination(); destText = (String) mTokenizer.terminateToken(destText); // Always leave a blank space at the end of a chip. int textLength = destText.length() - 1; SpannableString chipText = new SpannableString(destText); int end = getSelectionEnd(); int start = mTokenizer.findTokenStart(getText(), end); RecipientChip chip = null; try { chip = constructChipSpan(entry, start, false); chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (NullPointerException e) { Log.e(TAG, e.getMessage(), e); } editable.replace(tokenStart, tokenEnd, chipText); // Add this chip to the list of entries "to replace" if (chip != null) { chip.setOriginalText(chipText.toString()); mTemporaryRecipients.add(chip); } } } private RecipientEntry createTokenizedEntry(String token) { if (TextUtils.isEmpty(token)) { return null; } Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(token); String display = null; if (isValid(token) && tokens != null && tokens.length > 0) { // If we can get a name from tokenizing, then generate an entry from // this. display = tokens[0].getName(); if (!TextUtils.isEmpty(display)) { return RecipientEntry.constructGeneratedEntry(display, token); } else { display = tokens[0].getAddress(); if (!TextUtils.isEmpty(display)) { return RecipientEntry.constructFakeEntry(display); } } } // Unable to validate the token or to create a valid token from it. // Just create a chip the user can edit. if (mValidator != null && !mValidator.isValid(token)) { // Try fixing up the entry using the validator. token = mValidator.fixText(token).toString(); if (!TextUtils.isEmpty(token)) { // protect against the case of a validator with a null domain, // which doesn't add a domain to the token Rfc822Token[] tokenized = Rfc822Tokenizer.tokenize(token); if (tokenized.length > 0) { token = tokenized[0].getAddress(); } } } // Otherwise, fallback to just creating an editable email address chip. return RecipientEntry.constructFakeEntry(token); } private boolean isValid(String text) { return mValidator == null ? true : mValidator.isValid(text); } private String tokenizeAddress(String destination) { Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(destination); if (tokens != null && tokens.length > 0) { return tokens[0].getAddress(); } return destination; } @Override public void setTokenizer(Tokenizer tokenizer) { mTokenizer = tokenizer; super.setTokenizer(mTokenizer); } @Override public void setValidator(Validator validator) { mValidator = validator; super.setValidator(validator); } /** * We cannot use the default mechanism for replaceText. Instead, * we override onItemClickListener so we can get all the associated * contact information including display text, address, and id. */ @Override protected void replaceText(CharSequence text) { return; } /** * Dismiss any selected chips when the back key is pressed. */ @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { clearSelectedChip(); } return super.onKeyPreIme(keyCode, event); } /** * Monitor key presses in this view to see if the user types * any commit keys, which consist of ENTER, TAB, or DPAD_CENTER. * If the user has entered text that has contact matches and types * a commit key, create a chip from the topmost matching contact. * If the user has entered text that has no contact matches and types * a commit key, then create a chip from the text they have entered. */ @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_ENTER: case KeyEvent.KEYCODE_DPAD_CENTER: if (event.hasNoModifiers()) { if (commitDefault()) { return true; } if (mSelectedChip != null) { clearSelectedChip(); return true; } else if (focusNext()) { return true; } } break; case KeyEvent.KEYCODE_TAB: if (event.hasNoModifiers()) { if (mSelectedChip != null) { clearSelectedChip(); } else { commitDefault(); } if (focusNext()) { return true; } } } return super.onKeyUp(keyCode, event); } private boolean focusNext() { View next = focusSearch(View.FOCUS_DOWN); if (next != null) { next.requestFocus(); return true; } return false; } /** * Create a chip from the default selection. If the popup is showing, the * default is the first item in the popup suggestions list. Otherwise, it is * whatever the user had typed in. End represents where the the tokenizer * should search for a token to turn into a chip. * @return If a chip was created from a real contact. */ private boolean commitDefault() { Editable editable = getText(); int end = getSelectionEnd(); int start = mTokenizer.findTokenStart(editable, end); if (shouldCreateChip(start, end)) { int whatEnd = mTokenizer.findTokenEnd(getText(), start); // In the middle of chip; treat this as an edit // and commit the whole token. if (whatEnd != getSelectionEnd()) { handleEdit(start, whatEnd); return true; } return commitChip(start, end , editable); } return false; } private void commitByCharacter() { Editable editable = getText(); int end = getSelectionEnd(); int start = mTokenizer.findTokenStart(editable, end); if (shouldCreateChip(start, end)) { commitChip(start, end, editable); } setSelection(getText().length()); } private boolean commitChip(int start, int end, Editable editable) { if (getAdapter().getCount() > 0 && enoughToFilter()) { // choose the first entry. submitItemAtPosition(0); dismissDropDown(); return true; } else { int tokenEnd = mTokenizer.findTokenEnd(editable, start); String text = editable.toString().substring(start, tokenEnd).trim(); clearComposingText(); if (text != null && text.length() > 0 && !text.equals(" ")) { RecipientEntry entry = createTokenizedEntry(text); if (entry != null) { QwertyKeyListener.markAsReplaced(editable, start, end, ""); CharSequence chipText = createChip(entry, false); editable.replace(start, end, chipText); } dismissDropDown(); return true; } } return false; } private boolean shouldCreateChip(int start, int end) { return hasFocus() && enoughToFilter() && !alreadyHasChip(start, end); } private boolean alreadyHasChip(int start, int end) { RecipientChip[] chips = getSpannable().getSpans(start, end, RecipientChip.class); if ((chips == null || chips.length == 0)) { return false; } return true; } private void handleEdit(int start, int end) { // This is in the middle of a chip, so select out the whole chip // and commit it. Editable editable = getText(); setSelection(end); String text = getText().toString().substring(start, end); RecipientEntry entry = RecipientEntry.constructFakeEntry(text); QwertyKeyListener.markAsReplaced(editable, start, end, ""); CharSequence chipText = createChip(entry, false); editable.replace(start, getSelectionEnd(), chipText); dismissDropDown(); } /** * If there is a selected chip, delegate the key events * to the selected chip. */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mSelectedChip != null && keyCode == KeyEvent.KEYCODE_DEL) { if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { mAlternatesPopup.dismiss(); } removeChip(mSelectedChip); } if (keyCode == KeyEvent.KEYCODE_ENTER && event.hasNoModifiers()) { return true; } return super.onKeyDown(keyCode, event); } private Spannable getSpannable() { return getText(); } private int getChipStart(RecipientChip chip) { return getSpannable().getSpanStart(chip); } private int getChipEnd(RecipientChip chip) { return getSpannable().getSpanEnd(chip); } /** * Instead of filtering on the entire contents of the edit box, * this subclass method filters on the range from * {@link Tokenizer#findTokenStart} to {@link #getSelectionEnd} * if the length of that range meets or exceeds {@link #getThreshold} * and makes sure that the range is not already a Chip. */ @Override protected void performFiltering(CharSequence text, int keyCode) { if (enoughToFilter()) { int end = getSelectionEnd(); int start = mTokenizer.findTokenStart(text, end); // If this is a RecipientChip, don't filter // on its contents. Spannable span = getSpannable(); RecipientChip[] chips = span.getSpans(start, end, RecipientChip.class); if (chips != null && chips.length > 0) { return; } } super.performFiltering(text, keyCode); } private void clearSelectedChip() { if (mSelectedChip != null) { unselectChip(mSelectedChip); mSelectedChip = null; } setCursorVisible(true); } /** * Monitor touch events in the RecipientEditTextView. * If the view does not have focus, any tap on the view * will just focus the view. If the view has focus, determine * if the touch target is a recipient chip. If it is and the chip * is not selected, select it and clear any other selected chips. * If it isn't, then select that chip. */ @Override public boolean onTouchEvent(MotionEvent event) { if (!isFocused()) { // Ignore any chip taps until this view is focused. return super.onTouchEvent(event); } boolean handled = super.onTouchEvent(event); int action = event.getAction(); boolean chipWasSelected = false; if (mSelectedChip == null) { mGestureDetector.onTouchEvent(event); } if (mCopyAddress == null && action == MotionEvent.ACTION_UP) { float x = event.getX(); float y = event.getY(); int offset = putOffsetInRange(getOffsetForPosition(x, y)); RecipientChip currentChip = findChip(offset); if (currentChip != null) { if (action == MotionEvent.ACTION_UP) { if (mSelectedChip != null && mSelectedChip != currentChip) { clearSelectedChip(); mSelectedChip = selectChip(currentChip); } else if (mSelectedChip == null) { // Selection may have moved due to the tap event, // but make sure we correctly reset selection to the // end so that any unfinished chips are committed. setSelection(getText().length()); commitDefault(); mSelectedChip = selectChip(currentChip); } else { onClick(mSelectedChip, offset, x, y); } } chipWasSelected = true; handled = true; } } if (action == MotionEvent.ACTION_UP && !chipWasSelected) { clearSelectedChip(); } return handled; } private void scrollLineIntoView(int line) { if (mScrollView != null) { mScrollView.scrollBy(0, calculateOffsetFromBottom(line)); } } private void showAlternates(RecipientChip currentChip, ListPopupWindow alternatesPopup, int width, Context context) { int line = getLayout().getLineForOffset(getChipStart(currentChip)); int bottom = calculateOffsetFromBottom(line); // Align the alternates popup with the left side of the View, // regardless of the position of the chip tapped. alternatesPopup.setWidth(width); alternatesPopup.setAnchorView(this); alternatesPopup.setVerticalOffset(bottom); alternatesPopup.setAdapter(createAlternatesAdapter(currentChip)); alternatesPopup.setOnItemClickListener(mAlternatesListener); // Clear the checked item. mCheckedItem = -1; alternatesPopup.show(); ListView listView = alternatesPopup.getListView(); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); // Checked item would be -1 if the adapter has not // loaded the view that should be checked yet. The // variable will be set correctly when onCheckedItemChanged // is called in a separate thread. if (mCheckedItem != -1) { listView.setItemChecked(mCheckedItem, true); mCheckedItem = -1; } } private ListAdapter createAlternatesAdapter(RecipientChip chip) { return new RecipientAlternatesAdapter(getContext(), chip.getContactId(), chip.getDataId(), mAlternatesLayout, this); } private ListAdapter createSingleAddressAdapter(RecipientChip currentChip) { return new SingleRecipientArrayAdapter(getContext(), mAlternatesLayout, currentChip .getEntry()); } @Override public void onCheckedItemChanged(int position) { ListView listView = mAlternatesPopup.getListView(); if (listView != null && listView.getCheckedItemCount() == 0) { listView.setItemChecked(position, true); } mCheckedItem = position; } // TODO: This algorithm will need a lot of tweaking after more people have used // the chips ui. This attempts to be "forgiving" to fat finger touches by favoring // what comes before the finger. private int putOffsetInRange(int o) { int offset = o; Editable text = getText(); int length = text.length(); // Remove whitespace from end to find "real end" int realLength = length; for (int i = length - 1; i >= 0; i--) { if (text.charAt(i) == ' ') { realLength--; } else { break; } } // If the offset is beyond or at the end of the text, // leave it alone. if (offset >= realLength) { return offset; } Editable editable = getText(); while (offset >= 0 && findText(editable, offset) == -1 && findChip(offset) == null) { // Keep walking backward! offset--; } return offset; } private int findText(Editable text, int offset) { if (text.charAt(offset) != ' ') { return offset; } return -1; } private RecipientChip findChip(int offset) { RecipientChip[] chips = getSpannable().getSpans(0, getText().length(), RecipientChip.class); // Find the chip that contains this offset. for (int i = 0; i < chips.length; i++) { RecipientChip chip = chips[i]; int start = getChipStart(chip); int end = getChipEnd(chip); if (offset >= start && offset <= end) { return chip; } } return null; } private CharSequence createChip(RecipientEntry entry, boolean pressed) { String displayText = entry.getDestination(); displayText = (String) mTokenizer.terminateToken(displayText); // Always leave a blank space at the end of a chip. int textLength = displayText.length()-1; SpannableString chipText = new SpannableString(displayText); int end = getSelectionEnd(); int start = mTokenizer.findTokenStart(getText(), end); try { RecipientChip chip = constructChipSpan(entry, start, pressed); chipText.setSpan(chip, 0, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); chip.setOriginalText(chipText.toString()); } catch (NullPointerException e) { Log.e(TAG, e.getMessage(), e); return null; } return chipText; } /** * When an item in the suggestions list has been clicked, create a chip from the * contact information of the selected item. */ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { submitItemAtPosition(position); } private void submitItemAtPosition(int position) { RecipientEntry entry = createValidatedEntry( (RecipientEntry)getAdapter().getItem(position)); if (entry == null) { return; } clearComposingText(); int end = getSelectionEnd(); int start = mTokenizer.findTokenStart(getText(), end); Editable editable = getText(); QwertyKeyListener.markAsReplaced(editable, start, end, ""); CharSequence chip = createChip(entry, false); if (chip != null) { editable.replace(start, end, chip); } } private RecipientEntry createValidatedEntry(RecipientEntry item) { if (item == null) { return null; } final RecipientEntry entry; // If the display name and the address are the same, or if this is a // valid contact, but the destination is invalid, then make this a fake // recipient that is editable. String destination = item.getDestination(); if (TextUtils.isEmpty(item.getDisplayName()) || TextUtils.equals(item.getDisplayName(), destination) || (mValidator != null && !mValidator.isValid(destination))) { entry = RecipientEntry.constructFakeEntry(destination); } else { entry = item; } return entry; } /** Returns a collection of contact Id for each chip inside this View. */ /* package */ Collection<Long> getContactIds() { final Set<Long> result = new HashSet<Long>(); RecipientChip[] chips = getRecipients(); if (chips != null) { for (RecipientChip chip : chips) { result.add(chip.getContactId()); } } return result; } private RecipientChip[] getRecipients() { return getSpannable().getSpans(0, getText().length(), RecipientChip.class); } private RecipientChip[] getSortedRecipients() { ArrayList<RecipientChip> recipientsList = new ArrayList<RecipientChip>(Arrays .asList(getRecipients())); final Spannable spannable = getSpannable(); Collections.sort(recipientsList, new Comparator<RecipientChip>() { @Override public int compare(RecipientChip first, RecipientChip second) { int firstStart = spannable.getSpanStart(first); int secondStart = spannable.getSpanStart(second); if (firstStart < secondStart) { return -1; } else if (firstStart > secondStart) { return 1; } else { return 0; } } }); return recipientsList.toArray(new RecipientChip[recipientsList.size()]); } /** Returns a collection of data Id for each chip inside this View. May be null. */ /* package */ Collection<Long> getDataIds() { final Set<Long> result = new HashSet<Long>(); RecipientChip [] chips = getRecipients(); if (chips != null) { for (RecipientChip chip : chips) { result.add(chip.getDataId()); } } return result; } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { return false; } @Override public void onDestroyActionMode(ActionMode mode) { } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } /** * No chips are selectable. */ @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { return false; } /** * Create the more chip. The more chip is text that replaces any chips that * do not fit in the pre-defined available space when the * RecipientEditTextView loses focus. */ private void createMoreChip() { if (!mShouldShrink) { return; } ImageSpan[] tempMore = getSpannable().getSpans(0, getText().length(), MoreImageSpan.class); if (tempMore.length > 0) { getSpannable().removeSpan(tempMore[0]); } RecipientChip[] recipients = getSortedRecipients(); if (recipients == null || recipients.length <= CHIP_LIMIT) { mMoreChip = null; return; } Spannable spannable = getSpannable(); int numRecipients = recipients.length; int overage = numRecipients - CHIP_LIMIT; String moreText = String.format(mMoreItem.getText().toString(), overage); TextPaint morePaint = new TextPaint(getPaint()); morePaint.setTextSize(mMoreItem.getTextSize()); morePaint.setColor(mMoreItem.getCurrentTextColor()); int width = (int)morePaint.measureText(moreText) + mMoreItem.getPaddingLeft() + mMoreItem.getPaddingRight(); int height = getLineHeight(); Bitmap drawable = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(drawable); canvas.drawText(moreText, 0, moreText.length(), 0, height - getLayout().getLineDescent(0), morePaint); Drawable result = new BitmapDrawable(getResources(), drawable); result.setBounds(0, 0, width, height); MoreImageSpan moreSpan = new MoreImageSpan(result); // Remove the overage chips. if (recipients == null || recipients.length == 0) { Log.w(TAG, "We have recipients. Tt should not be possible to have zero RecipientChips."); mMoreChip = null; return; } mRemovedSpans = new ArrayList<RecipientChip>(); int totalReplaceStart = 0; int totalReplaceEnd = 0; Editable text = getText(); for (int i = numRecipients - overage; i < recipients.length; i++) { mRemovedSpans.add(recipients[i]); if (i == numRecipients - overage) { totalReplaceStart = spannable.getSpanStart(recipients[i]); } if (i == recipients.length - 1) { totalReplaceEnd = spannable.getSpanEnd(recipients[i]); } if (mTemporaryRecipients == null || !mTemporaryRecipients.contains(recipients[i])) { int spanStart = spannable.getSpanStart(recipients[i]); int spanEnd = spannable.getSpanEnd(recipients[i]); recipients[i].setOriginalText(text.toString().substring(spanStart, spanEnd)); } spannable.removeSpan(recipients[i]); } int end = Math.max(totalReplaceStart, totalReplaceEnd); int start = Math.min(totalReplaceStart, totalReplaceEnd); SpannableString chipText = new SpannableString(text.subSequence(start, end)); chipText.setSpan(moreSpan, 0, chipText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); text.replace(start, end, chipText); mMoreChip = moreSpan; } /** * Replace the more chip, if it exists, with all of the recipient chips it had * replaced when the RecipientEditTextView gains focus. */ private void removeMoreChip() { if (mMoreChip != null) { Spannable span = getSpannable(); span.removeSpan(mMoreChip); mMoreChip = null; // Re-add the spans that were removed. if (mRemovedSpans != null && mRemovedSpans.size() > 0) { // Recreate each removed span. Editable editable = getText(); for (RecipientChip chip : mRemovedSpans) { int chipStart; int chipEnd; String token; // Need to find the location of the chip, again. token = (String) chip.getOriginalText(); chipStart = editable.toString().indexOf(token); // -1 for the space! chipEnd = Math.min(editable.length(), chipStart + token.length()); // Only set the span if we found a matching token. if (chipStart != -1) { editable.setSpan(chip, chipStart, chipEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } mRemovedSpans.clear(); } } } /** * Show specified chip as selected. If the RecipientChip is just an email address, * selecting the chip will take the contents of the chip and place it at * the end of the RecipientEditTextView for inline editing. If the * RecipientChip is a complete contact, then selecting the chip * will change the background color of the chip, show the delete icon, * and a popup window with the address in use highlighted and any other * alternate addresses for the contact. * @param currentChip Chip to select. * @return A RecipientChip in the selected state or null if the chip * just contained an email address. */ public RecipientChip selectChip(RecipientChip currentChip) { if (currentChip.getContactId() == RecipientEntry.INVALID_CONTACT) { CharSequence text = currentChip.getValue(); Editable editable = getText(); removeChip(currentChip); editable.append(text); setCursorVisible(true); setSelection(editable.length()); return new RecipientChip(null, RecipientEntry.constructFakeEntry((String) text), -1); } else if (currentChip.getContactId() == RecipientEntry.GENERATED_CONTACT) { int start = getChipStart(currentChip); int end = getChipEnd(currentChip); getSpannable().removeSpan(currentChip); RecipientChip newChip; try { newChip = constructChipSpan(currentChip.getEntry(), start, true); } catch (NullPointerException e) { Log.e(TAG, e.getMessage(), e); return null; } Editable editable = getText(); QwertyKeyListener.markAsReplaced(editable, start, end, ""); if (start == -1 || end == -1) { Log.d(TAG, "The chip being selected no longer exists but should."); } else { editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } newChip.setSelected(true); if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) { scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); } showAddress(newChip, mAddressPopup, getWidth(), getContext()); setCursorVisible(false); return newChip; } else { int start = getChipStart(currentChip); int end = getChipEnd(currentChip); getSpannable().removeSpan(currentChip); RecipientChip newChip; try { newChip = constructChipSpan(currentChip.getEntry(), start, true); } catch (NullPointerException e) { Log.e(TAG, e.getMessage(), e); return null; } Editable editable = getText(); QwertyKeyListener.markAsReplaced(editable, start, end, ""); if (start == -1 || end == -1) { Log.d(TAG, "The chip being selected no longer exists but should."); } else { editable.setSpan(newChip, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } newChip.setSelected(true); if (newChip.getEntry().getContactId() == RecipientEntry.INVALID_CONTACT) { scrollLineIntoView(getLayout().getLineForOffset(getChipStart(newChip))); } showAlternates(newChip, mAlternatesPopup, getWidth(), getContext()); setCursorVisible(false); return newChip; } } private void showAddress(final RecipientChip currentChip, final ListPopupWindow popup, int width, Context context) { int line = getLayout().getLineForOffset(getChipStart(currentChip)); int bottom = calculateOffsetFromBottom(line); // Align the alternates popup with the left side of the View, // regardless of the position of the chip tapped. popup.setWidth(width); popup.setAnchorView(this); popup.setVerticalOffset(bottom); popup.setAdapter(createSingleAddressAdapter(currentChip)); popup.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { unselectChip(currentChip); popup.dismiss(); } }); popup.show(); ListView listView = popup.getListView(); listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); listView.setItemChecked(0, true); } /** * Remove selection from this chip. Unselecting a RecipientChip will render * the chip without a delete icon and with an unfocused background. This * is called when the RecipientChip no longer has focus. */ public void unselectChip(RecipientChip chip) { int start = getChipStart(chip); int end = getChipEnd(chip); Editable editable = getText(); mSelectedChip = null; if (start == -1 || end == -1) { Log.e(TAG, "The chip being unselected no longer exists."); } else { getSpannable().removeSpan(chip); QwertyKeyListener.markAsReplaced(editable, start, end, ""); editable.removeSpan(chip); try { editable.setSpan(constructChipSpan(chip.getEntry(), start, false), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } catch (NullPointerException e) { Log.e(TAG, e.getMessage(), e); } } setCursorVisible(true); setSelection(editable.length()); if (mAlternatesPopup != null && mAlternatesPopup.isShowing()) { mAlternatesPopup.dismiss(); } } /** * Return whether this chip contains the position passed in. */ public boolean matchesChip(RecipientChip chip, int offset) { int start = getChipStart(chip); int end = getChipEnd(chip); if (start == -1 || end == -1) { return false; } return (offset >= start && offset <= end); } /** * Return whether a touch event was inside the delete target of * a selected chip. It is in the delete target if: * 1) the x and y points of the event are within the * delete assset. * 2) the point tapped would have caused a cursor to appear * right after the selected chip. * @return boolean */ private boolean isInDelete(RecipientChip chip, int offset, float x, float y) { // Figure out the bounds of this chip and whether or not // the user clicked in the X portion. return chip.isSelected() && offset == getChipEnd(chip); } /** * Remove the chip and any text associated with it from the RecipientEditTextView. */ private void removeChip(RecipientChip chip) { Spannable spannable = getSpannable(); int spanStart = spannable.getSpanStart(chip); int spanEnd = spannable.getSpanEnd(chip); Editable text = getText(); int toDelete = spanEnd; boolean wasSelected = chip == mSelectedChip; // Clear that there is a selected chip before updating any text. if (wasSelected) { mSelectedChip = null; } // Always remove trailing spaces when removing a chip. while (toDelete >= 0 && toDelete < text.length() && text.charAt(toDelete) == ' ') { toDelete++; } spannable.removeSpan(chip); text.delete(spanStart, toDelete); if (wasSelected) { clearSelectedChip(); } } /** * Replace this currently selected chip with a new chip * that uses the contact data provided. */ public void replaceChip(RecipientChip chip, RecipientEntry entry) { boolean wasSelected = chip == mSelectedChip; if (wasSelected) { mSelectedChip = null; } int start = getChipStart(chip); int end = getChipEnd(chip); getSpannable().removeSpan(chip); Editable editable = getText(); CharSequence chipText = createChip(entry, false); if (start == -1 || end == -1) { Log.e(TAG, "The chip to replace does not exist but should."); editable.insert(0, chipText); } else { // There may be a space to replace with this chip's new associated // space. Check for it. int toReplace = end; while (toReplace >= 0 && toReplace < editable.length() && editable.charAt(toReplace) == ' ') { toReplace++; } editable.replace(start, toReplace, chipText); } setCursorVisible(true); if (wasSelected) { clearSelectedChip(); } } /** * Handle click events for a chip. When a selected chip receives a click * event, see if that event was in the delete icon. If so, delete it. * Otherwise, unselect the chip. */ public void onClick(RecipientChip chip, int offset, float x, float y) { if (chip.isSelected()) { if (isInDelete(chip, offset, x, y)) { removeChip(chip); } else { clearSelectedChip(); } } } private boolean chipsPending() { return mPendingChipsCount > 0 || (mRemovedSpans != null && mRemovedSpans.size() > 0); } @Override public void removeTextChangedListener(TextWatcher watcher) { mTextWatcher = null; super.removeTextChangedListener(watcher); } private class RecipientTextWatcher implements TextWatcher { @Override public void afterTextChanged(Editable s) { // If the text has been set to null or empty, make sure we remove // all the spans we applied. if (TextUtils.isEmpty(s)) { // Remove all the chips spans. Spannable spannable = getSpannable(); RecipientChip[] chips = spannable.getSpans(0, getText().length(), RecipientChip.class); for (RecipientChip chip : chips) { spannable.removeSpan(chip); } if (mMoreChip != null) { spannable.removeSpan(mMoreChip); } return; } // Get whether there are any recipients pending addition to the // view. If there are, don't do anything in the text watcher. if (chipsPending()) { return; } if (mSelectedChip != null) { setCursorVisible(true); setSelection(getText().length()); clearSelectedChip(); } int length = s.length(); // Make sure there is content there to parse and that it is // not just the commit character. if (length > 1) { char last; int end = getSelectionEnd() == 0 ? 0 : getSelectionEnd() - 1; int len = length() - 1; if (end != len) { last = s.charAt(end); } else { last = s.charAt(len); } if (last == COMMIT_CHAR_SEMICOLON || last == COMMIT_CHAR_COMMA) { commitByCharacter(); } else if (last == COMMIT_CHAR_SPACE) { // Check if this is a valid email address. If it is, // commit it. String text = getText().toString(); int tokenStart = mTokenizer.findTokenStart(text, getSelectionEnd()); String sub = text.substring(tokenStart, mTokenizer.findTokenEnd(text, tokenStart)); if (mValidator != null && mValidator.isValid(sub)) { commitByCharacter(); } } } } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // Do nothing. } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } } private class RecipientReplacementTask extends AsyncTask<Void, Void, Void> { private RecipientChip createFreeChip(RecipientEntry entry) { String displayText = entry.getDestination(); if (displayText.indexOf(",") == -1) { displayText = (String) mTokenizer.terminateToken(displayText); } try { return constructChipSpan(entry, -1, false); } catch (NullPointerException e) { Log.e(TAG, e.getMessage(), e); return null; } } @Override protected Void doInBackground(Void... params) { if (mIndividualReplacements != null) { mIndividualReplacements.cancel(true); } // For each chip in the list, look up the matching contact. // If there is a match, replace that chip with the matching // chip. final ArrayList<RecipientChip> originalRecipients = new ArrayList<RecipientChip>(); RecipientChip[] existingChips = getSortedRecipients(); for (int i = 0; i < existingChips.length; i++) { originalRecipients.add(existingChips[i]); } if (mRemovedSpans != null) { originalRecipients.addAll(mRemovedSpans); } String[] addresses = new String[originalRecipients.size()]; for (int i = 0; i < originalRecipients.size(); i++) { addresses[i] = originalRecipients.get(i).getEntry().getDestination(); } HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter .getMatchingRecipients(getContext(), addresses); final ArrayList<RecipientChip> replacements = new ArrayList<RecipientChip>(); for (final RecipientChip temp : originalRecipients) { RecipientEntry entry = null; if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) && getSpannable().getSpanStart(temp) != -1) { // Replace this. entry = createValidatedEntry(entries.get(tokenizeAddress(temp.getEntry() .getDestination()))); } if (entry != null) { replacements.add(createFreeChip(entry)); } else { replacements.add(temp); } } if (replacements != null && replacements.size() > 0) { mHandler.post(new Runnable() { @Override public void run() { SpannableStringBuilder text = new SpannableStringBuilder(getText() .toString()); Editable oldText = getText(); int start, end; int i = 0; for (RecipientChip chip : originalRecipients) { start = oldText.getSpanStart(chip); if (start != -1) { end = oldText.getSpanEnd(chip); text.removeSpan(chip); // Leave a spot for the space! RecipientChip replacement = replacements.get(i); text.setSpan(replacement, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); replacement.setOriginalText(text.toString().substring(start, end)); } i++; } Editable editable = getText(); editable.clear(); editable.insert(0, text); originalRecipients.clear(); } }); } return null; } } private class IndividualReplacementTask extends AsyncTask<Object, Void, Void> { @SuppressWarnings("unchecked") @Override protected Void doInBackground(Object... params) { // For each chip in the list, look up the matching contact. // If there is a match, replace that chip with the matching // chip. final ArrayList<RecipientChip> originalRecipients = (ArrayList<RecipientChip>) params[0]; String[] addresses = new String[originalRecipients.size()]; for (int i = 0; i < originalRecipients.size(); i++) { addresses[i] = originalRecipients.get(i).getEntry().getDestination(); } HashMap<String, RecipientEntry> entries = RecipientAlternatesAdapter .getMatchingRecipients(getContext(), addresses); for (final RecipientChip temp : originalRecipients) { if (RecipientEntry.isCreatedRecipient(temp.getEntry().getContactId()) && getSpannable().getSpanStart(temp) != -1) { // Replace this. final RecipientEntry entry = createValidatedEntry(entries .get(tokenizeAddress(temp.getEntry().getDestination()))); if (entry != null) { mHandler.post(new Runnable() { @Override public void run() { replaceChip(temp, entry); } }); } } } return null; } } /** * MoreImageSpan is a simple class created for tracking the existence of a * more chip across activity restarts/ */ private class MoreImageSpan extends ImageSpan { public MoreImageSpan(Drawable b) { super(b); } } @Override public boolean onDown(MotionEvent e) { return false; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { // Do nothing. return false; } @Override public void onLongPress(MotionEvent event) { if (mSelectedChip != null) { return; } float x = event.getX(); float y = event.getY(); int offset = putOffsetInRange(getOffsetForPosition(x, y)); RecipientChip currentChip = findChip(offset); if (currentChip != null) { // Copy the selected chip email address. showCopyDialog(currentChip.getEntry().getDestination()); } } private void showCopyDialog(final String address) { mCopyAddress = address; mCopyDialog.setTitle(address); mCopyDialog.setContentView(mCopyViewRes); mCopyDialog.setCancelable(true); mCopyDialog.setCanceledOnTouchOutside(true); mCopyDialog.findViewById(android.R.id.button1).setOnClickListener(this); mCopyDialog.setOnDismissListener(this); mCopyDialog.show(); } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // Do nothing. return false; } @Override public void onShowPress(MotionEvent e) { // Do nothing. } @Override public boolean onSingleTapUp(MotionEvent e) { // Do nothing. return false; } @Override public void onDismiss(DialogInterface dialog) { mCopyAddress = null; } @Override public void onClick(View v) { // Copy this to the clipboard. ClipboardManager clipboard = (ClipboardManager) getContext().getSystemService( Context.CLIPBOARD_SERVICE); clipboard.setPrimaryClip(ClipData.newPlainText("", mCopyAddress)); mCopyDialog.dismiss(); } }
5dc446a83a659a9eec3ad6528fb0a39f8a5d3424
26b7f30c6640b8017a06786e4a2414ad8a4d71dd
/src/number_of_direct_superinterfaces/i40312.java
55751136d3548c88bf35ee29e653954ce4da341c
[]
no_license
vincentclee/jvm-limits
b72a2f2dcc18caa458f1e77924221d585f23316b
2fd1c26d1f7984ea8163bc103ad14b6d72282281
refs/heads/master
2020-05-18T11:18:41.711400
2014-09-14T04:25:18
2014-09-14T04:25:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
69
java
package number_of_direct_superinterfaces; public interface i40312 {}
4187e20c3949b8367ce4cd6effd24dc52482ec85
d54851017cfcc91ca17927623a71b5a66602f8ac
/src/main/java/Ali/ashique/ITCENTERFEESMANAGEMENT/converters/StudentCommandToStudent.java
d4cbbea58d7c4f326169f55908e975991fc89960
[]
no_license
AshiqueAliMahar/IT-CENTER-FEES-MANAGEMENT
4a0201189c16d245018d31e81603b31a8a528f8d
7f56ccc416819bf1d3e1d2db98908c18da8f6437
refs/heads/master
2020-08-28T15:11:47.992402
2019-10-26T16:18:12
2019-10-26T16:18:12
217,735,674
0
0
null
null
null
null
UTF-8
Java
false
false
1,036
java
package Ali.ashique.ITCENTERFEESMANAGEMENT.converters; import Ali.ashique.ITCENTERFEESMANAGEMENT.command.StudentCommand; import Ali.ashique.ITCENTERFEESMANAGEMENT.models.Student; import lombok.AllArgsConstructor; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import java.util.stream.Collectors; @Component @AllArgsConstructor public class StudentCommandToStudent implements Converter<StudentCommand, Student> { private FeeCommandToFee feeCommandToFee; @Override public Student convert(StudentCommand studentCommand) { Student student = new Student(); student.setAdmissionDate(studentCommand.getAdmissionDate()); student.setDob(studentCommand.getDob()); student.setName(studentCommand.getName()); student.setRollNo(studentCommand.getRollNo()); student.setFees(studentCommand.getFeeCommands().stream().map(fee -> feeCommandToFee.convert(fee)).collect(Collectors.toList())); return student; } }
d95066e70485b2cd7360a2d71364d25ea91fa0b3
c3a6b3dcf51b4cc3048961e38d4602326926c51c
/src/com/cqupt/mis/rms/model/MajorContributeNew.java
63ce4f8c313ba0c0df4fa5c360a8f20d2f1f6f23
[]
no_license
sdgdsffdsfff/RMS_OLD
5640a326c6290c4f0a5147e493f644b0827afbdb
4ec88fc2914909210f13936162af5223ec275882
refs/heads/master
2021-01-18T11:29:49.828784
2015-08-28T08:11:51
2015-08-28T08:11:51
41,786,646
1
0
null
2015-09-02T07:27:26
2015-09-02T07:27:25
null
UTF-8
Java
false
false
2,956
java
package com.cqupt.mis.rms.model; import java.util.Date; public class MajorContributeNew { private String majorId; private String classContribute;//项目级别 private String typeContribute;//项目类别 private String timeContribute;//立项时间 private String majorName;//项目名称 private Date checkTime;//申报时间 private Date endTime;//结项时间 private Float rewardCollege;//奖励金额 private String remarks;//备注 private String projectSource;//项目来源 private Float reportedAmounts;//申报金额 private CQUPTUser submitUser; private CQUPTUser approvedUser; private Integer status; private String returnReason; public String getMajorId() { return majorId; } public void setMajorId(String majorId) { this.majorId = majorId; } public String getClassContribute() { return classContribute; } public void setClassContribute(String classContribute) { this.classContribute = classContribute; } public String getTypeContribute() { return typeContribute; } public void setTypeContribute(String typeContribute) { this.typeContribute = typeContribute; } public String getTimeContribute() { return timeContribute; } public void setTimeContribute(String timeContribute) { this.timeContribute = timeContribute; } public String getMajorName() { return majorName; } public void setMajorName(String majorName) { this.majorName = majorName; } public Date getCheckTime() { return checkTime; } public void setCheckTime(Date checkTime) { this.checkTime = checkTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Float getRewardCollege() { return rewardCollege; } public void setRewardCollege(Float rewardCollege) { this.rewardCollege = rewardCollege; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public CQUPTUser getSubmitUser() { return submitUser; } public void setSubmitUser(CQUPTUser submitUser) { this.submitUser = submitUser; } public CQUPTUser getApprovedUser() { return approvedUser; } public void setApprovedUser(CQUPTUser approvedUser) { this.approvedUser = approvedUser; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getReturnReason() { return returnReason; } public void setReturnReason(String returnReason) { this.returnReason = returnReason; } public String getProjectSource() { return projectSource; } public void setProjectSource(String projectSource) { this.projectSource = projectSource; } public Float getReportedAmounts() { return reportedAmounts; } public void setReportedAmounts(Float reportedAmounts) { this.reportedAmounts = reportedAmounts; } }
[ "Bern@22ed7b37-85c0-c74d-bab2-c74a3d316cc0" ]
Bern@22ed7b37-85c0-c74d-bab2-c74a3d316cc0
895c9eb80c91e8ea571dc977f444d2e985f2032a
989066ee88468d1458072d596f3cffaee0858323
/app/src/main/java/com/example/asmaralokapreset/ui/home/HomeViewModel.java
16b4884f1dc04cdc56abe86ac35c06b841a19f32
[]
no_license
DimasNuryadin/Android-AsmaralokaPreset
f093166b40c5ab2a33f0632a8062e003e225da79
d8dc709659ef7d99615444ed329f73e6cebed05e
refs/heads/main
2023-07-16T05:19:44.786375
2021-08-22T04:52:38
2021-08-22T04:52:38
398,716,607
0
0
null
null
null
null
UTF-8
Java
false
false
500
java
package com.example.asmaralokapreset.ui.home; import android.widget.Button; import android.widget.ImageView; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; public class HomeViewModel extends ViewModel { private MutableLiveData<String> mText; public HomeViewModel() { mText = new MutableLiveData<>(); mText.setValue(""); } public LiveData<String> getText() { return mText; } }
d0c19f90a571f905ea2a422220a18bf16fa6f540
3334f27475d5d09b3370428bcc6831b93034a645
/Athena/src/main/java/com/charky/repository/TagRepository.java
2c6d99abeb21c5baf91076bd64749325cd8aca50
[]
no_license
charky/Athena
8b1e29cb2a77d13c40bc24948ec1e11cdd3bfec2
f7c8c48b8849dbb704ea7e08aafff3b70853d982
refs/heads/master
2020-07-14T01:12:37.809741
2016-09-18T18:02:49
2016-09-18T18:02:49
67,919,489
0
0
null
null
null
null
UTF-8
Java
false
false
229
java
package com.charky.repository; import org.springframework.data.repository.CrudRepository; import com.charky.domain.Tag; public interface TagRepository extends CrudRepository<Tag, Long> { public Tag findByName(String name); }
42e3998c3293270dffac8062bf5745058570cd3b
3864169ce76fa3fcf838475ba9c165f22d23f04a
/group24/1148285693/learning2017/common/src/main/java/me/lzb/common/utils/AppUtils.java
906c88e7475dd7d60e6450f6ff8e135ed4ebd9e6
[]
no_license
wizardzhang2017/coding2017
0b97887e5f879cb93263242a8f0228e0c1f6d920
b179683f0c737b5681b3de15f485cc0cc512f394
refs/heads/master
2021-01-17T17:08:38.254092
2017-05-27T04:46:56
2017-05-27T04:46:56
84,127,737
2
26
null
2017-05-27T04:46:57
2017-03-06T22:31:00
Java
UTF-8
Java
false
false
355
java
package me.lzb.common.utils; /** * Created by lzbfe on 2017/4/29. */ public class AppUtils { /** * 获取一个数的位数 * @param i * @return */ public static int getDigit(int i) { int a = i; int c = 0; while (a > 0) { a = a / 10; c++; } return c; } }
c601af53bc7c3ef00633238e99d755c286bd6c4f
1563c3b6054c22023a160e1decebc4489bbef06d
/src/main/java/com/ordermanager/project/system/user/domain/UserStatus.java
bd21c654933dcef1f182282c49fbaacb5b7f7e47
[]
no_license
retname/sdlcksups
12993f00912ee787410e280cceacbc6dcaacb6c2
0f95049fcdb90f76dabef8317d01b5f80948e73e
refs/heads/main
2023-05-04T18:12:27.147109
2021-05-25T03:26:30
2021-05-25T03:26:30
370,531,331
0
0
null
null
null
null
UTF-8
Java
false
false
445
java
package com.ordermanager.project.system.user.domain; public enum UserStatus { OK("0", "正常"), DISABLE("1", "停用"), DELETED("2", "删除"); private final String code; private final String info; UserStatus(String code, String info) { this.code = code; this.info = info; } public String getCode() { return code; } public String getInfo() { return info; } }
d3bc4450b1fb588e83e3d19ca97996379d05b081
39fb47502ad4ed339a7e4c439f692c9f40f3db61
/app/src/main/java/com/example/apssw/MainActivity.java
1398f8f528ae018140e21f5d8bd3e15381d39160
[]
no_license
Athulpreman/appdemo
dc9ed27cb8e826fa477a5e272244252dbf4b881c
d5cfb47ffcf197955923cb860a99522f51ce72dd
refs/heads/master
2020-09-26T12:18:45.842195
2019-12-06T10:07:55
2019-12-06T10:07:55
226,253,928
0
0
null
null
null
null
UTF-8
Java
false
false
2,229
java
package com.example.apssw; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText ed1,ed2,e3,e4,e5,e6,e7; Button bt1,bt2; String a,b,c,d,e,f,g; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ed1=(EditText)findViewById(R.id.stdname); ed2=(EditText)findViewById(R.id.amno); e3=(EditText)findViewById(R.id.rolno); e4=(EditText)findViewById(R.id.clg); e5=(EditText)findViewById(R.id.parent); e6=(EditText)findViewById(R.id.mob); e7=(EditText)findViewById(R.id.plc); bt1=(Button)findViewById(R.id.button1); bt2=(Button)findViewById(R.id.button2); bt2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent ob =new Intent(getApplicationContext(),Register.class); startActivity(ob); } }); bt1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { a = ed1.getText().toString(); b = ed2.getText().toString(); c = e3.getText().toString(); d = e4.getText().toString(); e = e5.getText().toString(); f = e6.getText().toString(); g = e7.getText().toString(); if ((a.equals("Athul")) && (c.equals("12345"))) { Toast.makeText(getApplicationContext(), "Login Sussefull..", Toast.LENGTH_SHORT).show(); Intent i=new Intent(getApplicationContext(),Welcome.class); startActivity(i); } else { Toast.makeText(getApplicationContext(),"Login Failed",Toast.LENGTH_LONG).show(); } } }); } }
11cf25dcf353ff23d58436f68537a47bc508e6a0
d0b9a5de771f45d3f9328c826e633f9197977f6b
/src/solid/o/LoanApprovalHandler2.java
c3411f0ff8ff8e9b0885465b6eaa35d41319216b
[]
no_license
vsns11/lectures-java-core
96d766fc3961f6cd614df98d0c5aa1410b2ee64a
59498c2c146ac7a66549f751b1d5c89afb104174
refs/heads/master
2023-05-08T02:02:29.700904
2021-05-27T19:40:45
2021-05-27T19:40:45
null
0
0
null
null
null
null
UTF-8
Java
false
false
182
java
package solid.o; public class LoanApprovalHandler2 { public void approveLoan(Validator validator) { if ( validator.isValid()) { //Process the loan. } } }
196567a8659ccfa52ae99daa6d94aab7a08323f5
09c0dd7d5f87966fa162a0517cf6db2146c864fe
/src/main/java/pl/sztukakodu/bookaro/catalog/db/BookJpaRepository.java
a38fc103ce4bf4721a153cefb73a07c0809deed7
[]
no_license
rengreen/bookaro
d93cf826de648217f4ce72c2ca20330816d5bb68
4e2e00ecee36d37804456159c3d7ebed0088fcee
refs/heads/master
2023-04-08T20:54:10.768750
2021-04-20T06:58:21
2021-04-20T06:58:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
643
java
package pl.sztukakodu.bookaro.catalog.db; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import pl.sztukakodu.bookaro.catalog.domain.Book; import java.util.List; public interface BookJpaRepository extends JpaRepository<Book, Long> { List<Book> findByTitleStartsWithIgnoreCase(String title); @Query( " SELECT b FROM Book b JOIN b.authors a " + " WHERE " + " lower(a.name) LIKE lower(concat('%', :name,'%')) " ) List<Book> findByAuthor(@Param("name") String name); }
88847ab8eedf78841ce05bcd5345211d336b2a5e
d532bd40f590de8af7d6a195403a0d0c4a733367
/src/main/java/ar/com/manflack/desafiospring/app/rest/FlightController.java
d399392208a57c736a6cac7bbd615e210d5f8e5a
[]
no_license
Manflack/hotel-flights-reservation
51553c3b538a986aff8554a4fca6b85008c661d2
6d667826cadf122f2c515684c0d67fe7fc769a3f
refs/heads/main
2023-04-07T02:50:27.626713
2021-04-20T15:27:54
2021-04-20T15:27:54
359,303,787
0
0
null
null
null
null
UTF-8
Java
false
false
2,206
java
package ar.com.manflack.desafiospring.app.rest; import ar.com.manflack.desafiospring.app.dto.StatusDTO; import ar.com.manflack.desafiospring.app.rest.request.FlightReservationRequest; import ar.com.manflack.desafiospring.app.rest.response.FlightReservationResponse; import ar.com.manflack.desafiospring.domain.exception.*; import ar.com.manflack.desafiospring.domain.exception.flight.FlightNotAvailableException; import ar.com.manflack.desafiospring.domain.exception.flight.FlightSeatTypeNotValidException; import ar.com.manflack.desafiospring.domain.exception.hotel.ReservationNotValidException; import ar.com.manflack.desafiospring.domain.service.FlightService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController public class FlightController { @Autowired private FlightService flightService; @GetMapping("/api/v1/flights") public ResponseEntity<?> getAllHotels(@RequestParam(required = false) String dateFrom, @RequestParam(required = false) String dateTo, @RequestParam(required = false) String origin, @RequestParam(required = false) String destination) throws ProvinceNotValidException, DateNotValidException { return new ResponseEntity<>(flightService.getAllFlights(dateFrom, dateTo, origin, destination), HttpStatus.OK); } @PostMapping("/api/v1/flight-reservation") public ResponseEntity<?> makeFlightReservation(@RequestBody FlightReservationRequest request) throws EmailNotValidException, ReservationNotValidException, CardNotProvidedException, FlightSeatTypeNotValidException, DateNotValidException, ProvinceNotValidException, FlightNotAvailableException, InvalidCardDuesException { FlightReservationResponse response = flightService.makeFlightReservation(request.getUserName(), request.getFlightReservation()); response.setStatusCode(new StatusDTO(HttpStatus.OK.value(), "El proceso termino satisfactoriamente")); return new ResponseEntity<>(response, HttpStatus.OK); } }
98930d64979b3705fa2004f4d996ebb3dc46f52f
00e3d3386496339950258f807101d9cc91a179cc
/src/main/java/coffeemachine/view/maintenance/MaintenancePane.java
350134530d03239efb734fe75752886999aa5b5b
[]
no_license
elliass/coffee-machine-gui
2b59e345c7c0627b9da08f1d613b15660c2e8e23
acdf1b55e54769cded5beed671231976065a72d3
refs/heads/master
2023-08-03T22:25:27.502664
2021-09-12T20:30:11
2021-09-12T20:30:11
400,745,543
0
0
null
null
null
null
UTF-8
Java
false
false
1,988
java
package coffeemachine.view.maintenance; import coffeemachine.view.BottomPane; import coffeemachine.view.LeftPane; import coffeemachine.view.RightPane; import coffeemachine.view.TopPane; import javafx.geometry.Insets; import javafx.scene.layout.BorderPane; public class MaintenancePane extends BorderPane { private LeftPane leftPane = null; private RightPane rightPane = null; private MaintenanceScreenPane screenPane = null; private TopPane topPane = null; private BottomPane bottomPane = null; public MaintenancePane() { initPane(); } private void initPane() { this.setLeft(getLeftPane()); this.setRight(getRightPane()); this.setCenter(getScreenPane()); this.setTop(getTopPane()); this.setBottom(getBottomPane()); this.setPrefHeight(300); this.setPrefWidth(850); this.setMargin(screenPane, new Insets(10)); this.setPadding(new Insets(5)); } private LeftPane getLeftPane() { if (leftPane == null) { leftPane = new LeftPane(); leftPane.disableAllBtnExceptBack(); } return leftPane; } private RightPane getRightPane() { if (rightPane == null) { rightPane = new RightPane(); rightPane.disableAllBtnForMaintenance(); } return rightPane; } private MaintenanceScreenPane getScreenPane() { if (screenPane == null) { screenPane = MaintenanceScreenPane.getInstance(); } return screenPane; } private TopPane getTopPane() { if (topPane == null) { topPane = new TopPane(); topPane.disableAllDrinkBtn(); topPane.disableBtn0(); } return topPane; } private BottomPane getBottomPane() { if (bottomPane == null) { bottomPane = new BottomPane(); bottomPane.disableAllBtn(); } return bottomPane; } }
0f567fc6ba179d1f43fd32b44f46841648e03582
469f11a4fd4d9e856e180e2dea15fb6bf34d591f
/src/main/java/lesson2/sort/CocktailSort.java
a369c7d7eebffb0702af08af96cb945a231738f1
[]
no_license
shuricans/ads-java_021021
e6d1a07fcb7fce54cf3a5238173800a399d573ac
feb37259d08b12ff57ee6087e1eb0a18c13c1090
refs/heads/master
2023-08-27T10:44:07.037902
2021-10-30T14:24:49
2021-10-30T14:24:49
413,133,070
0
0
null
2021-10-30T14:24:50
2021-10-03T16:28:33
Java
UTF-8
Java
false
false
1,045
java
package lesson2.sort; public class CocktailSort { public static void sort( Integer[] A ){ boolean swapped; do { swapped = false; for (int i =0; i<= A.length - 2;i++) { if (A[ i ] > A[ i + 1 ]) { //test whether the two elements are in the wrong order int temp = A[i]; A[i] = A[i+1]; A[i+1]=temp; swapped = true; } } if (!swapped) { //we can exit the outer loop here if no swaps occurred. break; } swapped = false; for (int i= A.length - 2;i>=0;i--) { if (A[ i ] > A[ i + 1 ]) { int temp = A[i]; A[i] = A[i+1]; A[i+1]=temp; swapped = true; } } //if no elements have been swapped, then the list is sorted } while (swapped); } }
[ "XN}O81Q.&AYX48F6^,@lbzo1xfiQMW,8KEP!^U'hg;~NtcB~" ]
XN}O81Q.&AYX48F6^,@lbzo1xfiQMW,8KEP!^U'hg;~NtcB~
6274d7b25306e8290c7fdec426dc8bd0b8b11b72
1235df5613a76c0869d244f7607acdb37ca54bc6
/version1/version1.3/AverageTemperature3.java
c2512c6a32727e3a42cdc4d88351dd6313952025
[]
no_license
furkan-ozbudak/weather-stats
7871c0d28d636e48d578b0a5e2bfd2557b10b7ea
e71263e6152f475b9723baaea3b9a03ebc9b62a0
refs/heads/master
2022-12-28T16:41:10.796944
2020-10-18T21:00:47
2020-10-18T21:00:47
305,194,630
0
0
null
null
null
null
UTF-8
Java
false
false
3,574
java
package AverageTemperature3; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.DoubleWritable; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; public class AverageTemperature3 extends Configured implements Tool { public static class AverageTemperatureMapper extends Mapper<LongWritable, Text, Text, Pair> { private HashMap<Text, Pair> map; private final static IntWritable one = new IntWritable(1); @Override protected void setup(Context context) throws IOException, InterruptedException { map = new HashMap<>(); } @Override public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { Text year = new Text(value.toString().substring(15, 19)); double t = ((Double.parseDouble(value.toString().substring(87, 92))) / 10.0); if (map.containsKey(year)) { Pair p = map.get(year); map.put(year, new Pair( new DoubleWritable(p.getSum().get() + t), new IntWritable(p.getCount().get() + 1))); } else { map.put(year, new Pair(new DoubleWritable(t), one)); } } @Override protected void cleanup(Context context) throws IOException, InterruptedException { for (Map.Entry<Text, Pair> e : map.entrySet()) { context.write(e.getKey(), e.getValue()); } } } public static class AverageTemperatureReducer extends Reducer<Text, Pair, Text, DoubleWritable> { private final static DoubleWritable averageTemperature = new DoubleWritable(); @Override public void reduce(Text key, Iterable<Pair> values, Context context) throws IOException, InterruptedException { double sum = 0; int count = 0; for (Pair pair : values) { sum += pair.getSum().get(); count += pair.getCount().get(); } averageTemperature.set(sum / count); context.write(key, averageTemperature); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); int res = ToolRunner.run(conf, new AverageTemperature3(), args); System.exit(res); } @Override public int run(String[] args) throws Exception { FileSystem fs = FileSystem.get(new Configuration()); fs.delete(new Path(args[2]), true); Job job = new Job(getConf(), "AverageTemperature"); job.setJarByClass(AverageTemperature3.class); job.setMapperClass(AverageTemperatureMapper.class); job.setReducerClass(AverageTemperatureReducer.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(Pair.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(DoubleWritable.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); FileInputFormat.addInputPath(job, new Path(args[1])); FileOutputFormat.setOutputPath(job, new Path(args[2])); return job.waitForCompletion(true) ? 0 : 1; } }
4a6b2d8e71fe04a3e8a482194569797a1dd40666
69ada1084b7e1d573825f980a0d9cb66a3847cdc
/DAD1-2/REVISÃO_04/src/MainConcurso.java
fc8480dd112e16c2bb61c82e4d452dd6bcae4306
[]
no_license
Streit1/Estruturas-de-Dados
b59cc5e0909c6a05c26ae59ecd59e8de3590abab
7b6853ea75f09d568a5d33e6255e642816dec9e0
refs/heads/master
2020-03-22T15:45:55.709089
2019-08-02T14:05:49
2019-08-02T14:05:49
140,276,377
0
0
null
null
null
null
ISO-8859-1
Java
false
false
1,418
java
/* * Fazer um programa que: * a) leia o número de inscrição, altura e peso das moças inscritas em um concurso de beleza (utilize flag adequada para encerrar a leitura); * b) calcule e imprima as moças aprovadas para o concurso, ou seja, as moças com IMC inferior a 18. IMC = índice de massa corporal (peso / altura2). */ import javax.swing.*; public class MainConcurso {//ini class MainConcurso public static void main(String[] args) {//ini Main() Concurso conc[] = new Concurso[2]; Concurso obj = new Concurso(); int op = -1; do { op = Menu(); switch(op){ case 1: obj.leitura(conc); break; case 2: obj.calcula(conc); break; } }while (op >0); }//fim Main() public static int Menu() {// menu() int op = -1 ; do { try { op = Integer.parseInt(JOptionPane.showInputDialog("BEM VINDO AO CONCURSO!\n" + "DIGITE A OPÇÃO DESEJADA!\n" + "1-PARA SE INSCREVER\n" + "2-PARA IMPRIMIR DADOS DAS CANDIDATAS CADASTRADAS\n\n" + "DIGITE 0 (ZERO) PARA SAIR")); if(op>2) { JOptionPane.showMessageDialog(null, "DIGITE UMA OPÇÃO VÁLIDA!"); } }catch(NumberFormatException e) { JOptionPane.showMessageDialog(null, " DIGITE UMA OPÇÃO VÁLIDA!\n\nPARA EVITAR O ERRO: " + e + "!"); } }while(op < 0 || op >2 ); return op; }//fim menu() }//fim class MainConcurso
9eaa5b262f5a7ba7379daa2ecf1ec14991b7e2fc
d503dd16ac738110d82a8f469d2fc65ea3065113
/spring-demo-annotations/src/com/katsa/springdemo/RandomFortuneService.java
3d8aef342ae560887a0062887bb7ef878a31d710
[]
no_license
katsa9/spring-learning
e9463db83be815d8a9744ba92dbe8a2c55146ce9
308dad77f5452f3f0d8d8955f1aba2c7bfef95eb
refs/heads/master
2020-03-08T19:42:34.341613
2019-01-23T11:56:32
2019-01-23T11:56:32
128,361,658
0
0
null
null
null
null
UTF-8
Java
false
false
502
java
package com.katsa.springdemo; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.springframework.stereotype.Component; @Component public class RandomFortuneService implements FortuneService{ private List<String> fortunes = new ArrayList<>(); public RandomFortuneService() { fortunes.add("Fortune 1"); fortunes.add("Fortune 2"); fortunes.add("Fortune 3"); } @Override public String getFortune() { return fortunes.get(new Random().nextInt(3)); } }
b5d9d5027022e3b5da7a2b04933b65c77b0d29f8
3e73a70cc1c06f081383b777a8412e3f0c12e534
/novelSearch/src/searchEngines/crawl/abstracts/AbstractGetChapterContent.java
f41040d28a9ad32597a5be238d2bfc6cc81085d8
[]
no_license
foreverSFJ/searchEngines
4c7bed53102567c35fd9a3bb0f5761e79b32d0f0
ffa24291b7afcc627d3882f8dd56bf14f221a898
refs/heads/master
2020-04-17T02:38:46.513267
2019-06-12T01:49:50
2019-06-12T01:49:50
166,145,993
0
0
null
null
null
null
UTF-8
Java
false
false
2,548
java
package searchEngines.crawl.abstracts; import java.util.Map; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import searchEngines.entitys.ChapterContent; import searchEngines.exclusive.NovelSiteEnum; import searchEngines.interfaces.IChapterGetContent; import searchEngines.utils.PraseRules; public abstract class AbstractGetChapterContent extends AbstractGetHTML implements IChapterGetContent { @Override public ChapterContent getChapterContent(String url) { try { String html = super.crawl(url); //处理源网页代码中的字符 html = html.replace("&nbsp;&nbsp;", "&emsp;").replace("<br />\r\n" + "<br />\r\n", "${line}").replace("<br/><br/>", "${line}").replace("<br/>", "${line}").replace("<br />", "${line}"); Document doc = Jsoup.parse(html); doc.setBaseUri(url); PraseRules prase = new PraseRules(); //使用url获得选择器 Map<String, String> contexts = prase.getContext(url); //使用枚举获得 选择器 // Map<String, String> contexts = PraseRules.getContext(NovelSiteEnum.getEnumByUrl(url)); ChapterContent chapterContent = new ChapterContent(); //获取章节名称 String titleSelector = contexts.get("chapter-content-title-selector"); String[] splits = titleSelector.split("\\,"); splits = parseSelector(splits); chapterContent.setTitle(doc.select(splits[0]).get(Integer.parseInt(splits[1])).text()); //获取章节内容 String contentSelector = contexts.get("chapter-content-content-selector"); chapterContent.setContent(doc.select(contentSelector).first().text().replace("${line}", "\n")); //获取上一章地址 String prevSelector = contexts.get("chapter-content-prev-selector"); splits = prevSelector.split("\\,"); splits = parseSelector(splits); chapterContent.setPrev(doc.select(splits[0]).get(Integer.parseInt(splits[1])).absUrl("href")); //获取下一章地址 String nextSelector = contexts.get("chapter-content-next-selector"); splits = nextSelector.split("\\,"); splits = parseSelector(splits); chapterContent.setNext(doc.select(splits[0]).get(Integer.parseInt(splits[1])).absUrl("href")); //返回这个章节实体 return chapterContent; }catch (Exception e) { throw new RuntimeException(e); } } /** * 处理下标 */ private String[] parseSelector(String[] splits) { String[] newSplits = new String[2]; if (splits.length == 1) { newSplits[0] = splits[0]; newSplits[1] = "0"; return newSplits; } else { return splits; } } }
d5ce404f530134367003050b991131be62bcb8db
93f3578669fb0d0030a550316aebe0d7b4221631
/rpc-supplychain-jxc/src/main/java/cn/com/glsx/supplychain/jxc/mapper/STKMerchantStockMapper.java
0dea3d37ffdee6c3e41bfba641ca90544fdd4b2e
[]
no_license
shanghaif/supplychain
4d7de62809b6c88ac5080a85a77fc4bf3d856db8
c36c771b0304c5739de98bdfc322c0082a9e523d
refs/heads/master
2023-02-09T19:01:35.562699
2021-01-05T09:39:11
2021-01-05T09:39:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
579
java
package cn.com.glsx.supplychain.jxc.mapper; import org.apache.ibatis.annotations.Mapper; import org.oreframework.datasource.mybatis.mapper.OreMapper; import com.github.pagehelper.Page; import cn.com.glsx.supplychain.jxc.dto.STKMerchantStockDTO; import cn.com.glsx.supplychain.jxc.model.STKMerchantStock; import java.util.List; @Mapper public interface STKMerchantStockMapper extends OreMapper<STKMerchantStock>{ public Page<STKMerchantStockDTO> pageMerchantStock(STKMerchantStock record); public List<STKMerchantStockDTO> exportMerchantStock(STKMerchantStock record); }
a29fbe2c10aa897dcd937f5edb75b117ae929b2c
e778d3dc3f88049dbd989f213458eefabbd1f241
/leecode/字符串/FindRepeatedDnaSequences.java
375310de4ac1da9d67c4010f36ce4016ba63f0b2
[]
no_license
JornShen/algorithmn
cc5071f1c7b0dad5dd8866058ea83c74f77077d5
745b732f811c8b8e3bd686c4e4cacaf4f0e5478b
refs/heads/master
2021-01-24T18:58:46.848732
2018-03-22T07:48:10
2018-03-22T07:48:10
86,165,441
1
0
null
null
null
null
UTF-8
Java
false
false
3,149
java
/* leetcode 187. Repeated DNA Sequences All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T, for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA. Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. For example, Given s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT", Return: ["AAAAACCCCC", "CCCCCAAAAA"]. */ // 思路基本相同, 但是映射的空间需要还可以优化 class Solution { public List<String> findRepeatedDnaSequences(String s) { Set<String> pool = new HashSet<>(); Set<String> set = new HashSet<>(); for (int i = 10, j = 0; i <= s.length(); i++, j++) { String tmp = s.substring(j, i); if (pool.contains(tmp)) set.add(tmp); else pool.add(tmp); } return new ArrayList<>(set); } } // 普遍的做法, 看不太懂 class Solution{//11ms public List<String> findRepeatedDnaSequences(String s){ List<String> res = new ArrayList<>(); if (s == null || s.length() < 10) { return res; } //对字母进行编码 char[] map = new char[256]; map['A'] = 0; map['C'] = 1; map['G'] = 2; map['T'] = 3; int mask = 0xfffff; //20bit,10个字母,每个字母占2bit int val = 0; char[] schar = s.toCharArray(); for (int i = 0;i < 9 ;i ++ ) {//对前9位进行编码 val = (val << 2) | (map[schar[i]] & 3); } byte[] bytes = new byte[1 << 20]; // 设置映射集合 for (int i = 9; i < schar.length; i++) { val = ((val << 2) & mask) | ((map[schar[i]]) & 3);//编码 if (bytes[val] == 1) { res.add(String.valueOf(schar,i - 9,10)); } if (bytes[val] < 2) { bytes[val]++; } } return res; } } // 另一种 更清晰的做法 // 四个字母用两位就能表示, 十个字符就只需要用 20 个字符进行表示 public class Solution { public List<String> findRepeatedDnaSequences(String s) { List<String> res = new ArrayList<String>(); if(s == null || s.length() < 11) return res; int hash = 0; Map<Character, Integer> map = new HashMap<Character, Integer>(); map.put('A', 0); map.put('C', 1); map.put('G', 2); map.put('T', 3); Set<Integer> set = new HashSet<Integer>(); // 只出现一次 for(int i = 0; i < s.length(); i++) { char c = s.charAt(i); if(i < 9) hash = (hash << 2) + map.get(c); else { hash = (hash << 2) + map.get(c); hash &= (1 << 20) - 1; // 取后二十位 if(set.contains(hash)) res.add(s.substring(i - 9, i + 1)); else set.add(hash); } } return res; } }
2160889241f6d43c01cc5fcebb0360171828688c
c19cb77e3958a194046d6f84ca97547cc3a223c3
/core/src/main/java/org/bouncycastle/crypto/prng/drbg/Utils.java
f7a41176e49e9be4c16e3d83868f8599d596fb0c
[ "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
bcgit/bc-java
1b6092bc5d2336ec26ebd6da6eeaea6600b4c70a
62b03c0f704ebd243fe5f2d701aef4edd77bba6e
refs/heads/main
2023-09-04T00:48:33.995258
2023-08-30T05:33:42
2023-08-30T05:33:42
10,416,648
1,984
1,021
MIT
2023-08-26T05:14:28
2013-06-01T02:38:42
Java
UTF-8
Java
false
false
3,203
java
package org.bouncycastle.crypto.prng.drbg; import java.util.Hashtable; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.Mac; import org.bouncycastle.util.Integers; class Utils { static final Hashtable maxSecurityStrengths = new Hashtable(); static { maxSecurityStrengths.put("SHA-1", Integers.valueOf(128)); maxSecurityStrengths.put("SHA-224", Integers.valueOf(192)); maxSecurityStrengths.put("SHA-256", Integers.valueOf(256)); maxSecurityStrengths.put("SHA-384", Integers.valueOf(256)); maxSecurityStrengths.put("SHA-512", Integers.valueOf(256)); maxSecurityStrengths.put("SHA-512/224", Integers.valueOf(192)); maxSecurityStrengths.put("SHA-512/256", Integers.valueOf(256)); } static int getMaxSecurityStrength(Digest d) { return ((Integer)maxSecurityStrengths.get(d.getAlgorithmName())).intValue(); } static int getMaxSecurityStrength(Mac m) { String name = m.getAlgorithmName(); return ((Integer)maxSecurityStrengths.get(name.substring(0, name.indexOf("/")))).intValue(); } /** * Used by both Dual EC and Hash. */ static byte[] hash_df(Digest digest, byte[] seedMaterial, int seedLength) { // 1. temp = the Null string. // 2. . // 3. counter = an 8-bit binary value representing the integer "1". // 4. For i = 1 to len do // Comment : In step 4.1, no_of_bits_to_return // is used as a 32-bit string. // 4.1 temp = temp || Hash (counter || no_of_bits_to_return || // input_string). // 4.2 counter = counter + 1. // 5. requested_bits = Leftmost (no_of_bits_to_return) of temp. // 6. Return SUCCESS and requested_bits. byte[] temp = new byte[(seedLength + 7) / 8]; int len = temp.length / digest.getDigestSize(); int counter = 1; byte[] dig = new byte[digest.getDigestSize()]; for (int i = 0; i <= len; i++) { digest.update((byte)counter); digest.update((byte)(seedLength >> 24)); digest.update((byte)(seedLength >> 16)); digest.update((byte)(seedLength >> 8)); digest.update((byte)seedLength); digest.update(seedMaterial, 0, seedMaterial.length); digest.doFinal(dig, 0); int bytesToCopy = ((temp.length - i * dig.length) > dig.length) ? dig.length : (temp.length - i * dig.length); System.arraycopy(dig, 0, temp, i * dig.length, bytesToCopy); counter++; } // do a left shift to get rid of excess bits. if (seedLength % 8 != 0) { int shift = 8 - (seedLength % 8); int carry = 0; for (int i = 0; i != temp.length; i++) { int b = temp[i] & 0xff; temp[i] = (byte)((b >>> shift) | (carry << (8 - shift))); carry = b; } } return temp; } static boolean isTooLarge(byte[] bytes, int maxBytes) { return bytes != null && bytes.length > maxBytes; } }
7a6d9924bfbfc39ef6c4ab8f6f751c6d52abfc02
0af8b92686a58eb0b64e319b22411432aca7a8f3
/large-multiproject/project76/src/main/java/org/gradle/test/performance76_2/Production76_179.java
9b43862bad2fd284b96286e936a7081e734ca76a
[]
no_license
gradle/performance-comparisons
b0d38db37c326e0ce271abebdb3c91769b860799
e53dc7182fafcf9fedf07920cbbea8b40ee4eef4
refs/heads/master
2023-08-14T19:24:39.164276
2022-11-24T05:18:33
2022-11-24T05:18:33
80,121,268
17
15
null
2022-09-30T08:04:35
2017-01-26T14:25:33
null
UTF-8
Java
false
false
305
java
package org.gradle.test.performance76_2; public class Production76_179 extends org.gradle.test.performance16_2.Production16_179 { private final String property; public Production76_179() { this.property = "foo"; } public String getProperty() { return property; } }
503f254215e1863507183c2369d31e57d52e8dd1
fcfcff20212d60821b437110729a5acda3d513bb
/ExcleToFirebase/src/com/rubbersoft/FirebaseDataSender.java
770c2982440ffcca4a34eaff9b8ff04f63c8d0ba
[]
no_license
faiz636/Valve-Leakage
cf6b29d5d443d14d7e13b974981c9872c1d46db1
5bf336760d6c27693812277f7ec80c08aadaddc1
refs/heads/master
2021-01-12T21:45:06.999747
2016-01-17T08:03:31
2016-01-17T08:03:31
44,426,415
0
0
null
null
null
null
UTF-8
Java
false
false
8,471
java
package com.rubbersoft; import com.firebase.client.AuthData; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.rubbersoft.model.SheetData; import com.rubbersoft.model.SheetRow; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Iterator; import java.util.Map; /** * Created by Faiz on 23/12/2015. */ public class FirebaseDataSender { //address of firebase databse private static final String FIREBASE_URL = "https://incandescent-torch-9709.firebaseio.com/"; private boolean mWait;//flag for wait operation private static Firebase mRootRef;//usable root reference for firebase database private static AuthData mUserAuth;//authentication data from firebase private ArrayList<SheetData> sheetDataList;//list of sheet data to be send private String threadName;//name of running instance private static int runCounter;//to check which run it is static { mRootRef = new Firebase(FIREBASE_URL);//create firebase root reference } public FirebaseDataSender(ArrayList<SheetData> sheetDataList) { this.sheetDataList = sheetDataList;//save data base object this.mWait = true; run();//start necessary operation } public void run() { threadName = "FirebaseDataSender-"+runCounter++;//set name of running instance and counter checkForInterNetConnection();//check for internet connection if (mUserAuth==null){//login if not authenticated loginUser("[email protected]", "123"); } sendData();//send data to firebase } /** * wait for internet connection until available */ private void checkForInterNetConnection() {//check for internet connection(connection with google server :) while (!netIsAvailable()) { printMessage("Internet Connection Not Available, Retrying In 5 sec..."); try { Thread.sleep(1000);//wait for second } catch (InterruptedException e) { e.printStackTrace(); } } printMessage("Internet Available, proceeding..."); } /** * authenticate with firebase database * * @param email user email * @param pass user password * */ public synchronized void loginUser(String email, String pass) { if(mUserAuth!=null) return;//if already login mWait = true; printMessage("logging in user"); //authenticate with email and password mRootRef.authWithPassword(email, pass, new Firebase.AuthResultHandler() { @Override public void onAuthenticated(AuthData authData) {//firebase response if authentication is success printMessage("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider()); FirebaseDataSender.mUserAuth = authData; mWait = false; } @Override public void onAuthenticationError(FirebaseError firebaseError) {//firebase response if not unsuccessful // there was an error processErrorCode(firebaseError); mWait = false; } }); waitToCompleteOperation("waiting for user to login");//wait for login complete printMessage("user logged in"); } /** * try to connect google * * @return true if connection is established else false */ private static boolean netIsAvailable() { try { final URL url = new URL("http://www.google.com");//make a url final URLConnection conn = url.openConnection();//obtain a connection with url conn.connect();//connect with setver return true;//will reach here only if connection is establish } catch (MalformedURLException e) { //this exception will occur if url is incorrect throw new RuntimeException(e); } catch (IOException e) { return false; } } /** * Send data to firebase passed to this thread. * Each data item will be sent to firebase separately * then waits for its completion. * After completion next item in the collection will be sent */ private void sendData() { final int[] wait = {0};//waiting counter in array for (int i = 0; i < 4; i++) {//loop for sheet int j=0; ArrayList<SheetRow> list = sheetDataList.get(i).getAllRows(); printMessage("sending node " + (i + 1) + " data, size : " + list.size()); for (SheetRow item : list) {//loop for rows wait[0]++;//increase wile sending data System.out.println(" ------------> sending : "+ j++); //get firebase data SheetRow.FirebaseData data = new SheetRow.FirebaseData(item); //send data to firebase mRootRef.child("node" + (i + 1)).push().setValue(data, new Firebase.CompletionListener() { @Override public void onComplete(FirebaseError firebaseError, Firebase firebase) {//response for data sent if (firebaseError == null) { printMessage("row sent"); } else { processErrorCode(firebaseError); } mWait = --wait[0] > 0;//decrement wait counter and update wait flag } }); } printMessage("All rows sent"); } mWait = wait[0] > 0; waitToCompleteOperation("data sent waiting for acknowledgement");//wait for data to be sent printMessage("All nodes data sent"); } /** * Wait to complete operation from where it is called * when calling operation is completed * wait flag would be set to false */ public void waitToCompleteOperation(String s) { int i = 0; while (mWait) {//if wait is enable try { printMessage(s + "--" + i++); Thread.sleep(500);//wait for 500 ms if (!netIsAvailable()) { printMessage("Connection Lost"); } } catch (InterruptedException e) { e.printStackTrace(); } } printMessage("waiting end"); } //print formatted data private void printMessage(String message){ System.out.println(threadName + "--" + message); } /** * process error code received from firebase */ public void processErrorCode(FirebaseError firebaseError) { if (firebaseError == null) { return; } printMessage("processing error code:" + firebaseError); switch (firebaseError.getCode()) { case FirebaseError.AUTHENTICATION_PROVIDER_DISABLED: printMessage("AUTHENTICATION_PROVIDER_DISABLED"); break; case FirebaseError.DISCONNECTED: printMessage("DISCONNECTED"); break; case FirebaseError.DENIED_BY_USER: printMessage("DENIED_BY_USER"); break; case FirebaseError.EMAIL_TAKEN: printMessage("EMAIL_TAKEN"); break; case FirebaseError.INVALID_AUTH_ARGUMENTS: printMessage("INVALID_AUTH_ARGUMENTS"); break; case FirebaseError.INVALID_EMAIL: printMessage("INVALID_EMAIL"); break; case FirebaseError.EXPIRED_TOKEN: printMessage("EXPIRED_TOKEN"); break; case FirebaseError.PERMISSION_DENIED: printMessage("PERMISSION_DENIED"); break; case FirebaseError.INVALID_PASSWORD: printMessage("INVALID_PASSWORD"); break; case FirebaseError.INVALID_CREDENTIALS: printMessage("INVALID_CREDENTIALS"); break; case FirebaseError.INVALID_CONFIGURATION: printMessage("INVALID_CONFIGURATION"); break; case FirebaseError.NETWORK_ERROR: printMessage("NETWORK_ERROR"); break; } } }
e8371cbb4335e48b1df966438626faea48548250
feed898abc082458f0c2e1c2f3b266923c803347
/chapter_008/src/test/java/ru/job4j/servlets/ajax/PersonTest.java
0d611694b655ee5cfc1bd62d08d7bef553e03ec0
[ "Apache-2.0" ]
permissive
Zhekbland/job4j
c256466c72b417e437c6b304750438d4c5737daf
118ff2565f1b44498faa47e5143606607700d5c6
refs/heads/master
2022-11-28T08:51:45.943457
2020-04-19T09:14:45
2020-04-19T09:14:45
137,885,095
1
0
Apache-2.0
2022-11-16T12:23:57
2018-06-19T11:55:31
Java
UTF-8
Java
false
false
727
java
package ru.job4j.servlets.ajax; import org.junit.Test; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; public class PersonTest { @Test public void createPerson() { Person person = new Person(1, "Inna", "Inna", "female", "person"); person.setId(2); person.setName("Petr"); person.setSurname("Ars"); person.setGender("male"); person.setDescription("developer"); assertThat(person.getId(), is(2)); assertThat(person.getName(), is("Petr")); assertThat(person.getSurname(), is("Ars")); assertThat(person.getGender(), is("male")); assertThat(person.getDescription(), is("developer")); } }
56b6ba4802bd62deef9da6ac8c7d6d94269c4caa
58df55b0daff8c1892c00369f02bf4bf41804576
/src/fok.java
f6fee62aa44be5ea82332911938010d251ec2eca
[]
no_license
gafesinremedio/com.google.android.gm
0b0689f869a2a1161535b19c77b4b520af295174
278118754ea2a262fd3b5960ef9780c658b1ce7b
refs/heads/master
2020-05-04T15:52:52.660697
2016-07-21T03:39:17
2016-07-21T03:39:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
267
java
import java.util.Date; public final class fok extends ffn implements ffi<Date> { public fok(String paramString) { super(paramString, 4300000); } } /* Location: * Qualified Name: fok * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
ff2d5e97ff4e8e9a419ed30e38954abbe9998146
76600a8112c9bc05af7e98fff943f96dbf6443bd
/core/tags/MYRMIDON_PRE_CONF_MUNGE/proposal/myrmidon/src/java/org/apache/antlib/vfile/DefaultFileSet.java
e8cbf469bdafedef9bd82081b441e208d6ad192d
[]
no_license
BeatrizTercero/repoSvnAnt
222a360bc83cdcde6fb6ab60c2a5962320a4b607
326ec26c2e5d7bbaedfd4d33a85c7a87773864be
refs/heads/master
2021-01-11T10:06:10.493081
2016-12-17T19:36:24
2016-12-17T19:36:24
77,481,221
0
0
null
null
null
null
UTF-8
Java
false
false
3,507
java
/* * Copyright (C) The Apache Software Foundation. All rights reserved. * * This software is published under the terms of the Apache Software License * version 1.1, a copy of which has been included with this distribution in * the LICENSE.txt file. */ package org.apache.antlib.vfile; import java.util.ArrayList; import org.apache.antlib.vfile.selectors.AndFileSelector; import org.apache.antlib.vfile.selectors.FileSelector; import org.apache.aut.vfs.FileObject; import org.apache.aut.vfs.FileSystemException; import org.apache.aut.vfs.FileType; import org.apache.avalon.excalibur.i18n.ResourceManager; import org.apache.avalon.excalibur.i18n.Resources; import org.apache.myrmidon.api.TaskContext; import org.apache.myrmidon.api.TaskException; /** * A file set, that contains those files under a directory that match * a set of selectors. * * @author <a href="mailto:[email protected]">Adam Murdoch</a> * * @ant:data-type name="v-fileset" * @ant:type type="v-fileset" name="v-fileset" */ public class DefaultFileSet implements FileSet { private final static Resources REZ = ResourceManager.getPackageResources( DefaultFileSet.class ); private FileObject m_dir; private final AndFileSelector m_selector = new AndFileSelector(); /** * Sets the root directory. */ public void setDir( final FileObject dir ) { m_dir = dir; } /** * Adds a selector. */ public void add( final FileSelector selector ) { m_selector.add( selector ); } /** * Returns the contents of the set. */ public FileSetResult getResult( final TaskContext context ) throws TaskException { if( m_dir == null ) { final String message = REZ.getString( "fileset.dir-not-set.error" ); throw new TaskException( message ); } try { final DefaultFileSetResult result = new DefaultFileSetResult(); final ArrayList stack = new ArrayList(); final ArrayList pathStack = new ArrayList(); stack.add( m_dir ); pathStack.add( "" ); while( stack.size() > 0 ) { // Pop next folder off the stack FileObject folder = (FileObject)stack.remove( 0 ); String path = (String)pathStack.remove( 0 ); // Queue the children of the folder FileObject[] children = folder.getChildren(); for( int i = 0; i < children.length; i++ ) { FileObject child = children[ i ]; String childPath = path + child.getName().getBaseName(); // Check whether to include the file in the result if( m_selector.accept( child, childPath, context ) ) { result.addElement( child, childPath ); } if( child.getType() == FileType.FOLDER ) { // A folder - push it on to the stack stack.add( 0, child ); pathStack.add( 0, childPath + '/' ); } } } return result; } catch( FileSystemException e ) { final String message = REZ.getString( "fileset.list-files.error", m_dir ); throw new TaskException( message, e ); } } }
[ "(no author)@13f79535-47bb-0310-9956-ffa450edef68" ]
(no author)@13f79535-47bb-0310-9956-ffa450edef68
44441cc211103fd74b1b3e628848fcc3cff974ba
1bd1e6d31c01afbe9cb7b0ed54226f354ec2514f
/HelloWorld.java
d9d1b7835ac803efff87789d20c565481ad452a4
[]
no_license
MooniDeer/test
6d96cdb3486311e4c05854d11e9b47491f725687
f66bf59e04c96dd66c87c21c40aa30cb09eabadc
refs/heads/main
2022-12-27T11:03:44.469473
2020-10-12T17:58:06
2020-10-12T17:58:06
303,465,171
0
0
null
null
null
null
UTF-8
Java
false
false
136
java
package test; public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World !"); } }
63265340e053dd970e6d2c823442090fbcdd1952
74e94b19b8a9748558bbaa2b86d4e7c6db835e2f
/core/common/src/main/java/com/comcast/redirector/api/model/Warning.java
deb2606de231e06e462e67f34d861925b0db2af5
[ "Apache-2.0" ]
permissive
Comcast/redirector
b236567e2bae687e0189c2cdc45731dd8c055a1a
6770fe01383bc7ea110c7c8e14c137212ebc0ba1
refs/heads/master
2021-03-27T20:48:38.988332
2019-09-26T08:39:18
2019-09-26T08:39:18
80,451,996
10
13
Apache-2.0
2019-09-26T08:39:19
2017-01-30T18:50:31
Java
UTF-8
Java
false
false
1,227
java
/** * Copyright 2017 Comcast Cable Communications Management, LLC * * 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. * * @author Yuriy Dmitriev ([email protected]) */ package com.comcast.redirector.api.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Warning { @XmlElement(name = "message", required = true) private String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
e92a22f5ff64612f936fff065a881486de2b11ea
ed166738e5dec46078b90f7cca13a3c19a1fd04b
/minor/guice-OOM-error-reproduction/src/main/java/gen/S_Gen101.java
76a53dc04fc532d9abfcc922cb3cfd409cfff214
[]
no_license
michalradziwon/script
39efc1db45237b95288fe580357e81d6f9f84107
1fd5f191621d9da3daccb147d247d1323fb92429
refs/heads/master
2021-01-21T21:47:16.432732
2016-03-23T02:41:50
2016-03-23T02:41:50
22,663,317
2
0
null
null
null
null
UTF-8
Java
false
false
331
java
package gen; public class S_Gen101 { @com.google.inject.Inject public S_Gen101(S_Gen102 s_gen102){ System.out.println(this.getClass().getCanonicalName() + " created. " + s_gen102 ); } @com.google.inject.Inject public void injectInterfaceWithoutImpl(gen.InterfaceWithoutImpl i){} // should expolode :) }
c02ba3fc1253d1d341c574187a7ee2ea51cd57a4
ffc7c75291c4799ba7812731df1f9133cdd5d069
/app/src/main/java/com/example/mobihealthtest/ChildFragment.java
564dfd5cbc267b4b650298be901e550d42535142
[]
no_license
swapnilshah5889/mobihealthtest
a542add5db6f94cfb3185f95a97403228648da40
3b3535bf5ae6c63b090788cf95a53e0c3e49e9a0
refs/heads/master
2022-03-31T07:41:19.908227
2020-01-31T12:21:56
2020-01-31T12:21:56
236,700,808
0
0
null
null
null
null
UTF-8
Java
false
false
1,162
java
package com.example.mobihealthtest; import android.content.Context; import android.net.Uri; import android.os.Bundle; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.squareup.picasso.Picasso; public class ChildFragment extends Fragment { Context context; public int card; public ImageView img_card; public ChildFragment() { // Required empty public constructor } public ChildFragment(Context context, int card) { this.context = context; this.card = card; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_child, container, false); // Inflate the layout for this fragment img_card = (ImageView) view.findViewById(R.id.img_card); Bundle bundle = getArguments(); Picasso.with(context).load(card).into(img_card); //img_card.setImageResource(card); return view; } }
6ec332d63d7adfbe51d3304666629b5433a5f2a6
ab933e378097a158263efe7c2bc7070f61466dd6
/Server/CS6650Assign3/src/main/java/com/amazonaws/lambda/demo/PostHandler.java
cf2c8576a0c55a6bcba218793db74dc021c8ba21
[]
no_license
OneOneBee/CS6650Assignment3Lambda
91bf1a801687024ec7c4a68fe70b35fa4a8bdbc9
53f7085a5aa5fb8ab443ef210d6b8b85b967b158
refs/heads/master
2020-04-09T09:36:24.005057
2018-12-03T19:05:53
2018-12-03T19:05:53
160,239,576
0
0
null
null
null
null
UTF-8
Java
false
false
1,851
java
package com.amazonaws.lambda.demo; import java.beans.PropertyVetoException; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.util.LinkedHashMap; import com.amazonaws.services.lambda.runtime.Context; import com.amazonaws.services.lambda.runtime.RequestHandler; public class PostHandler implements RequestHandler<Object, String> { public String handleRequest(Object event, Context context) { context.getLogger().log("Input: " + event); LinkedHashMap input = (LinkedHashMap) event; if (input.get("userid") == null || input.get("day") == null || input.get("timeinterval") == null || input.get("stepcount") == null) { return "400 Invalid Input"; } int userid = Integer.parseInt((String)input.get("userid")); int day = Integer.parseInt((String)input.get("day")); int timeinterval = Integer.parseInt((String)input.get("timeinterval")); int stepcount = Integer.parseInt((String)input.get("stepcount")); try { insertData(userid, day, timeinterval, stepcount); } catch (Exception e) { e.printStackTrace(); return "Post failed!"; } return "Post successed!" + userid + "/" + day + "/" + timeinterval + "/" + stepcount; } private void insertData(int userId, int day, int timeInterval, int stepCount) throws IOException, PropertyVetoException { Connection conn = null; try { conn = ConnectionPool.getInstance().getConnection(); Statement stmt = null; stmt = conn.createStatement(); String insertUser = "INSERT IGNORE INTO users(user_id, day_range, time_interval, step_count)" + "VALUES (" + userId + "," + day + "," + timeInterval + "," + stepCount + ")"; stmt.executeUpdate(insertUser); conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
afda0e195d7e7251c8473f01d1fb5c69641fe5e9
1d086a5a6d0174db23ad737cdfc56d54eb2807c4
/src/main/java/buildcraft/api/statements/StatementParameterItemStack.java
1ab387715137d29789c63edae46346187b8c3397
[]
no_license
UniversalRed/RedstoneDistortion
b33e43ebc6d5e7ab9c01a5229d3c35e6830e55c4
a3d868b85d95cd7c522213de78d59da51f7b8a19
refs/heads/master
2021-03-12T23:29:52.627923
2015-02-11T02:15:34
2015-02-11T02:15:34
30,561,566
7
0
null
2015-02-11T02:15:35
2015-02-09T22:15:32
Java
UTF-8
Java
false
false
2,026
java
/** * Copyright (c) 2011-2014, SpaceToad and the BuildCraft Team * http://www.mod-buildcraft.com * * The BuildCraft API is distributed under the terms of the MIT License. * Please check the contents of the license, which should be located * as "LICENSE.API" in the BuildCraft source code distribution. */ package buildcraft.api.statements; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.IIcon; public class StatementParameterItemStack implements IStatementParameter { protected ItemStack stack; @Override public IIcon getIcon() { return null; } @Override public ItemStack getItemStack() { return stack; } @Override public void onClick(IStatementContainer source, IStatement stmt, ItemStack stack, StatementMouseClick mouse) { if (stack != null) { this.stack = stack.copy(); this.stack.stackSize = 1; } } @Override public void writeToNBT(NBTTagCompound compound) { if (stack != null) { NBTTagCompound tagCompound = new NBTTagCompound(); stack.writeToNBT(tagCompound); compound.setTag("stack", tagCompound); } } @Override public void readFromNBT(NBTTagCompound compound) { stack = ItemStack.loadItemStackFromNBT(compound.getCompoundTag("stack")); } @Override public boolean equals(Object object) { if (object instanceof StatementParameterItemStack) { StatementParameterItemStack param = (StatementParameterItemStack) object; return ItemStack.areItemStacksEqual(stack, param.stack) && ItemStack.areItemStackTagsEqual(stack, param.stack); } else { return false; } } @Override public String getDescription() { if (stack != null) { return stack.getDisplayName(); } else { return ""; } } @Override public String getUniqueTag() { return "buildcraft:stack"; } @Override public void registerIcons(IIconRegister iconRegister) { } @Override public IStatementParameter rotateLeft() { return this; } }
9e6a5afb58d6c003f2522aa8ac70234481d802eb
b0e36d0594fbbdcdd8e8cb8392ab03e4547bd57e
/src/main/java/br/com/sisbov/infrastructure/repository/VacinaJpaRepository.java
5486b205c47b420572f76aa24281cc473d56579b
[]
no_license
elvisguarda03/sisbov
fde20a898301d50e88b77b8d7f05848fa138deb8
4d45a4d277bdfc9a543aacd1a8471569568ad04d
refs/heads/master
2022-08-09T12:25:13.672860
2019-10-23T02:16:57
2019-10-23T02:16:57
216,467,518
0
0
null
2022-06-21T02:04:41
2019-10-21T03:11:09
Java
UTF-8
Java
false
false
320
java
package br.com.sisbov.infrastructure.repository; import br.com.sisbov.domain.entity.Vacina; import br.com.sisbov.domain.repository.VacinaRepository; public class VacinaJpaRepository extends BaseJpaRepository<Vacina> implements VacinaRepository { public VacinaJpaRepository() { super(Vacina.class); } }
ba60177cf8964b21c51100be2488de840f328089
8c813be7f92a74d725dda1468d7e26434305e2a2
/src/main/java/org/bian/dto/CRGuidelineComplianceAssessmentRetrieveInputModel.java
ee8d9df09ec82953c291bd60af0c0fb60046023c
[ "Apache-2.0" ]
permissive
bianapis/sd-guideline-compliance-v2.0
039c52616682ffae4f8557f3121b0de963e1abdb
5551866a65e6899b3b733e4e41d3e158d6578471
refs/heads/master
2020-07-11T11:16:01.851530
2019-09-03T11:58:19
2019-09-03T11:58:19
204,524,395
0
0
null
null
null
null
UTF-8
Java
false
false
3,809
java
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.bian.dto.CRGuidelineComplianceAssessmentRetrieveInputModelGuidelineComplianceAssessmentInstanceAnalysis; import org.bian.dto.CRGuidelineComplianceAssessmentRetrieveInputModelGuidelineComplianceAssessmentInstanceReportRecord; import javax.validation.Valid; /** * CRGuidelineComplianceAssessmentRetrieveInputModel */ public class CRGuidelineComplianceAssessmentRetrieveInputModel { private Object guidelineComplianceAssessmentRetrieveActionTaskRecord = null; private String guidelineComplianceAssessmentRetrieveActionRequest = null; private CRGuidelineComplianceAssessmentRetrieveInputModelGuidelineComplianceAssessmentInstanceReportRecord guidelineComplianceAssessmentInstanceReportRecord = null; private CRGuidelineComplianceAssessmentRetrieveInputModelGuidelineComplianceAssessmentInstanceAnalysis guidelineComplianceAssessmentInstanceAnalysis = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The retrieve service call consolidated processing record * @return guidelineComplianceAssessmentRetrieveActionTaskRecord **/ public Object getGuidelineComplianceAssessmentRetrieveActionTaskRecord() { return guidelineComplianceAssessmentRetrieveActionTaskRecord; } public void setGuidelineComplianceAssessmentRetrieveActionTaskRecord(Object guidelineComplianceAssessmentRetrieveActionTaskRecord) { this.guidelineComplianceAssessmentRetrieveActionTaskRecord = guidelineComplianceAssessmentRetrieveActionTaskRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Details of the retrieve action service request (lists requested reports) * @return guidelineComplianceAssessmentRetrieveActionRequest **/ public String getGuidelineComplianceAssessmentRetrieveActionRequest() { return guidelineComplianceAssessmentRetrieveActionRequest; } public void setGuidelineComplianceAssessmentRetrieveActionRequest(String guidelineComplianceAssessmentRetrieveActionRequest) { this.guidelineComplianceAssessmentRetrieveActionRequest = guidelineComplianceAssessmentRetrieveActionRequest; } /** * Get guidelineComplianceAssessmentInstanceReportRecord * @return guidelineComplianceAssessmentInstanceReportRecord **/ public CRGuidelineComplianceAssessmentRetrieveInputModelGuidelineComplianceAssessmentInstanceReportRecord getGuidelineComplianceAssessmentInstanceReportRecord() { return guidelineComplianceAssessmentInstanceReportRecord; } public void setGuidelineComplianceAssessmentInstanceReportRecord(CRGuidelineComplianceAssessmentRetrieveInputModelGuidelineComplianceAssessmentInstanceReportRecord guidelineComplianceAssessmentInstanceReportRecord) { this.guidelineComplianceAssessmentInstanceReportRecord = guidelineComplianceAssessmentInstanceReportRecord; } /** * Get guidelineComplianceAssessmentInstanceAnalysis * @return guidelineComplianceAssessmentInstanceAnalysis **/ public CRGuidelineComplianceAssessmentRetrieveInputModelGuidelineComplianceAssessmentInstanceAnalysis getGuidelineComplianceAssessmentInstanceAnalysis() { return guidelineComplianceAssessmentInstanceAnalysis; } public void setGuidelineComplianceAssessmentInstanceAnalysis(CRGuidelineComplianceAssessmentRetrieveInputModelGuidelineComplianceAssessmentInstanceAnalysis guidelineComplianceAssessmentInstanceAnalysis) { this.guidelineComplianceAssessmentInstanceAnalysis = guidelineComplianceAssessmentInstanceAnalysis; } }
a5b31f879a11033385110609f9692ed0ab96b86b
64d0a842230928c4881ffbd7f918f6e2c1ed4c1f
/tq.java.spring.jie.mi/src/main/java/_5_transaction/_20_spring_transaction_manage/PrototypeTransactionInterceptor.java
e0bd688e7a5968d0ea732d62da8042f9a8bc179c
[]
no_license
t734070824/tq.java
358c2948a20690139ba1e6fab663143023b4f577
5034531e63083bbc496d59fa7332c0f07d0221d8
refs/heads/master
2022-12-20T22:43:50.995285
2020-10-13T01:35:17
2020-10-13T01:35:17
110,670,183
1
2
null
2022-12-16T00:03:45
2017-11-14T09:36:24
Java
UTF-8
Java
false
false
1,759
java
package _5_transaction._20_spring_transaction_manage; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; import org.springframework.transaction.TransactionStatus; import java.lang.reflect.Method; /** * @author [email protected] * @date 2018/4/16 14:53 */ public class PrototypeTransactionInterceptor implements MethodInterceptor{ private PlatformTransactionManager transactionManager; @Override public Object invoke(MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); TransactionDefinition definition = getTransactionDefinitionByMethod(method); TransactionStatus txStatus = transactionManager.getTransaction(definition); Object result = null; try{ result = invocation.proceed(); } catch (Throwable e){ if(needRollbackOn(e)){ transactionManager.rollback(txStatus); }else { transactionManager.commit(txStatus); } throw e; } transactionManager.commit(txStatus); return result; } private boolean needRollbackOn(Throwable e) { return false; } private TransactionDefinition getTransactionDefinitionByMethod(Method method) { //TODO 实现细节 return null; } public PlatformTransactionManager getTransactionManager() { return transactionManager; } public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } }
2b10ee290f51e1a099a799a6e2b3cd6d5d69ac16
c2745516073be0e243c2dff24b4bb4d1d94d18b8
/sdk/resourcemanager/azure-resourcemanager-network/src/main/java/com/azure/resourcemanager/network/fluent/ConnectionMonitorsClient.java
01278643b892043fc6a53e87434d0fb72c2823e8
[ "MIT", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "CC0-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later" ]
permissive
milismsft/azure-sdk-for-java
84b48d35e3fca8611933b3f86929788e5e8bceed
f4827811c870d09855417271369c592412986861
refs/heads/master
2022-09-25T19:29:44.973618
2022-08-17T14:43:22
2022-08-17T14:43:22
90,779,733
1
0
MIT
2021-12-21T21:11:58
2017-05-09T18:37:49
Java
UTF-8
Java
false
false
47,099
java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.network.fluent; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceMethod; import com.azure.core.http.rest.PagedFlux; import com.azure.core.http.rest.PagedIterable; import com.azure.core.http.rest.Response; import com.azure.core.management.polling.PollResult; import com.azure.core.util.Context; import com.azure.core.util.polling.PollerFlux; import com.azure.core.util.polling.SyncPoller; import com.azure.resourcemanager.network.fluent.models.ConnectionMonitorInner; import com.azure.resourcemanager.network.fluent.models.ConnectionMonitorQueryResultInner; import com.azure.resourcemanager.network.fluent.models.ConnectionMonitorResultInner; import com.azure.resourcemanager.network.models.TagsObject; import java.nio.ByteBuffer; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in ConnectionMonitorsClient. */ public interface ConnectionMonitorsClient { /** * Create or update a connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters that define the operation to create a connection monitor. * @param migrate Value indicating whether connection monitor V1 should be migrated to V2 format. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about the connection monitor along with {@link Response} on successful completion of {@link * Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<Flux<ByteBuffer>>> createOrUpdateWithResponseAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName, ConnectionMonitorInner parameters, String migrate); /** * Create or update a connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters that define the operation to create a connection monitor. * @param migrate Value indicating whether connection monitor V1 should be migrated to V2 format. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link PollerFlux} for polling of information about the connection monitor. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) PollerFlux<PollResult<ConnectionMonitorResultInner>, ConnectionMonitorResultInner> beginCreateOrUpdateAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName, ConnectionMonitorInner parameters, String migrate); /** * Create or update a connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters that define the operation to create a connection monitor. * @param migrate Value indicating whether connection monitor V1 should be migrated to V2 format. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link SyncPoller} for polling of information about the connection monitor. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<ConnectionMonitorResultInner>, ConnectionMonitorResultInner> beginCreateOrUpdate( String resourceGroupName, String networkWatcherName, String connectionMonitorName, ConnectionMonitorInner parameters, String migrate); /** * Create or update a connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters that define the operation to create a connection monitor. * @param migrate Value indicating whether connection monitor V1 should be migrated to V2 format. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link SyncPoller} for polling of information about the connection monitor. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<ConnectionMonitorResultInner>, ConnectionMonitorResultInner> beginCreateOrUpdate( String resourceGroupName, String networkWatcherName, String connectionMonitorName, ConnectionMonitorInner parameters, String migrate, Context context); /** * Create or update a connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters that define the operation to create a connection monitor. * @param migrate Value indicating whether connection monitor V1 should be migrated to V2 format. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about the connection monitor on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<ConnectionMonitorResultInner> createOrUpdateAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName, ConnectionMonitorInner parameters, String migrate); /** * Create or update a connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters that define the operation to create a connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about the connection monitor on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<ConnectionMonitorResultInner> createOrUpdateAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName, ConnectionMonitorInner parameters); /** * Create or update a connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters that define the operation to create a connection monitor. * @param migrate Value indicating whether connection monitor V1 should be migrated to V2 format. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about the connection monitor. */ @ServiceMethod(returns = ReturnType.SINGLE) ConnectionMonitorResultInner createOrUpdate( String resourceGroupName, String networkWatcherName, String connectionMonitorName, ConnectionMonitorInner parameters, String migrate); /** * Create or update a connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters that define the operation to create a connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about the connection monitor. */ @ServiceMethod(returns = ReturnType.SINGLE) ConnectionMonitorResultInner createOrUpdate( String resourceGroupName, String networkWatcherName, String connectionMonitorName, ConnectionMonitorInner parameters); /** * Create or update a connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters that define the operation to create a connection monitor. * @param migrate Value indicating whether connection monitor V1 should be migrated to V2 format. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about the connection monitor. */ @ServiceMethod(returns = ReturnType.SINGLE) ConnectionMonitorResultInner createOrUpdate( String resourceGroupName, String networkWatcherName, String connectionMonitorName, ConnectionMonitorInner parameters, String migrate, Context context); /** * Gets a connection monitor by name. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a connection monitor by name along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<ConnectionMonitorResultInner>> getWithResponseAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Gets a connection monitor by name. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a connection monitor by name on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<ConnectionMonitorResultInner> getAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Gets a connection monitor by name. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a connection monitor by name. */ @ServiceMethod(returns = ReturnType.SINGLE) ConnectionMonitorResultInner get(String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Gets a connection monitor by name. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a connection monitor by name along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<ConnectionMonitorResultInner> getWithResponse( String resourceGroupName, String networkWatcherName, String connectionMonitorName, Context context); /** * Deletes the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<Flux<ByteBuffer>>> deleteWithResponseAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Deletes the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link PollerFlux} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) PollerFlux<PollResult<Void>, Void> beginDeleteAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Deletes the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link SyncPoller} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<Void>, Void> beginDelete( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Deletes the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link SyncPoller} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<Void>, Void> beginDelete( String resourceGroupName, String networkWatcherName, String connectionMonitorName, Context context); /** * Deletes the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return A {@link Mono} that completes when a successful response is received. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Void> deleteAsync(String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Deletes the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Deletes the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void delete(String resourceGroupName, String networkWatcherName, String connectionMonitorName, Context context); /** * Update tags of the specified connection monitor. * * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters supplied to update connection monitor tags. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about the connection monitor along with {@link Response} on successful completion of {@link * Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<ConnectionMonitorResultInner>> updateTagsWithResponseAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName, TagsObject parameters); /** * Update tags of the specified connection monitor. * * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters supplied to update connection monitor tags. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about the connection monitor on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<ConnectionMonitorResultInner> updateTagsAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName, TagsObject parameters); /** * Update tags of the specified connection monitor. * * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters supplied to update connection monitor tags. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about the connection monitor. */ @ServiceMethod(returns = ReturnType.SINGLE) ConnectionMonitorResultInner updateTags( String resourceGroupName, String networkWatcherName, String connectionMonitorName, TagsObject parameters); /** * Update tags of the specified connection monitor. * * @param resourceGroupName The name of the resource group. * @param networkWatcherName The name of the network watcher. * @param connectionMonitorName The name of the connection monitor. * @param parameters Parameters supplied to update connection monitor tags. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return information about the connection monitor along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) Response<ConnectionMonitorResultInner> updateTagsWithResponse( String resourceGroupName, String networkWatcherName, String connectionMonitorName, TagsObject parameters, Context context); /** * Stops the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<Flux<ByteBuffer>>> stopWithResponseAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Stops the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link PollerFlux} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) PollerFlux<PollResult<Void>, Void> beginStopAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Stops the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link SyncPoller} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<Void>, Void> beginStop( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Stops the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link SyncPoller} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<Void>, Void> beginStop( String resourceGroupName, String networkWatcherName, String connectionMonitorName, Context context); /** * Stops the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return A {@link Mono} that completes when a successful response is received. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Void> stopAsync(String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Stops the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void stop(String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Stops the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void stop(String resourceGroupName, String networkWatcherName, String connectionMonitorName, Context context); /** * Starts the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<Flux<ByteBuffer>>> startWithResponseAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Starts the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link PollerFlux} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) PollerFlux<PollResult<Void>, Void> beginStartAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Starts the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link SyncPoller} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<Void>, Void> beginStart( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Starts the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link SyncPoller} for polling of long-running operation. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<Void>, Void> beginStart( String resourceGroupName, String networkWatcherName, String connectionMonitorName, Context context); /** * Starts the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return A {@link Mono} that completes when a successful response is received. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Void> startAsync(String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Starts the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void start(String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Starts the specified connection monitor. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name of the connection monitor. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. */ @ServiceMethod(returns = ReturnType.SINGLE) void start(String resourceGroupName, String networkWatcherName, String connectionMonitorName, Context context); /** * Query a snapshot of the most recent connection states. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name given to the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of connection states snapshots along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<Response<Flux<ByteBuffer>>> queryWithResponseAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Query a snapshot of the most recent connection states. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name given to the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link PollerFlux} for polling of list of connection states snapshots. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) PollerFlux<PollResult<ConnectionMonitorQueryResultInner>, ConnectionMonitorQueryResultInner> beginQueryAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Query a snapshot of the most recent connection states. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name given to the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link SyncPoller} for polling of list of connection states snapshots. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<ConnectionMonitorQueryResultInner>, ConnectionMonitorQueryResultInner> beginQuery( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Query a snapshot of the most recent connection states. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name given to the connection monitor. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return the {@link SyncPoller} for polling of list of connection states snapshots. */ @ServiceMethod(returns = ReturnType.LONG_RUNNING_OPERATION) SyncPoller<PollResult<ConnectionMonitorQueryResultInner>, ConnectionMonitorQueryResultInner> beginQuery( String resourceGroupName, String networkWatcherName, String connectionMonitorName, Context context); /** * Query a snapshot of the most recent connection states. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name given to the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of connection states snapshots on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) Mono<ConnectionMonitorQueryResultInner> queryAsync( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Query a snapshot of the most recent connection states. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name given to the connection monitor. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of connection states snapshots. */ @ServiceMethod(returns = ReturnType.SINGLE) ConnectionMonitorQueryResultInner query( String resourceGroupName, String networkWatcherName, String connectionMonitorName); /** * Query a snapshot of the most recent connection states. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param connectionMonitorName The name given to the connection monitor. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of connection states snapshots. */ @ServiceMethod(returns = ReturnType.SINGLE) ConnectionMonitorQueryResultInner query( String resourceGroupName, String networkWatcherName, String connectionMonitorName, Context context); /** * Lists all connection monitors for the specified Network Watcher. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of connection monitors as paginated response with {@link PagedFlux}. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedFlux<ConnectionMonitorResultInner> listAsync(String resourceGroupName, String networkWatcherName); /** * Lists all connection monitors for the specified Network Watcher. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of connection monitors as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<ConnectionMonitorResultInner> list(String resourceGroupName, String networkWatcherName); /** * Lists all connection monitors for the specified Network Watcher. * * @param resourceGroupName The name of the resource group containing Network Watcher. * @param networkWatcherName The name of the Network Watcher resource. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return list of connection monitors as paginated response with {@link PagedIterable}. */ @ServiceMethod(returns = ReturnType.COLLECTION) PagedIterable<ConnectionMonitorResultInner> list( String resourceGroupName, String networkWatcherName, Context context); }
3fa406220310cd9293b93d866cb35d762219f1f1
6a4717fd3bfd68435fb054f93cf61d16daef41db
/library/src/main/java/com/miu30/common/async/HttpRequest.java
facfcdb4aab740ccb1c40d4eae745302f5153c1b
[ "Apache-2.0" ]
permissive
mc190diancom/taxi_inspect
79a9d4ed1ac5666ca33090c6c81e2763c9bac79c
8e07e03006f520c1f33a6c5cad59e14e5eae34dd
refs/heads/master
2020-05-17T23:58:05.046853
2019-07-04T09:24:55
2019-07-04T09:24:55
184,045,911
0
0
Apache-2.0
2019-06-25T07:18:43
2019-04-29T09:58:41
Java
UTF-8
Java
false
false
12,757
java
package com.miu30.common.async; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.util.EntityUtils; import com.lidroid.xutils.http.client.multipart.MultipartEntity; import com.lidroid.xutils.http.client.multipart.content.FileBody; import com.miu30.common.config.Config; import okhttp3.FormBody; import okhttp3.Headers; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; public class HttpRequest { public static String post(String strURL, Map<String, String> textMap, Map<String, String> fileMap) { String BOUNDARY = "---------------------------123821742118716"; // boundary就是request头和上传文件内容的分隔符 try { URL url = new URL(strURL);// 创建连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setInstanceFollowRedirects(true); connection.setRequestMethod("POST"); // 设置请求方式 connection.setRequestProperty("Accept", "text/html"); // 设置接收数据的格式 connection.setRequestProperty("Content-Encoding", "gzip"); // 设置接收数据的格式 connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); // 设置发送数据的格式 connection.setConnectTimeout(15 * 1000); connection.setReadTimeout(15 * 1000); connection.connect(); OutputStream out = new DataOutputStream(connection.getOutputStream()); // utf-8编码 if (textMap != null) { StringBuffer strBuf = new StringBuffer(); Iterator<Map.Entry<String, String>> iter = textMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); String inputName = (String) entry.getKey(); String inputValue = (String) entry.getValue(); if (inputValue == null) { continue; } strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n"); strBuf.append(inputValue); } out.write(strBuf.toString().getBytes()); } // file if (fileMap != null) { Iterator<Map.Entry<String, String>> iter = fileMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, String> entry = iter.next(); String inputName = (String) entry.getKey(); String inputValue = (String) entry.getValue(); if (inputValue == null) { continue; } File file = new File(inputValue); String filename = file.getName(); StringBuffer strBuf = new StringBuffer(); strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n"); strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + filename + "\"\r\n"); strBuf.append("Content-Type:" + "multipart/form-data" + "\r\n\r\n"); out.write(strBuf.toString().getBytes()); DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); } } byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); out.write(endData); out.flush(); out.close(); // 读取响应 int length = (int) connection.getContentLength();// 获取长度 InputStream is = connection.getInputStream(); if (length != -1) { byte[] data = new byte[length]; byte[] temp = new byte[512]; int readLen = 0; int destPos = 0; while ((readLen = is.read(temp)) > 0) { System.arraycopy(temp, 0, data, destPos, readLen); destPos += readLen; } String result = new String(data, "UTF-8"); // utf-8编码 System.out.println(result); return result; } } catch (IOException e) { e.printStackTrace(); } return "error"; // 自定义错误信息 } /** * 向指定URL发送GET方法的请求 * * @param url * 发送请求的URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return URL 所代表远程资源的响应结果 */ public static String sendGet(String url, String param) { String result = ""; BufferedReader in = null; int code = 0; try { String urlNameString = url + "?" + param; URL realUrl = new URL(urlNameString); // 打开和URL之间的连接 HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8 * 1000); connection.setReadTimeout(8 * 1000); // 设置通用的请求属性 connection.setRequestProperty("accept", "*/*"); connection.setRequestProperty("connection", "Keep-Alive"); connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 建立实际的连接 connection.connect(); // 获取所有响应头字段 Map<String, List<String>> map = connection.getHeaderFields(); // 遍历所有的响应头字段 for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } // 获取返回码 code = connection.getResponseCode(); // 定义 BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送GET请求出现异常!!错误码:" + code + "。\n" + e); e.printStackTrace(); } // 使用finally块来关闭输入流 finally { try { if (in != null) { in.close(); } } catch (Exception e2) { e2.printStackTrace(); } } return result; } /* * private static String downloadApk(String url, String param) { try { // * 判断SD卡是否存在,并且是否具有读写权限 if * (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) * { // 获得存储卡的路径 String sdpath = Environment.getExternalStorageDirectory() + * "/"; mSavePath = sdpath + "download"; URL url = new * URL(mHashMap.get("url")); // 创建连接 HttpURLConnection conn = * (HttpURLConnection) url.openConnection(); conn.connect(); // 获取文件大小 int * length = conn.getContentLength(); // 创建输入流 InputStream is = * conn.getInputStream(); * * File file = new File(mSavePath); // 判断文件目录是否存在 if (!file.exists()) { * file.mkdir(); } File apkFile = new File(mSavePath, mHashMap.get("name")); * FileOutputStream fos = new FileOutputStream(apkFile); int count = 0; // * 缓存 byte buf[] = new byte[1024]; // 写入到文件中 do { int numread = * is.read(buf); count += numread; // 计算进度条位置 progress = (int) (((float) * count / length) * 100); // 更新进度 mHandler.sendEmptyMessage(DOWNLOAD); if * (numread <= 0) { // 下载完成 mHandler.sendEmptyMessage(DOWNLOAD_FINISH); * break; } // 写入文件 fos.write(buf, 0, numread); } while (!cancelUpdate);// * 点击取消就停止下载. fos.close(); is.close(); } } catch (MalformedURLException e) { * e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // * 取消下载对话框显示 mDownloadDialog.dismiss(); } }; */ /** * 向指定 URL 发送POST方法的请求 * * @param url * 发送请求的 URL * @param param * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return 所代表远程资源的响应结果 * @throws Exception */ //conn.setRequestProperty("accept", "**/*//*"); public static String sendPost(String url, String param) throws Exception { return new String(sendPost2(url, param).getBytes()); /*PrintWriter out = null; BufferedReader in = null; String result = ""; int code = 0; try { URL realUrl = new URL(url); // 打开和URL之间的连接 HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection(); conn.setRequestMethod("POST"); // 发送POST请求必须设置如下两行 conn.setDoOutput(true); conn.setDoInput(true); conn.setConnectTimeout(8 * 1000); conn.setReadTimeout(8 * 1000); // 设置通用的请求属性 conn.setRequestProperty("Cache-Control", "no-cache"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 获取URLConnection对象对应的输出流 out = new PrintWriter(conn.getOutputStream()); out.print(param); // flush输出流的缓冲 out.flush(); // 获取返回码 code = conn.getResponseCode(); // 定义BufferedReader输入流来读取URL的响应 in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += line; } } catch (Exception e) { System.out.println("发送 POST 请求出现异常!错误码:" + code + "。\n" + e); e.printStackTrace(); throw e; } // 使用finally块来关闭输出流、输入流 finally { try { if (out != null) { out.close(); } if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result;*/ } public static HeaderResponse sendPost2(String url, String param) throws Exception { OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(8, TimeUnit.SECONDS) .readTimeout(8, TimeUnit.SECONDS).build(); FormBody.Builder builder = new FormBody.Builder(); String[] p1 = param.split("&"); if(p1 != null) { for (String par : p1) { String[] p2 = par.split("="); if(p2 !=null && p2.length > 1){ builder.add(p2[0], p2[1]); } } } RequestBody formBody = builder.build(); Request.Builder requestBuilder = new Request.Builder().url(url).post(formBody); Request request = requestBuilder.build(); Response response = okHttpClient.newCall(request).execute(); if (response.isSuccessful()) { return new HeaderResponse(response.headers(), response.body().bytes()); } else { throw new IOException("网络问题:" + response); } } public static class HeaderResponse { private Headers headers; private byte[] bytes; private HeaderResponse(Headers headers, byte[] bytes) { this.headers = headers; this.bytes = bytes; } public Headers getHeaders() { return headers; } public void setHeaders(Headers headers) { this.headers = headers; } public byte[] getBytes() { return bytes; } public void setBytes(byte[] bytes) { this.bytes = bytes; } } public static void writeFile(String data) { File file = new File(Config.PATH + "log.txt"); if (!file.exists()) { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } String path = Config.PATH+"log.txt"; FileOutputStream f_write = null; try { f_write = new FileOutputStream(path); f_write.write(data.getBytes()); } catch (Exception e) { e.printStackTrace(); } finally { try { f_write.close(); } catch (Exception e) { e.printStackTrace(); } } } // 上传文件到媒体服务器 // 返回文件下载URL public static String uploadFile(String server, File file) throws Exception { URL url = new URL(server); DefaultHttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000); httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000); HttpPost httpPost = new HttpPost(url.toURI()); MultipartEntity m = new MultipartEntity(); m.addPart("file", new FileBody(file)); httpPost.setEntity(m); HttpResponse response = httpclient.execute(httpPost); if (response.getStatusLine().getStatusCode() != 200) { throw new DException("网络问题:" + response.getStatusLine().getStatusCode()); } String rst = EntityUtils.toString(response.getEntity(), "UTF-8"); return rst; } }
b32c2edc4d4cb20518afe1f700e9ce3f21411dde
faa28492e3a32c5f5ad7bf3f15fe3509dd8c8834
/SynomymExtractor/src/main/java/model/Candidates.java
d8aeaff79280952b09d1eeb9606dc01b8c71e87a
[]
no_license
primo/synreco
69f3476e9c563eb5501fa4d6da43f73b634bc0a2
21b6c959ddc11ab155060d8a82fe1bb33b9f65f4
refs/heads/master
2021-01-15T23:40:01.971571
2013-06-13T21:10:20
2013-06-13T21:10:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,016
java
package model; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class Candidates { public static Map<String, List<String>> generate(Map<String, List<String>> urls) { Set<String> set = new HashSet<String>(); Map<String, List<String>> pivot = new HashMap<String, List<String>>(); Map<String, List<String>> ret = new HashMap<String, List<String>>(); Iterator it = urls.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); String word = pairs.getKey().toString(); for(String domain : urls.get(word)){ List<String> com; if(pivot.containsKey(domain)){ com = pivot.get(domain); }else{ com = new ArrayList<String>(); } com.add(word); pivot.put(domain, com); } } it = pivot.entrySet().iterator(); System.out.println("Domen: "+pivot.size()); while (it.hasNext()) { Map.Entry pairs = (Map.Entry)it.next(); String word = pairs.getKey().toString(); List<String> group = pivot.get(word); if(group.size()>urls.size()/5){ System.out.println(word+" = "+group.size()); continue; } for(int i=0;i<group.size();++i){ String a = group.get(i); for(int j=i+1;j<group.size();++j){ String b = group.get(j); if(a!=b && set.add(a+"#"+b)){ List<String> tmp; if(ret.containsKey(a)) tmp = ret.get(a); else tmp = new ArrayList<String>(); tmp.add(b); ret.put(a, tmp); if(ret.containsKey(b)) tmp = ret.get(b); else tmp = new ArrayList<String>(); tmp.add(a); ret.put(b, tmp); } } } } System.out.println("kandydatów: "+set.size()); return ret; } }
2615c956c8829628dd4be1da9a0dfb092d504567
af79904e3ddb1be18ee66df4ead2fc749e8825e7
/src/abstraction/AmazonNewS2.java
01d54eb1f5fe2c16f70ef716037550bb4f146f30
[]
no_license
SanjaySinghRaj/JavaPrograming
784358aa85fd44209e90cf95aec2fd4da707cbc1
023a47072f559ae0fee4664015c40e3d711a0f2b
refs/heads/master
2023-06-26T20:33:02.739008
2021-07-30T12:26:06
2021-07-30T12:26:06
383,663,450
1
1
null
2021-07-07T04:13:28
2021-07-07T03:34:15
Java
UTF-8
Java
false
false
143
java
package abstraction; interface AmazonNewS2 { public void buy(); public void filter(); public void sort(); public void cart(); }
[ "Bhagwan Singh@LAPTOP-UTR7A9HQ" ]
Bhagwan Singh@LAPTOP-UTR7A9HQ
23859d80585ae3a1723220cd515c66ba29ee6654
d9477e8e6e0d823cf2dec9823d7424732a7563c4
/plugins/PHPParser/tags/PHPParser-2.0.2/src/gatchan/phpparser/methodlist/FunctionListParser.java
01beb966738e4ccb02b52dcfb1cf5e24d5415121
[]
no_license
RobertHSchmidt/jedit
48fd8e1e9527e6f680de334d1903a0113f9e8380
2fbb392d6b569aefead29975b9be12e257fbe4eb
refs/heads/master
2023-08-30T02:52:55.676638
2018-07-11T13:28:01
2018-07-11T13:28:01
140,587,948
1
0
null
null
null
null
UTF-8
Java
false
false
30,543
java
/* Generated By:JavaCC: Do not edit this line. FunctionListParser.java */ package gatchan.phpparser.methodlist; import java.io.*; import java.util.*; public class FunctionListParser implements FunctionListParserConstants { //{{{ main() method public static void main(String args[]) throws IOException { FunctionListParser parser = new FunctionListParser(new StringReader("")); BufferedReader in = new BufferedReader(new FileReader( "c:\u005c\u005cUsers\u005c\u005cChocoPC\u005c\u005cdev\u005c\u005cjEdit\u005c\u005cplugins\u005c\u005cPHPParser\u005c\u005csrc\u005c\u005cgatchan\u005c\u005cphpparser\u005c\u005cmethodlist\u005c\u005ctest")); String line = in.readLine(); Map<String, Function> functions = new HashMap<String, Function>(); while (line != null) { if (!line.isEmpty()) { parser.ReInit(new StringReader(line)); try { Function function = parser.function(); functions.put(function.getName(), function); } catch (TokenMgrError e) { System.err.println(line); } catch (ParseException e) { System.err.println(line); } } line = in.readLine(); } } //{{{ parse() method final public Map<String,Function> parse() throws ParseException { Function function; Map<String,Function> functions = new HashMap<String,Function>(); label_1: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case VOID: case STRING: case BOOL: case INTEGER: case NUMBER: case DOUBLE: case INT: case ARRAY: case LONG: case RESOURCE: case OBJECT: case MIXED: case FUNCTION_IDENTIFIER: ; break; default: jj_la1[0] = jj_gen; break label_1; } function = function(); Function f = functions.get(function.getName()); if (f == null) functions.put(function.getName(), function); else { f.setAlternative(function); } } jj_consume_token(0); {if (true) return functions;} throw new Error("Missing return statement in function"); } //}}} //{{{ function() method final public Function function() throws ParseException { String type; String methodName; List<Argument> arguments = null; type = returnType(); methodName = functionIdentifier(); jj_consume_token(LPAREN); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case VARARGSIDENTIFIER: case REF: case LBRACKET: case VOID: case STRING: case BOOL: case INTEGER: case NUMBER: case DOUBLE: case INT: case ARRAY: case LONG: case RESOURCE: case OBJECT: case MIXED: case FUNCTION_IDENTIFIER: arguments = firstArgument(); break; default: jj_la1[1] = jj_gen; ; } jj_consume_token(RPAREN); if (arguments == null) { {if (true) return new Function(type, methodName, new Argument[0]);} } Argument[] args = new Argument[arguments.size()]; args = arguments.toArray(args); {if (true) return new Function(type, methodName, args);} throw new Error("Missing return statement in function"); } //}}} //{{{ firstArgument() final public List<Argument> firstArgument() throws ParseException { Argument argument; List<Argument> arguments = new ArrayList<Argument>(); List<Argument> nextArgs; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case VOID: jj_consume_token(VOID); break; case VARARGSIDENTIFIER: case REF: case STRING: case BOOL: case INTEGER: case NUMBER: case DOUBLE: case INT: case ARRAY: case LONG: case RESOURCE: case OBJECT: case MIXED: case FUNCTION_IDENTIFIER: argument = argument(); arguments.add(argument); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: case LBRACKET: nextArgs = nextArguments(); arguments.addAll(nextArgs); break; default: jj_la1[2] = jj_gen; ; } break; case LBRACKET: jj_consume_token(LBRACKET); argument = argument(); argument.setOptional(true); arguments.add(argument); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: case LBRACKET: nextArgs = nextArguments(); for (Argument arg : nextArgs) { arg.setOptional(true); arguments.add(arg); } break; default: jj_la1[3] = jj_gen; ; } jj_consume_token(RBRACKET); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: case LBRACKET: nextArgs = nextArguments(); arguments.addAll(nextArgs); break; default: jj_la1[4] = jj_gen; ; } break; default: jj_la1[5] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return arguments;} throw new Error("Missing return statement in function"); } //}}} //{{{ nextArguments() method final public List<Argument> nextArguments() throws ParseException { Argument argument; List<Argument> arguments = new ArrayList<Argument>(); List<Argument> nextArgs; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: jj_consume_token(COMMA); argument = argument(); arguments.add(argument); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: case LBRACKET: nextArgs = nextArguments(); arguments.addAll(nextArgs); break; default: jj_la1[6] = jj_gen; ; } break; case LBRACKET: jj_consume_token(LBRACKET); jj_consume_token(COMMA); argument = argument(); argument.setOptional(true); arguments.add(argument); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: case LBRACKET: nextArgs = nextArguments(); for (Argument arg : nextArgs) { arg.setOptional(true); arguments.add(arg); } break; default: jj_la1[7] = jj_gen; ; } jj_consume_token(RBRACKET); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: case LBRACKET: nextArgs = nextArguments(); arguments.addAll(nextArgs); break; default: jj_la1[8] = jj_gen; ; } break; default: jj_la1[9] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return arguments;} throw new Error("Missing return statement in function"); } //}}} //{{{ argument() method final public Argument argument() throws ParseException { String type; String argumentName; String alternateType = null; boolean ref = false; String initializer = null; boolean varargs = false; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case VARARGSIDENTIFIER: jj_consume_token(VARARGSIDENTIFIER); Argument arg = new Argument("unknown", "..."); arg.setVarargs(true); {if (true) return arg;} break; case REF: case STRING: case BOOL: case INTEGER: case NUMBER: case DOUBLE: case INT: case ARRAY: case LONG: case RESOURCE: case OBJECT: case MIXED: case FUNCTION_IDENTIFIER: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case REF: jj_consume_token(REF); ref = true; break; default: jj_la1[10] = jj_gen; ; } type = type(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PIPE: jj_consume_token(PIPE); alternateType = type(); break; default: jj_la1[11] = jj_gen; ; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case REF: jj_consume_token(REF); ref = true; break; default: jj_la1[12] = jj_gen; ; } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case STAR: jj_consume_token(STAR); break; default: jj_la1[13] = jj_gen; ; } argumentName = argumentIdentifier(); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case ASSIGN: case VARARGS: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case VARARGS: jj_consume_token(VARARGS); varargs = true; break; case ASSIGN: jj_consume_token(ASSIGN); initializer = initializer(); label_2: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PIPE: ; break; default: jj_la1[14] = jj_gen; break label_2; } jj_consume_token(PIPE); String secondInitializer; secondInitializer = initializer(); initializer += " | " + secondInitializer; } break; default: jj_la1[15] = jj_gen; jj_consume_token(-1); throw new ParseException(); } break; default: jj_la1[16] = jj_gen; ; } Argument argument = new Argument(type, argumentName); argument.setAlternateType(alternateType); argument.setReference(ref); argument.setVarargs(varargs); if ("$...".equals(argumentName)) argument.setVarargs(true); argument.setDefaultValue(initializer); {if (true) return argument;} break; default: jj_la1[17] = jj_gen; jj_consume_token(-1); throw new ParseException(); } throw new Error("Missing return statement in function"); } //}}} //{{{ initializer() final public String initializer() throws ParseException { String ret; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case LITERAL: jj_consume_token(LITERAL); ret = token.image; break; case SINGLEQUOTE_LITERAL: jj_consume_token(SINGLEQUOTE_LITERAL); ret = token.image; break; case MINUS: jj_consume_token(MINUS); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case FUNCTION_IDENTIFIER: jj_consume_token(FUNCTION_IDENTIFIER); break; case INTEGER_LITERAL: jj_consume_token(INTEGER_LITERAL); break; default: jj_la1[18] = jj_gen; jj_consume_token(-1); throw new ParseException(); } ret = "-"+token.image; break; default: jj_la1[19] = jj_gen; if (jj_2_1(2)) { ret = functionCall(); } else { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case FUNCTION_IDENTIFIER: jj_consume_token(FUNCTION_IDENTIFIER); ret = token.image; break; case IDENTIFIER: jj_consume_token(IDENTIFIER); ret = token.image; break; case STRING: jj_consume_token(STRING); ret = token.image; break; case INTEGER_LITERAL: jj_consume_token(INTEGER_LITERAL); ret = token.image; break; case FLOATING_POINT_LITERAL: jj_consume_token(FLOATING_POINT_LITERAL); ret = token.image; break; default: jj_la1[20] = jj_gen; jj_consume_token(-1); throw new ParseException(); } } } switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case SLASH: case PLUS: switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case PLUS: jj_consume_token(PLUS); break; case SLASH: jj_consume_token(SLASH); break; default: jj_la1[21] = jj_gen; jj_consume_token(-1); throw new ParseException(); } String next; next = initializer(); {if (true) return ret + " + " + next;} break; default: jj_la1[22] = jj_gen; ; } {if (true) return ret;} throw new Error("Missing return statement in function"); } //}}} //{{{ functionCall() method final public String functionCall() throws ParseException { String ret; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case FUNCTION_IDENTIFIER: jj_consume_token(FUNCTION_IDENTIFIER); break; case ARRAY: jj_consume_token(ARRAY); break; default: jj_la1[23] = jj_gen; jj_consume_token(-1); throw new ParseException(); } ret = token.image; jj_consume_token(LPAREN); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case MINUS: case STRING: case ARRAY: case INTEGER_LITERAL: case FLOATING_POINT_LITERAL: case FUNCTION_IDENTIFIER: case IDENTIFIER: case LITERAL: case SINGLEQUOTE_LITERAL: initializer(); label_3: while (true) { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case COMMA: ; break; default: jj_la1[24] = jj_gen; break label_3; } jj_consume_token(COMMA); initializer(); } break; default: jj_la1[25] = jj_gen; ; } jj_consume_token(RPAREN); {if (true) return ret;} throw new Error("Missing return statement in function"); } //}}} //{{{ argumentIdentifier() method final public String argumentIdentifier() throws ParseException { String ret; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: jj_consume_token(IDENTIFIER); ret = token.image; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case SLASH: jj_consume_token(SLASH); switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case IDENTIFIER: jj_consume_token(IDENTIFIER); break; case FUNCTION_IDENTIFIER: jj_consume_token(FUNCTION_IDENTIFIER); break; default: jj_la1[26] = jj_gen; jj_consume_token(-1); throw new ParseException(); } ret += "/" + token.image; break; default: jj_la1[27] = jj_gen; ; } break; case OBJECT: jj_consume_token(OBJECT); ret = token.image; break; case VARARGSIDENTIFIER: jj_consume_token(VARARGSIDENTIFIER); ret = token.image; break; default: jj_la1[28] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return ret;} throw new Error("Missing return statement in function"); } //}}} //{{{ functionIdentifier() method final public String functionIdentifier() throws ParseException { switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case FUNCTION_IDENTIFIER: jj_consume_token(FUNCTION_IDENTIFIER); break; case ARRAY: jj_consume_token(ARRAY); break; default: jj_la1[29] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return token.image;} throw new Error("Missing return statement in function"); } //}}} //{{{ returnType() method final public String returnType() throws ParseException { String ret; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case VOID: jj_consume_token(VOID); ret = "void"; break; case STRING: case BOOL: case INTEGER: case NUMBER: case DOUBLE: case INT: case ARRAY: case LONG: case RESOURCE: case OBJECT: case MIXED: case FUNCTION_IDENTIFIER: ret = type(); break; default: jj_la1[30] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return ret;} throw new Error("Missing return statement in function"); } //}}} //{{{ type() method final public String type() throws ParseException { String ret; switch ((jj_ntk==-1)?jj_ntk():jj_ntk) { case STRING: jj_consume_token(STRING); ret = "string"; break; case BOOL: jj_consume_token(BOOL); ret = "boolean"; break; case INT: jj_consume_token(INT); ret = "integer"; break; case INTEGER: jj_consume_token(INTEGER); ret = "integer"; break; case NUMBER: jj_consume_token(NUMBER); ret = "number"; break; case OBJECT: jj_consume_token(OBJECT); ret = "object"; break; case ARRAY: jj_consume_token(ARRAY); ret = "array"; break; case LONG: jj_consume_token(LONG); ret = "long"; break; case RESOURCE: jj_consume_token(RESOURCE); ret = "resource"; break; case DOUBLE: jj_consume_token(DOUBLE); ret = "double"; break; case MIXED: jj_consume_token(MIXED); ret = "mixed"; break; case FUNCTION_IDENTIFIER: jj_consume_token(FUNCTION_IDENTIFIER); ret = token.image; if (jj_2_2(2)) { jj_consume_token(OBJECT); ret = ret + " object"; } else { ; } break; default: jj_la1[31] = jj_gen; jj_consume_token(-1); throw new ParseException(); } {if (true) return ret;} throw new Error("Missing return statement in function"); } private boolean jj_2_1(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_1(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(0, xla); } } private boolean jj_2_2(int xla) { jj_la = xla; jj_lastpos = jj_scanpos = token; try { return !jj_3_2(); } catch(LookaheadSuccess ls) { return true; } finally { jj_save(1, xla); } } private boolean jj_3_1() { if (jj_3R_4()) return true; return false; } private boolean jj_3R_4() { Token xsp; xsp = jj_scanpos; if (jj_scan_token(34)) { jj_scanpos = xsp; if (jj_scan_token(27)) return true; } if (jj_scan_token(LPAREN)) return true; return false; } private boolean jj_3_2() { if (jj_scan_token(OBJECT)) return true; return false; } /** Generated Token Manager. */ public FunctionListParserTokenManager token_source; SimpleCharStream jj_input_stream; /** Current token. */ public Token token; /** Next token. */ public Token jj_nt; private int jj_ntk; private Token jj_scanpos, jj_lastpos; private int jj_la; private int jj_gen; final private int[] jj_la1 = new int[32]; static private int[] jj_la1_0; static private int[] jj_la1_1; static { jj_la1_init_0(); jj_la1_init_1(); } private static void jj_la1_init_0() { jj_la1_0 = new int[] {0xfff00000,0xfff42800,0x48000,0x48000,0x48000,0xfff42800,0x48000,0x48000,0x48000,0x48000,0x2000,0x4000,0x2000,0x200,0x4000,0x1400,0x1400,0xffe02800,0x0,0x100,0x200000,0xc0,0xc0,0x8000000,0x8000,0x8200100,0x0,0x40,0x40000800,0x8000000,0xfff00000,0xffe00000,}; } private static void jj_la1_init_1() { jj_la1_1 = new int[] {0x4,0x4,0x0,0x0,0x0,0x4,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x4,0x5,0xc0,0xf,0x0,0x0,0x4,0x0,0xcf,0xc,0x0,0x8,0x4,0x4,0x4,}; } final private JJCalls[] jj_2_rtns = new JJCalls[2]; private boolean jj_rescan = false; private int jj_gc = 0; /** Constructor with InputStream. */ public FunctionListParser(java.io.InputStream stream) { this(stream, null); } /** Constructor with InputStream and supplied encoding */ public FunctionListParser(java.io.InputStream stream, String encoding) { try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source = new FunctionListParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 32; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } /** Reinitialise. */ public void ReInit(java.io.InputStream stream) { ReInit(stream, null); } /** Reinitialise. */ public void ReInit(java.io.InputStream stream, String encoding) { try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 32; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } /** Constructor. */ public FunctionListParser(java.io.Reader stream) { jj_input_stream = new SimpleCharStream(stream, 1, 1); token_source = new FunctionListParserTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 32; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } /** Reinitialise. */ public void ReInit(java.io.Reader stream) { jj_input_stream.ReInit(stream, 1, 1); token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 32; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } /** Constructor with generated Token Manager. */ public FunctionListParser(FunctionListParserTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 32; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } /** Reinitialise. */ public void ReInit(FunctionListParserTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 32; i++) jj_la1[i] = -1; for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls(); } private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; if (++jj_gc > 100) { jj_gc = 0; for (int i = 0; i < jj_2_rtns.length; i++) { JJCalls c = jj_2_rtns[i]; while (c != null) { if (c.gen < jj_gen) c.first = null; c = c.next; } } } return token; } token = oldToken; jj_kind = kind; throw generateParseException(); } static private final class LookaheadSuccess extends java.lang.Error { } final private LookaheadSuccess jj_ls = new LookaheadSuccess(); private boolean jj_scan_token(int kind) { if (jj_scanpos == jj_lastpos) { jj_la--; if (jj_scanpos.next == null) { jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken(); } else { jj_lastpos = jj_scanpos = jj_scanpos.next; } } else { jj_scanpos = jj_scanpos.next; } if (jj_rescan) { int i = 0; Token tok = token; while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; } if (tok != null) jj_add_error_token(kind, i); } if (jj_scanpos.kind != kind) return true; if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls; return false; } /** Get the next Token. */ final public Token getNextToken() { if (token.next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; jj_gen++; return token; } /** Get the specific Token. */ final public Token getToken(int index) { Token t = token; for (int i = 0; i < index; i++) { if (t.next != null) t = t.next; else t = t.next = token_source.getNextToken(); } return t; } private int jj_ntk() { if ((jj_nt=token.next) == null) return (jj_ntk = (token.next=token_source.getNextToken()).kind); else return (jj_ntk = jj_nt.kind); } private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>(); private int[] jj_expentry; private int jj_kind = -1; private int[] jj_lasttokens = new int[100]; private int jj_endpos; private void jj_add_error_token(int kind, int pos) { if (pos >= 100) return; if (pos == jj_endpos + 1) { jj_lasttokens[jj_endpos++] = kind; } else if (jj_endpos != 0) { jj_expentry = new int[jj_endpos]; for (int i = 0; i < jj_endpos; i++) { jj_expentry[i] = jj_lasttokens[i]; } jj_entries_loop: for (java.util.Iterator<?> it = jj_expentries.iterator(); it.hasNext();) { int[] oldentry = (int[])(it.next()); if (oldentry.length == jj_expentry.length) { for (int i = 0; i < jj_expentry.length; i++) { if (oldentry[i] != jj_expentry[i]) { continue jj_entries_loop; } } jj_expentries.add(jj_expentry); break jj_entries_loop; } } if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind; } } /** Generate ParseException. */ public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[40]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 32; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } if ((jj_la1_1[i] & (1<<j)) != 0) { la1tokens[32+j] = true; } } } } for (int i = 0; i < 40; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } jj_endpos = 0; jj_rescan_token(); jj_add_error_token(0, 0); int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); } /** Enable tracing. */ final public void enable_tracing() { } /** Disable tracing. */ final public void disable_tracing() { } private void jj_rescan_token() { jj_rescan = true; for (int i = 0; i < 2; i++) { try { JJCalls p = jj_2_rtns[i]; do { if (p.gen > jj_gen) { jj_la = p.arg; jj_lastpos = jj_scanpos = p.first; switch (i) { case 0: jj_3_1(); break; case 1: jj_3_2(); break; } } p = p.next; } while (p != null); } catch(LookaheadSuccess ls) { } } jj_rescan = false; } private void jj_save(int index, int xla) { JJCalls p = jj_2_rtns[index]; while (p.gen > jj_gen) { if (p.next == null) { p = p.next = new JJCalls(); break; } p = p.next; } p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla; } static final class JJCalls { int gen; Token first; int arg; JJCalls next; } //}}} }
[ "ezust@6b1eeb88-9816-0410-afa2-b43733a0f04e" ]
ezust@6b1eeb88-9816-0410-afa2-b43733a0f04e
97c1db62dfb4593839994ab0001dd49a0c432061
27f31bb2daf716e5e4f05a99545e379ad04b12ce
/app/src/test/java/com/way/heard/ExampleUnitTest.java
1859cbaaa9c3c6726a0c79aee5eae1618ffc1e44
[]
no_license
WaylanPunch/Heard
4ea33a83a52c66ffdc8f22483bf724a286b77fbc
69fd20476db5ba17c0c8c79c00c51a5b9eb3e621
refs/heads/master
2020-04-06T03:53:43.458217
2016-11-09T15:51:33
2016-11-09T15:51:33
56,174,329
9
2
null
null
null
null
UTF-8
Java
false
false
320
java
package com.way.heard; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
45df4f7bc5e95aff5b5afc5ae0f17be9c60beefd
2839089b62adf5145c47cffb15848d0fea37190f
/src/test/java/com/timgroup/statsd/ListProtocol.java
31661c30148edb8987a45f1f3225411a9c6c4d16
[ "MIT" ]
permissive
pgelinas/java-dogstatsd-client
22600b6102ed7af7bd7f8eef329d16e59b030f27
428c86790dd30914d93b9e07f2f6610a024dc9cc
refs/heads/master
2021-05-06T03:12:22.198827
2018-01-11T16:45:31
2018-01-24T20:37:27
114,814,964
0
1
null
2017-12-19T21:56:17
2017-12-19T21:56:17
null
UTF-8
Java
false
false
610
java
package com.timgroup.statsd; import java.io.IOException; import java.util.List; /** * Protocol implementation that just put the message in a list. Used for testing. */ class ListProtocol implements Protocol { final List<String> messageReceived; ListProtocol(List<String> messageReceived) { this.messageReceived = messageReceived; } @Override public void close() throws IOException { } @Override public void send(String message) throws IOException { messageReceived.add(message); } @Override public void flush() throws IOException { } }
a727d5edab388c6b29461efeba01ba3d093193de
44f42848e18da866372f262af8a76ba16dabeaf1
/Job-Application-Service-h/src/main/java/com/cg/edu/service/JobApplicationServiceImpl.java
9eca05c3c9064a9c32ad2dd1fab0e58ceba16e74
[]
no_license
deekshana22/OnlineJobPortal
35ea7be5751e36b284b087d83551da0f9f9b4b61
5bacdc75e9b81d992e8819c3a339f87edf221ca5
refs/heads/master
2022-12-02T01:49:15.129716
2020-08-20T17:24:25
2020-08-20T17:24:25
289,064,293
0
0
null
null
null
null
UTF-8
Java
false
false
2,629
java
package com.cg.edu.service; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.cg.edu.dao.JobApplicationRepository; import com.cg.edu.dto.Job; import com.cg.edu.dto.JobApplication; import com.cg.edu.dto.User; /** * @author HarshitSharma * */ @Service public class JobApplicationServiceImpl implements JobApplicationService { private static Logger myLogger; /** * static block to declare logger */ static { setMyLogger(LoggerFactory.getLogger(JobApplicationServiceImpl.class)); } @Autowired JobApplicationRepository repo; /** * This is the job apply method which creates one job application. * @param jobApplication * @return JobApplication object. */ @Override public JobApplication apply(JobApplication application) { return repo.save(application); } @Override public List<JobApplication> findAllJobApplication() { List<JobApplication> list = new ArrayList<>(); Iterable<JobApplication> iterable = repo.findAll(); Iterator<JobApplication> iterator = iterable.iterator(); while (iterator.hasNext()) { list.add(iterator.next()); } return list; } @Override public JobApplication findApplicationByJob(Job job, User user) { List<JobApplication> jobApplicationList = repo.findByJob(job); JobApplication app = null; for(int i=0; i<jobApplicationList.size(); i++) { try { if(jobApplicationList.get(i).getUser().getUserId().equals(user.getUserId())) { myLogger.info("-----------------application found-----------------"); app = jobApplicationList.get(i); break; } } catch(NullPointerException ex) { } } try { if(app.getApplicationId() != null) { myLogger.info("-----------------already applied to job-----------------"); } else { app = new JobApplication(); app.setJob(job); app.setUser(user); this.apply(app); myLogger.info("-----------------fresh job application-----------------"); } }catch(NullPointerException ex) { app = new JobApplication(); myLogger.info("-----------------fresh job application-----------------"); } return app; } /** * @return the myLogger */ public static Logger getMyLogger() { return myLogger; } /** * @param myLogger the myLogger to set */ public static void setMyLogger(Logger myLogger) { JobApplicationServiceImpl.myLogger = myLogger; } }
[ "SRUJANA [email protected]" ]
94fa9f32024c64cb1dc154c8d26ea543134dd377
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/square--okhttp/98ae0fb92c9335ec17f8710376183e18f5edd355/before/TlsVersion.java
bd477003937746947cd2683ce83f2d30a465efdf
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
1,401
java
/* * Copyright (C) 2014 Square, 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 okhttp3; import javax.net.ssl.SSLSocket; /** * Versions of TLS that can be offered when negotiating a secure socket. See * {@link SSLSocket#setEnabledProtocols}. */ public enum TlsVersion { TLS_1_2("TLSv1.2"), // 2008. TLS_1_1("TLSv1.1"), // 2006. TLS_1_0("TLSv1"), // 1999. SSL_3_0("SSLv3"), // 1996. ; final String javaName; TlsVersion(String javaName) { this.javaName = javaName; } public static TlsVersion forJavaName(String javaName) { switch (javaName) { case "TLSv1.2": return TLS_1_2; case "TLSv1.1": return TLS_1_1; case "TLSv1": return TLS_1_0; case "SSLv3": return SSL_3_0; } throw new IllegalArgumentException("Unexpected TLS version: " + javaName); } public String javaName() { return javaName; } }
58d927cd03360fd7425d7cabc9636bf00fe97503
bfa42980f2e553490c8883d59a4c7cd61a57c521
/src/test/java/com/csx/springBootDemo/RedisTest.java
c0c44460f756224950fedfca58976da8c82d8019
[]
no_license
chensongxian/springBootDemo
44d64f44ca87739424449e904405b7e755fc8d4c
78b653a297f23d170f6942acdeb003358eb6bca2
refs/heads/master
2021-01-24T11:49:05.065666
2018-03-01T01:47:37
2018-03-01T01:47:37
123,104,739
0
0
null
null
null
null
UTF-8
Java
false
false
1,890
java
package com.csx.springBootDemo; import com.csx.springBootDemo.domain.redis.User; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.test.context.junit4.SpringRunner; /** * Created with IntelliJ IDEA. * * @Description: TODO * @Author: csx * @Date: 2018/02/28 */ @RunWith(SpringRunner.class) @SpringBootTest public class RedisTest { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate<String, User> redisTemplate; @Test public void testUser() throws Exception { // 保存字符串 stringRedisTemplate.opsForValue().set("aaa", "111"); Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa")); // 保存对象 User user = new User("超人", 20); redisTemplate.opsForValue().set(user.getUsername(), user); user = new User("蝙蝠侠", 30); redisTemplate.opsForValue().set(user.getUsername(), user); user = new User("蜘蛛侠", 40); redisTemplate.opsForValue().set(user.getUsername(), user); Assert.assertEquals(20, redisTemplate.opsForValue().get("超人").getAge().longValue()); Assert.assertEquals(30, redisTemplate.opsForValue().get("蝙蝠侠").getAge().longValue()); Assert.assertEquals(40, redisTemplate.opsForValue().get("蜘蛛侠").getAge().longValue()); } @Test public void testRedis(){ // 保存字符串 stringRedisTemplate.opsForValue().set("aaa", "111"); Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa")); } }
22611f4696e79823e8eb184db56d8a4ccc653983
1e080c209a735712ea05f9faf2a14b08e2e3f8f6
/src/main/java/de/howaner/netflowcollector/database/DatabaseCache.java
5e8b6c9a4b591246f0c03fa31251f73813ad64cc
[ "BSD-3-Clause" ]
permissive
Howaner/NetflowCollector
89f92b1ad1590afc728ebc685eb548156007b238
9ff11eadaee7c09a4e91506c5ee8fd507af15345
refs/heads/master
2021-12-23T09:18:26.161108
2021-12-12T13:25:52
2021-12-12T13:25:52
135,903,053
3
5
null
null
null
null
UTF-8
Java
false
false
3,830
java
package de.howaner.netflowcollector.database; import de.howaner.netflowcollector.NetflowCollector; import de.howaner.netflowcollector.types.Flow; import de.howaner.netflowcollector.util.CacheList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import lombok.RequiredArgsConstructor; import org.bson.Document; public class DatabaseCache { private final Map<String, CacheList<Document>> cachedCollections = new HashMap<>(); private final ReadWriteLock cachedCollectionsLock = new ReentrantReadWriteLock(); private CacheTimeoutChecker timeoutCheckerThread; public void startTimeoutChecker() { this.timeoutCheckerThread = new CacheTimeoutChecker(); this.timeoutCheckerThread.start(); } public CacheList<Document> getOrCreateCacheList(String collection) { this.cachedCollectionsLock.readLock().lock(); try { CacheList<Document> list = this.cachedCollections.get(collection); if (list == null) { list = new CacheList<>(Document.class, NetflowCollector.getInstance().getConfig().getCacheSize()); list.setFullHandler(new MongoCacheFullHandler(collection)); this.cachedCollections.put(collection, list); } return list; } finally { this.cachedCollectionsLock.readLock().unlock(); } } public void timeoutCache() { long timeout = NetflowCollector.getInstance().getConfig().getCacheTimeout(); Map<String, CacheList<Document>> timeoutedCaches = new HashMap<>(); this.cachedCollectionsLock.writeLock().lock(); try { Iterator<Map.Entry<String, CacheList<Document>>> itr = this.cachedCollections.entrySet().iterator(); while (itr.hasNext()) { Map.Entry<String, CacheList<Document>> entry = itr.next(); if ((System.currentTimeMillis() - entry.getValue().getLastChange()) >= timeout) { itr.remove(); timeoutedCaches.put(entry.getKey(), entry.getValue()); NetflowCollector.getInstance().getLogger().info("Time-out for collection cache {} -> It will be saved to database and the cache get removed.", entry.getKey()); } } } finally { this.cachedCollectionsLock.writeLock().unlock(); } timeoutedCaches.values().forEach(CacheList::forceFull); } public void addFlow(Flow flow) { Document doc = flow.createDatabaseDocument(); String collection = NetflowCollector.getInstance().getConfig().getCollectionAdapter().getCollectionName(doc); CacheList<Document> cache = this.getOrCreateCacheList(collection); cache.add(doc); } /** * Forces all cache data to save and clear the cache. Used at application shutdown. */ public void forceSave() { this.cachedCollectionsLock.writeLock().lock(); try { this.cachedCollections.values().forEach(CacheList::forceFull); this.cachedCollections.clear(); } finally { this.cachedCollectionsLock.writeLock().unlock(); } } @RequiredArgsConstructor private class MongoCacheFullHandler implements CacheList.FullHandler<Document> { private final String collection; @Override public void onFull(Document[] elements) { NetflowCollector.getInstance().getLogger().info("[Database] Write {} flows of collection {} into database", elements.length, this.collection); List<Document> list = Arrays.asList(elements); NetflowCollector.getInstance().getDatabaseConnection().insertFlows(this.collection, list); } } private class CacheTimeoutChecker extends Thread { public CacheTimeoutChecker() { super("DatabaseCache Timeout Checker"); this.setDaemon(true); } @Override public void run() { while (!this.isInterrupted()) { try { Thread.sleep(60000L); } catch (InterruptedException ex) { break; } DatabaseCache.this.timeoutCache(); } } } }
6324e9e17f8f4ad1587c3563f8fbef83167c3597
fe46d7a83e2fc27aa7233e712f1af7584fbfa7e9
/src/main/java/youzhi/day01/Question4_3.java
2e08d7835091be53b1cc2df2b565cb8ea4763361
[]
no_license
youzhi0403/leetcode-learning
898f6f1b129c215d167493a91fb97d831d7c9dff
493bd435283299db683e3ea72e2301a53b5898f6
refs/heads/main
2023-05-04T19:32:58.287478
2021-05-25T11:51:22
2021-05-25T11:51:22
357,092,427
0
0
null
null
null
null
UTF-8
Java
false
false
8,842
java
package youzhi.day01; /** * @author youzhi * @date 2021/4/13 10:51 */ public class Question4_3 { public static void main(String[] args) { /** * 中位数的作用是什么:将一个集合划分为两个长度相等的子集,其中一个子集的元素总是大于另一个子集的元素 * 定义A集合,B集合 * 定义i,将A集合分为两个部分:{A[0],...,A[i-1]},{A[i]....,A[m-1]} m=A.length * 定义j,将B集合分为两个部分,{B[0],...,B[j-1]},{B[j]...,B[n-1]} n=B.length * 将A的左部分和B的左部分放到一个集合left_part, 把A的右部分和B的右部分放到一个集合right_part * * 当A和B的总长度是偶数,如果可以满足以下两个条件: * len(left_part) = len(right_part) * max(left_part) <= min(right_part) * 那么中位数就是:median = (max(left_part) + min(right_part))/2 * * 当A和B的总长度是奇数,如果可以满足以下两个条件 * len(left_part) = len(right_part) + 1 * max(left_part) <= min(right_part) * 那么中位数就是 max(left_part) * * 要确保 偶数情况 和 奇数情况 的两个条件,只需要保证: * 当m+n为偶数时,i+j = m - i + n - j ===========> i+j = (m + n)/2 * 当m+n为奇数时,i+j = m - i + n - j + 1 ===========> i+j = (m + n + 1)/2 * (1)从程序的角度可以合并为 i + j = (m + n + 1)/2 * * (2)规定A的长度小于等于B,如果A大于B,则交换两个数组 * * (3)B[j-1] <= A[i] 并且 A[i-1] <= B[j] * * 分析临界规则 * 假设A[i-1] A[i] B[j-1] B[j] 总是存在, * 对于i=0,i=m,j=0,j=n 这样的临界条件,只需要规定A[-1] = B[-1] = 负无穷大 A[m] = B[n] = 正无穷大 * 如果一个数组不出现前一部分时,对应的值为负无穷,就不会对前一部分的最大值产生影响 * 如果一个数组不出现后一部分时,对应的值为正无穷,就不会对后一部分的最小值产生影响 * * 所以我们需要做的是: * 在[0,m]中找到i,使得 B[j-1] <= A[i] 且 A[i-1] <= B[j] ,其中j = (m+n+1)/2 - i * 他等价于: * A[i-1] <= b[j] 其中 j = (m+n+1)/2 - i * 因为 一定存在一个最大的i满足A[i-1] <= B[j] * i+1肯定不满足 A[i-1] <= b[j],也就是A[i] > B[j-1] * * ======================== * 2021-4-19 * 当 m + n 为偶数或者为奇数, i+j = (m + n + 1)/2 * 当 m + n = 1 1 * 当 m + n = 2 1 * 3 2 * 4 2 * * i=0 A[i-1] = A[-1] = 负无穷大 * i=m A[i] = A[m] = 正无穷大 * j=0 B[j-1] = B[-1] = 负无穷大 * j=n B[j] = B[n] = 正无穷大 */ // int[] nums1 = new int[]{4}; // int[] nums2 = new int[]{1,2,3,5,6}; // int[] nums1 = new int[]{}; // int[] nums2 = new int[]{1}; // int[] nums1 = new int[]{1}; // int[] nums2 = new int[]{1}; int[] nums1 = new int[]{1,1,1}; int[] nums2 = new int[]{1,1,1}; // int[] nums1 = new int[]{2}; // int[] nums2 = new int[]{}; System.out.println(findMedianSortedArrays2(nums1,nums2)); } /** * (1)数学论证: * * 将一个集合划分为两个长度相等的子集,其中一个子集的元素总是大于另一个子集的元素 * 定义A集合,B集合 * 定义i,将A集合分为两个部分:{A[0],...,A[i-1]},{A[i]....,A[m-1]} m=A.length * 定义j,将B集合分为两个部分,{B[0],...,B[j-1]},{B[j]...,B[n-1]} n=B.length * 将A的左部分和B的左部分放到一个集合left_part, 把A的右部分和B的右部分放到一个集合right_part * * 当A和B的总长度是偶数,如果可以满足以下两个条件: * len(left_part) = len(right_part) * max(left_part) <= min(right_part) * 那么中位数就是:median = (max(left_part) + min(right_part))/2 * * 当A和B的总长度是奇数,如果可以满足以下两个条件 * len(left_part) = len(right_part) + 1 * max(left_part) <= min(right_part) * 那么中位数就是 max(left_part) * * 要确保【奇数场景】【偶数场景】这两种情况,要保证如下条件: * <一> i + j = m - i + n - j(偶数场景) 或者是 i + j = m - i + n - j + 1(奇数场景)。 * 可以得到 i + j = (m + n)/2(偶数场景)或者是 i + j = (m + n + 1)/2 (奇数场景) * 这里的分数结果只保留整数部分,可以将两种情况合并为: i + j = (m + n + 1)/2 * <二> 规定A的长度小于等于B的长度,即m<=n。(为了避免j为负数) * 那么j = (m + n + 1)/2 - i * 如果A的长度大于B,那么交换A和B即可 * <三> A[i-1] <= B[j] 并且 B[j-1] <= A[i] * * 对于临界条件的处理: * 假设A[i-1],B[j-1],A[i],B[i]总是存在的。对于i=0,i=m,j=0,j=n这些临界情况,我们只需要规定 * A[-1] = B[-1] = 负无穷大,A[m] = B[n] = 正无穷大。 * 当一个数组不出现前一部分时,对应的值为负无穷,就不会对前一部分的最大值产生影响 * 当一个数组不出现后一部分时,对应的值为正无穷,就不会对后一部分的最小值产生影响 * * 可以将<三>简化为:在[0,m]种找到最大的i,使得:A[i-1] <= B[j],其中j = (m+n+1)/2 - i * 证明过程:(1)当i从0~m递增时,A[i-1]递增,B[j]递减,所以一定存在一个最大的i满足A[i-1] <= B[j] * (2)如果i是最大的,那么说明i+1不满足。将i+1带入可以得到A[i] > B[j-1],也就是B[j-1]<A[i]。 * * 因此我们可以对i在[0,m]的区间进行二分搜索,找到最大的满足A[i-1] <= B[j]的i值。 * 程序思路: * <一>定义变量: * m: 数组A的长度 * n: 数组B的长度 * median1: 左部分数组的最大值 * median2: 右部分数组的最小值 * left: 在对[0,m]的区间进行二分搜索的左坐标,初始值为0 * right: 在对[0,m]的区间进行二分搜索的右坐标,初始值为m * nums1is1: nums1[i-1] * nums1i: nums1[i] * nums2js1: nums2[j-1] * nums2j: nums2[j] * <2>程序逻辑详情如下代码 * * * * @param nums1 * @param nums2 * @return */ public static double findMedianSortedArrays2(int[] nums1, int[] nums2){ //需要保证 nums1的长度比nums2的长度小,如果nums1.length > nums2.length,则对调两个数组 if(nums1.length > nums2.length){ return findMedianSortedArrays2(nums2, nums1); } //定义 //数组的长度 m, n //前一部分的最大值 median1 //后一部分的最小值 median2 //二分查找开始的左坐标 left //二分查找开始的右坐标 right //nums1[i-1],nums1[i],nums2[j-1],nums2[j] int m = nums1.length; int n = nums2.length; int median1 = 0; int median2 = 0; int left = 0; int right = m; int nums1is1 = 0; int nums1i = 0; int nums2js1 = 0; int nums2j = 0; while (left <= right){ int i = (left + right) / 2; int j = (m + n + 1) / 2 - i; if(i == 0){ nums1is1 = Integer.MIN_VALUE; }else{ nums1is1 = nums1[i-1]; } if(i == m){ nums1i = Integer.MAX_VALUE; }else{ nums1i = nums1[i]; } if(j == 0){ nums2js1 = Integer.MIN_VALUE; }else{ nums2js1 = nums2[j-1]; } if(j == n){ nums2j = Integer.MAX_VALUE; }else{ nums2j = nums2[j]; } //nums1is < nums2j 或者是 nums1is <= nums2j 都是可以的,不影响median1,median2的值改变 if(nums1is1 < nums2j){ median1 = Math.max(nums1is1, nums2js1); median2 = Math.min(nums1i, nums2j); left = i + 1; }else{ right = i - 1; } } int len = m + n; if(len % 2 == 0){ return (median1 + median2) / 2.0; }else{ return median1; } } }
91028191c265850a4d68760d2d3794108c0a1ad0
cfc011bce78edb05e883ed8c4bcb1341fe5331b2
/src/main/java/com/levemus/gliderhud/FlightDisplay/Recon/Compass/BearingDisplay.java
3fba69391ce62a34df605eef394e8e074b738058
[]
no_license
Levemus/GliderHUD
eae7215f449f04bfbb4b1ba6f37a80fa9800fd1c
e7aa2d0b2cae0c2e3494af242714db2c58609d1c
refs/heads/master
2016-08-12T18:34:05.523649
2016-03-05T01:44:43
2016-03-05T01:44:43
47,078,976
3
2
null
null
null
null
UTF-8
Java
false
false
1,920
java
package com.levemus.gliderhud.FlightDisplay.Recon.Compass; /* Both the author and publisher makes no representations or warranties about the suitability of this software, either expressed or implied, including but not limited to the implied warranties of merchantability, fitness for a particular purpose or noninfringement. Both the author and publisher shall not be liable for any damages suffered as a result of using, modifying or distributing the software or its derivatives. (c) 2015 Levemus Software, Inc. */ import android.app.Fragment; import android.graphics.Matrix; import android.view.View; import android.widget.ImageView; import com.levemus.gliderhud.FlightData.Processors.Factory.ProcessorID; import com.levemus.gliderhud.FlightData.Processors.Processor; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.UUID; /** * Created by mark@levemus on 15-12-29. */ // this class is only applicable within the context of the compass display class BearingDisplay extends CompassSubDisplay { @Override public HashSet<UUID> processorIDs() { return new HashSet<>(Arrays.asList( ProcessorID.BEARING, ProcessorID.GROUNDSPEED)); } public void display(Fragment parent, HashMap<UUID, Object> results) { if(mImageView == null) { mImageView = (ImageView) parent.getActivity().findViewById(com.levemus.gliderhud.R.id.bearing_pointer); mImageView.setVisibility(View.VISIBLE); } displayImage(parent, (double)results.get(ProcessorID.BEARING)); } private double MIN_GROUND_SPEED = 0.3; @Override public boolean canDisplay(HashMap<UUID, Object> results) { return results.containsKey(ProcessorID.BEARING) && results.containsKey(ProcessorID.GROUNDSPEED) && (Double)results.get(ProcessorID.GROUNDSPEED) > MIN_GROUND_SPEED; } }
190be8292bc58916beef3a19f75e18d6a87e6367
f41f909c7f93aae8c89c3c2bfbab6fd08fb6a589
/src/main/java/com/test/predqm/job/handler/PreDMQMJobHandler.java
d3bc5a2ec0bc31c5275918871c1e517f7d7fee90
[]
no_license
rakeshpriyad/sapient-code-excersize
c0f146148b5c917e023eec9cd25b009da0630381
f8ae1bb0bc49a23fcf55f2be0ab9e633cd3293f9
refs/heads/master
2020-03-16T23:09:01.839230
2018-05-12T10:39:31
2018-05-12T10:39:31
133,067,103
0
0
null
null
null
null
UTF-8
Java
false
false
2,090
java
package com.test.predqm.job.handler; import com.test.predqm.job.CustomerDataJob; import com.test.predqm.job.JobParameter; import com.test.predqm.launcher.CustomerJobLauncher; import com.test.predqm.launcher.JobStatus; import com.test.predqm.model.Customer; import com.test.predqm.processor.CustomerDataProcessor; import com.test.predqm.processor.ItemProcessor; import com.test.predqm.reader.CustomerFileReader; import com.test.predqm.translator.CustomerInputTranslator; import com.test.predqm.translator.CustomerOutputTranslator; import com.test.predqm.utils.PropertyUtils; import com.test.predqm.writer.CustomerFileWriter; import static com.test.predqm.constant.Constants.INPUT_FILE_NAME; import static com.test.predqm.constant.Constants.OUTPUT_FILE_NAME; public class PreDMQMJobHandler { public static void main(String[] args) { handleCustomerJob(); } public static void handleCustomerJob() { PropertyUtils properties = new PropertyUtils("G:\\\\RAKESH\\\\rajesh-ws\\\\PREDQM\\\\resources\\\\application.properties"); String inputFileName = properties.getProperty(INPUT_FILE_NAME) + "customer.csv" ;//"C:\\Users\\aayushraj\\Desktop\\file\\" + "customer.txt"; String outputFileName = properties.getProperty(OUTPUT_FILE_NAME) + "outputcustomer.csv";//"C:\\Users\\aayushraj\\Desktop\\file\\" + "customer2.txt"; JobParameter parameter = new JobParameter(); CustomerJobLauncher cLauncher = new CustomerJobLauncher(parameter); CustomerInputTranslator inputTranslator = new CustomerInputTranslator(); CustomerFileReader reader = new CustomerFileReader(inputTranslator, inputFileName); ItemProcessor<Customer, Customer> processor = new CustomerDataProcessor(); CustomerOutputTranslator outputTranslator = new CustomerOutputTranslator(); CustomerFileWriter writer = new CustomerFileWriter(outputTranslator, outputFileName); writer.write(reader.read()); CustomerDataJob cJob = new CustomerDataJob(reader, processor, writer); JobStatus status = cLauncher.launch(cJob); System.out.println(status); } }
20eb0960d8c3bbe0ac6d14b789511e41de5f5557
b6bba1ed17c3c29ec648a4e5da8a7b240ef3b53a
/src/main/java/eu/merlevede/util/DoubleTernaryOperator.java
21cae49e4791cf33c7c664c0ec2e34b20fcc1100
[]
no_license
JonMerlevede/FlipIt
ff20236703364729065d3201cd4e41e4caa1a3f2
0df0b605f3837cb7130727cb8d37397d030448dc
refs/heads/master
2020-12-23T22:32:13.709539
2016-08-11T12:54:59
2016-08-11T12:54:59
65,385,699
0
0
null
null
null
null
UTF-8
Java
false
false
200
java
package eu.merlevede.util; /** * Created by jonat on 30/05/2016. */ @FunctionalInterface public interface DoubleTernaryOperator { double applyAsDouble(double arg1, double arg2, double arg3); }
656e96339d69dab1df5e2791ff00ba2b0b84e9fb
1ab19d16b3ba1a8de44a6c733efdb376f03320fe
/api/mods/defeatedcrow/api/charm/package-info.java
b88e44adaa15cd6f226c78918c7e7d35b15d200f
[]
no_license
mezz/BuildcraftCompat
e36650ce341c771f4c2ae7d1a0f14bd8df369aa9
e11494e6f8b54b93080b6e3c25516e9052c970a9
refs/heads/6.5.x
2020-12-11T05:54:47.835811
2015-06-07T05:30:06
2015-06-07T05:30:06
36,623,014
1
0
null
2015-05-31T21:29:52
2015-05-31T21:29:52
Java
UTF-8
Java
false
false
444
java
/** * Copyright (c) defeatedcrow, 2013 * URL:http://forum.minecraftuser.jp/viewtopic.php?f=13&t=17657 * * Apple&Milk&Tea! is distributed under the terms of the Minecraft Mod Public License 1.0, or MMPL. * Please check the License(MMPL_1.0).txt included in the package file of this Mod. */ @API(apiVersion="2.6", owner="DCsAppleMilk", provides="AppleMilkTeaAPI|charm") package mods.defeatedcrow.api.charm; import cpw.mods.fml.common.API;
b5dac6f4413c0a46d6310b360e63575fbe1503b2
00727ffaefd8279b5c12afb464244eb5f95d2db1
/app/src/androidTest/java/com/example/a51capital/ExampleInstrumentedTest.java
cd720cf98727fe7cada3f10cc8fc91810c558e4c
[]
no_license
Santana-macharia/51capital-app
972eb78216831293d4f0739fc6a44cf7e6ffbc5a
320d2391bcf11813f23faec6ec46f0f12e8fed4d
refs/heads/master
2023-01-30T00:06:27.389917
2023-01-25T17:49:38
2023-01-25T17:49:38
318,179,644
0
0
null
null
null
null
UTF-8
Java
false
false
760
java
package com.example.a51capital; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.example.a51capital", appContext.getPackageName()); } }
5ea76829fa2e67cad47eb238bf4f89c7881964a5
30de6808684fd2f3fe750d0f54c72b4b227ec30b
/app/src/main/java/com/tin/whattoeat/Activity/GroceriesActivity.java
9b6c93d7c34d2f9704e99168ed16a9a0858cb562
[]
no_license
tincheleky/wfd-app
8bbd4cb743a65ea097837754759d823f83a4e5ce
4e6e51a9fe7dbdcff70094c0570effd28e60b5be
refs/heads/master
2020-04-09T15:20:41.115264
2016-09-28T04:34:49
2016-09-28T04:34:49
68,146,940
0
0
null
null
null
null
UTF-8
Java
false
false
7,730
java
package com.tin.whattoeat.Activity; import android.app.Activity; import android.content.Intent; import android.graphics.Paint; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.tin.whattoeat.Listener.OnSwipeListener; import com.tin.whattoeat.Model.GlobalData; import com.tin.whattoeat.Model.GroceriesManager; import com.tin.whattoeat.Model.GroceryItem; import com.tin.whattoeat.R; public class GroceriesActivity extends AppCompatActivity { /** * Whether or not the activity is in two-pane mode, i.e. running on a tablet * device. */ Activity activity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_groceries); Toolbar toolbar = (Toolbar) findViewById(R.id.groceries_toolbar); setSupportActionBar(toolbar); toolbar.setTitle("Groceries"); activity = this; // Show the Up button in the action bar. ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.groceries_fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); View recyclerView = findViewById(R.id.groceries_recycler_view); assert recyclerView != null; setupRecyclerView((RecyclerView) recyclerView); } private void setupRecyclerView(@NonNull RecyclerView recyclerView) { recyclerView.setAdapter(new GroceriesRecyclerAdapter(GlobalData.getSelectedRecipes())); } public class GroceriesRecyclerAdapter extends RecyclerView.Adapter<GroceriesRecyclerAdapter.ViewHolder> { private final GroceriesManager groceriesManager; public GroceriesRecyclerAdapter(GroceriesManager groceriesManager) { this.groceriesManager = groceriesManager; System.out.println("------------ TESTING +++ ::: " + groceriesManager.getItemsCount() ); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()) .inflate(R.layout.groceries_list_content, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { holder.mItem = groceriesManager.at(position); holder.mGroceriesItemName.setText(holder.mItem.getIngredient().getIngName()); holder.mGroceriesItemQuantity.setText(String.valueOf(holder.mItem.getQuantity())); holder.mGroceriesItemAdd.setVisibility(ImageView.INVISIBLE); holder.mGroceriesItemAdd.setEnabled(false); holder.mGroceriesItemRemove.setVisibility(ImageView.INVISIBLE); holder.mGroceriesItemRemove.setEnabled(false); if(Integer.valueOf(holder.mGroceriesItemQuantity.getText().toString()) == 0){ holder.mGroceriesItemName.setPaintFlags(holder.mGroceriesItemName.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); } holder.mView.setOnClickListener(v -> { //WHAT HAPPENS IF CLICKED }); System.out.println("+++++++ TESTING: " + groceriesManager.getItemsCount()); } @Override public int getItemCount() { return groceriesManager.getItemsCount(); } public class ViewHolder extends RecyclerView.ViewHolder{ public final View mView; public final TextView mGroceriesItemName; public final TextView mGroceriesItemQuantity; public final ImageView mGroceriesItemAdd; public final ImageView mGroceriesItemRemove; public GroceryItem mItem; public ViewHolder(View view) { super(view); mView = view; mView.setOnTouchListener(new OnSwipeListener(GroceriesActivity.this){ @Override public void onSwipeRight(){ System.out.println("TESTING SWIPE RIGHT"); mGroceriesItemAdd.setVisibility(ImageView.INVISIBLE); mGroceriesItemAdd.setEnabled(false); mGroceriesItemRemove.setVisibility(ImageView.INVISIBLE); mGroceriesItemRemove.setEnabled(false); } @Override public void onSwipeLeft(){ System.out.println("TESTING SWIPE LEFT"); mGroceriesItemAdd.setVisibility(ImageView.VISIBLE); mGroceriesItemAdd.setEnabled(true); mGroceriesItemRemove.setVisibility(ImageView.VISIBLE); mGroceriesItemRemove.setEnabled(true); } }); mGroceriesItemName = (TextView) view.findViewById(R.id.groceries_item_name); mGroceriesItemQuantity = (TextView) view.findViewById(R.id.groceries_item_quantity); mGroceriesItemAdd = (ImageView) view.findViewById(R.id.groceries_item_add); mGroceriesItemRemove = (ImageView) view.findViewById(R.id.groceries_item_remove); mGroceriesItemAdd.setOnClickListener(v->{ mItem.increaseQuantity(); mGroceriesItemQuantity.setText(String.valueOf(mItem.getQuantity())); if(mItem.getQuantity() > 0) { mGroceriesItemName.setPaintFlags(0); } }); mGroceriesItemRemove.setOnClickListener(v->{ mItem.decreaseQuantity(); mGroceriesItemQuantity.setText(String.valueOf(mItem.getQuantity())); if(mItem.getQuantity() == 0) { mGroceriesItemName.setPaintFlags(mGroceriesItemName.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); } }); } @Override public String toString() { return super.toString() + " '" + mGroceriesItemName.getText() + "'"; } } } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // navigateUpTo(new Intent(this, HomeActivity.class)); return true; } return super.onOptionsItemSelected(item); } }
81a105a2eb85e1ebf30b75fb8f61bf15c62d176f
4fc577208073aded9dd4b830623eca6ae972b543
/manager/biz/src/main/java/com/alibaba/otter/manager/biz/remote/impl/StatsRemoteServiceImpl.java
07cf56c15505600c5e35a67f226ab56993520de4
[ "Apache-2.0" ]
permissive
khitanwarrior/otter
bcf9267c98144b803344bcf4ddb94a833ddc8021
3579aa9453c1a5f69df257e81ca74446cbb4d88d
refs/heads/master
2021-01-25T02:38:12.336001
2013-09-02T10:07:10
2013-09-02T10:07:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,425
java
/* * Copyright (C) 2010-2101 Alibaba Group Holding Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.otter.manager.biz.remote.impl; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.Assert; import com.alibaba.otter.manager.biz.remote.StatsRemoteService; import com.alibaba.otter.manager.biz.statistics.delay.DelayStatService; import com.alibaba.otter.manager.biz.statistics.table.TableStatService; import com.alibaba.otter.manager.biz.statistics.throughput.ThroughputStatService; import com.alibaba.otter.shared.common.model.statistics.delay.DelayCount; import com.alibaba.otter.shared.common.model.statistics.delay.DelayStat; import com.alibaba.otter.shared.common.model.statistics.table.TableStat; import com.alibaba.otter.shared.common.model.statistics.throughput.ThroughputStat; import com.alibaba.otter.shared.common.model.statistics.throughput.ThroughputType; import com.alibaba.otter.shared.common.utils.thread.NamedThreadFactory; import com.alibaba.otter.shared.communication.core.CommunicationRegistry; import com.alibaba.otter.shared.communication.model.statistics.DelayCountEvent; import com.alibaba.otter.shared.communication.model.statistics.StatisticsEventType; import com.alibaba.otter.shared.communication.model.statistics.TableStatEvent; import com.alibaba.otter.shared.communication.model.statistics.ThroughputStatEvent; import com.google.common.base.Function; import com.google.common.collect.MapMaker; /** * 统计模块远程接口 * * @author jianghang 2011-10-21 下午03:04:40 * @version 4.0.0 */ public class StatsRemoteServiceImpl implements StatsRemoteService { private static final Logger logger = LoggerFactory.getLogger(StatsRemoteServiceImpl.class); private static final int DEFAULT_POOL = 10; private DelayStatService delayStatService; private TableStatService tableStatService; private ThroughputStatService throughputStatService; private Long statUnit = 60 * 1000L; //统计周期,默认60秒 private ScheduledThreadPoolExecutor scheduler; private Map<Long, AvgStat> delayStats; private Map<Long, Map<ThroughputType, ThroughputStat>> throughputStats; public StatsRemoteServiceImpl(){ // 注册一下事件处理 CommunicationRegistry.regist(StatisticsEventType.delayCount, this); CommunicationRegistry.regist(StatisticsEventType.tableStat, this); CommunicationRegistry.regist(StatisticsEventType.throughputStat, this); delayStats = new MapMaker().makeComputingMap(new Function<Long, AvgStat>() { public AvgStat apply(Long pipelineId) { return new AvgStat(); } }); throughputStats = new MapMaker().makeComputingMap(new Function<Long, Map<ThroughputType, ThroughputStat>>() { public Map<ThroughputType, ThroughputStat> apply(Long pipelineId) { return new HashMap<ThroughputType, ThroughputStat>(); } }); scheduler = new ScheduledThreadPoolExecutor(DEFAULT_POOL, new NamedThreadFactory("Otter-Statistics-Server"), new ThreadPoolExecutor.CallerRunsPolicy()); if (statUnit > 0) { scheduler.scheduleAtFixedRate(new Runnable() { public void run() { try { flushDelayStat(); } catch (Exception e) { logger.error("flush delay stat failed!", e); } } }, statUnit, statUnit, TimeUnit.MILLISECONDS); scheduler.scheduleAtFixedRate(new Runnable() { public void run() { try { flushThroughputStat(); } catch (Exception e) { logger.error("flush Throughput stat failed!", e); } } }, statUnit, statUnit, TimeUnit.MILLISECONDS); } } public void onDelayCount(DelayCountEvent event) { Assert.notNull(event); Assert.notNull(event.getCount()); // 更新delay queue的计数器 DelayCount count = event.getCount(); // 构造一次delay stat快照 DelayStat stat = new DelayStat(); stat.setPipelineId(count.getPipelineId()); stat.setDelayNumber(0L); // 不再记录堆积量 stat.setDelayTime(count.getTime()); // 只记录延迟时间 if (statUnit <= 0) { delayStatService.createDelayStat(stat); } else { synchronized (delayStats) { delayStats.get(count.getPipelineId()).merge(stat); } } } public void onThroughputStat(ThroughputStatEvent event) { Assert.notNull(event); Assert.notNull(event.getStats()); if (statUnit <= 0) { for (ThroughputStat stat : event.getStats()) { throughputStatService.createOrUpdateThroughput(stat); } } else { synchronized (throughputStats) { for (ThroughputStat stat : event.getStats()) { Map<ThroughputType, ThroughputStat> data = throughputStats.get(stat.getPipelineId()); ThroughputStat old = data.get(stat.getType()); if (old != null) { //执行合并 old.setNumber(stat.getNumber() + old.getNumber()); old.setSize(stat.getSize() + old.getSize()); if (stat.getEndTime().after(old.getEndTime())) { old.setEndTime(stat.getEndTime()); } if (stat.getStartTime().before(stat.getStartTime())) { stat.setStartTime(stat.getStartTime()); } } else { data.put(stat.getType(), stat); } } } } } public void onTableStat(TableStatEvent event) { Assert.notNull(event); Assert.notNull(event.getStats()); for (TableStat stat : event.getStats()) { tableStatService.updateTableStat(stat); } } private void flushDelayStat() { synchronized (delayStats) { // 需要做同步,避免delay数据丢失 for (Map.Entry<Long, AvgStat> stat : delayStats.entrySet()) { if (stat.getValue().count.get() > 0) { DelayStat delay = new DelayStat(); delay.setPipelineId(stat.getKey()); delay.setDelayTime(stat.getValue().getAvg()); delay.setDelayNumber(0L); delayStatService.createDelayStat(delay); } } delayStats.clear(); } } private void flushThroughputStat() { synchronized (throughputStats) { Collection<Map<ThroughputType, ThroughputStat>> stats = throughputStats.values(); for (Map<ThroughputType, ThroughputStat> stat : stats) { for (ThroughputStat data : stat.values()) { throughputStatService.createOrUpdateThroughput(data); } } throughputStats.clear(); } } public static class AvgStat { private AtomicLong number = new AtomicLong(0L); private AtomicLong count = new AtomicLong(0L); public void merge(DelayStat stat) { count.incrementAndGet(); number.addAndGet(stat.getDelayTime()); } public Long getAvg() { if (count.get() > 0) { return number.get() / count.get(); } else { return 0L; } } } // ===================== setter / getter ===================== public void setDelayStatService(DelayStatService delayStatService) { this.delayStatService = delayStatService; } public void setTableStatService(TableStatService tableStatService) { this.tableStatService = tableStatService; } public void setThroughputStatService(ThroughputStatService throughputStatService) { this.throughputStatService = throughputStatService; } }
b3b81323695ff2a93cddf8cbdaaf4febaf2977bb
95482f145d3e9a24d1805e637ae4915e2975f30f
/app/src/main/java/uz/mold/MoldApplication.java
490c4165b86ddcdcb9888f7175a22fb55a709dd8
[]
no_license
sherbaev/Mold
3001e228b850c469e1e4e89025269709c96d7fde
a303a522661d6a506555bffaf5b6169397541841
refs/heads/master
2020-09-23T05:28:30.760258
2019-08-26T12:24:54
2019-08-26T12:24:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,226
java
package uz.mold; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import uz.mold.lang.LangPref; import uz.mold.lang.LocaleHelper; public class MoldApplication extends Application { private static MoldApplication moldInstance; private static Context resourceContext; public static Context getResourceContext() { if (resourceContext == null) { String language = LangPref.getLanguage(moldInstance); resourceContext = LocaleHelper.setLocale(moldInstance, language); } return resourceContext; } public static String getLangString(int resId) { return getResourceContext().getString(resId); } public static String getLangString(int resId, Object... formatArgs) { return getResourceContext().getString(resId, formatArgs); } public static SharedPreferences getSharedPreferences(String name) { return moldInstance.getSharedPreferences(name, Context.MODE_PRIVATE); } public static void changeLanguageCode() { resourceContext = null; } @Override public void onCreate() { super.onCreate(); moldInstance = this; } }
5c777c074f94fe6b2f152ffdc9767e41cb6421cd
5ae456a396e6d53811ad7d229b6ebba0e2d3c282
/src/review/controller/ReviewWriteServlet.java
729978673f3461c27241032fe8e51f9602fe66bb
[]
no_license
Forthepeople5802/semiProject
8391e31b5d0c6ece371e77af65e2339cd5d93043
2357470b565584118ad0a60e97bcc9313d486b50
refs/heads/master
2020-04-21T18:21:55.474253
2019-02-08T16:53:43
2019-02-08T16:53:43
169,766,808
0
0
null
null
null
null
UTF-8
Java
false
false
2,843
java
package review.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.output.WriterOutputStream; import review.model.service.ReviewService; import review.model.vo.Review; /** * Servlet implementation class ReviewWriteServlet */ @WebServlet("/reviewwrite") public class ReviewWriteServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ReviewWriteServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); int rno=0; int count=0; String check="0"; if(request.getParameter("rno") != null || request.getParameter("count") !=null) { rno=Integer.parseInt(request.getParameter("rno")); count = Integer.parseInt(request.getParameter("count")); check=request.getParameter("check"); } String bid=request.getParameter("bid"); String lid=request.getParameter("lid"); String title=request.getParameter("title"); String content=request.getParameter("content"); int starpoint=Integer.parseInt(request.getParameter("starpoint")); int result=0; if(!(check.equals("1"))) { Review review=new Review(); review.setReview_title(title); review.setReview_Content(content); review.setBusiness_Id(bid); review.setReview_Writer(lid); review.setReview_Grade(starpoint); result=new ReviewService().reviewWrite(review); }else if(check.equals("1")) { Review review=new Review(); review.setNumber(rno); review.setReview_title(title); review.setReview_Content(content); review.setBusiness_Id(bid); review.setReview_Writer(lid); review.setReview_Grade(starpoint); review.setReview_Count(count); result=new ReviewService().reviewWriteModify(review); } System.out.println("몇이냐" + result); response.setContentType("text/html; charset=utf-8;"); if(result > 0) { PrintWriter out = response.getWriter(); out.flush(); out.close(); }else{ } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
[ "DJ@DJ" ]
DJ@DJ
29a8fb270747db269acd8de8c2a556388e53a149
2a6a80619d7266c53a5292e6e0a67f592d9c022d
/app/src/main/java/com/andsomore/sosinfosante/CompteActivity.java
769a97fcab2e2174452e52e62328b6d935773a8b
[]
no_license
fried19/SosInfoSante
ec73e70370a665d138bbc33ad9603ede6a00bd79
7d57451e13bc1d6f48fba4c35ab3e760c2a74a8d
refs/heads/master
2021-01-03T11:17:38.070873
2020-02-12T16:23:46
2020-02-12T16:23:46
240,058,988
0
0
null
null
null
null
UTF-8
Java
false
false
344
java
package com.andsomore.sosinfosante; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class CompteActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_compte); } }