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
de13513092b09886c085515101419b7ceb0707d0
be0eb6f465c1566327b56d004c8300f468bce9ab
/src/proiect/Controller5.java
2b10c584838acf0728eb43e12979c866cfd7bb34
[]
no_license
AdrianLupu21/ISO2768ToleranceCalculator
fc90f19a712b80f499d1e0b0535e55f636835d01
8f9c4bb0207763819d181fd6b12f539d48c897bd
refs/heads/master
2020-04-27T21:19:07.924627
2019-03-09T13:31:55
2019-03-09T13:31:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
13,111
java
package proiect; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.file.Paths; import java.sql.*; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextField; import javafx.scene.control.Alert.AlertType; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class Controller5 { private double valoareAbatereAlezaj = -1; private double xOffset; private double yOffset; private String tipAbatereAlezaj; private double campTolerantaAlezaj = -1; private int valoareAbatereArbore = -1; private String tipAbatereArbore; private double campTolerantaArbore = -1; private double[] showResults; static Stage stage = null; @FXML private VBox text; @FXML private ScrollPane scroll; @FXML private AnchorPane anchor; @FXML private TextField fiArbore; @FXML private ChoiceBox<String> tarbore; @FXML private ChoiceBox<String> itarbore; @FXML private TextField fialezaj; @FXML private ChoiceBox<String> talezaj; @FXML private ChoiceBox<String> italezaj; @FXML private Button calculate; @FXML private Button back; @FXML private VBox minimize; @FXML private VBox close; @FXML void onClose(MouseEvent event) { Platform.exit(); } @FXML void onMinimize(MouseEvent event) { Stage stage = (Stage) minimize.getScene().getWindow(); stage.setIconified(true); } @FXML void initialize() throws URISyntaxException { scroll.setFitToHeight(true); //adaug date in scroll option { String sqlAlezajClasa = "SELECT alezaje.clasa FROM alezaje GROUP BY alezaje.clasa ORDER BY alezaje.clasa"; String sqlArboreClasa = "SELECT arbori.clasa FROM arbori GROUP BY arbori.clasa ORDER BY arbori.clasa"; String sqlTolerFund = "SELECT tolerante_fundamentale.treapta FROM tolerante_fundamentale GROUP BY treapta ORDER BY treapta"; try(Statement s1 = dbConn("abateri.accdb")){ s1.execute(sqlAlezajClasa); ResultSet alezajClasa = s1.getResultSet(); s1.execute(sqlArboreClasa); ResultSet arboreClasa = s1.getResultSet(); s1.execute(sqlTolerFund); ResultSet tolerFund = s1.getResultSet(); while(alezajClasa != null && alezajClasa.next()) { talezaj.getItems().add(alezajClasa.getString(1)); } while(arboreClasa != null && arboreClasa.next()) { tarbore.getItems().add(arboreClasa.getString(1)); } while(tolerFund != null && tolerFund.next()) { italezaj.getItems().add(tolerFund.getString(1)); itarbore.getItems().add(tolerFund.getString(1)); } }catch(Exception e) { System.out.println(e.getCause() + e.getMessage()); } } } @FXML void onBack(ActionEvent event) throws IOException { Parent newScene = null; stage = (Stage) back.getScene().getWindow(); newScene = FXMLLoader.load(getClass().getResource("../View.fxml")); Scene scene = new Scene(newScene); stage.setScene(scene); stage.show(); newScene.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { xOffset = event.getSceneX(); yOffset = event.getSceneY(); } }); newScene.setOnMouseDragged(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { stage.setX(event.getScreenX() - xOffset); stage.setY(event.getScreenY() - yOffset); } }); } @FXML void onCalculate(ActionEvent event) throws SQLException { text.getChildren().clear(); System.out.println(talezaj.getValue()); if(fiArbore.getText().equals("")) { alerta("Trebuiesc introduse diametrele alezajului si arborelui"); }else { try(Statement s = dbConn("abateri.accdb")){ String sqlAlezaj = "SELECT alezaje.valoare,alezaje.tip_abatere,alezaje.treapta_toler," + "dimensiuni.peste,dimensiuni.pana_la_inclusiv FROM alezaje INNER JOIN dimensiuni ON " + "alezaje.dimensiuni=dimensiuni.ID WHERE alezaje.clasa = \""+ talezaj.getValue()+"\" AND " + "dimensiuni.peste < " + fiArbore.getText() + " AND dimensiuni.pana_la_inclusiv >=" + fiArbore.getText(); String sqlArbore = "SELECT arbori.valoare,arbori.tip_abatere,arbori.treapta_toler," + "dimensiuni.peste,dimensiuni.pana_la_inclusiv FROM arbori INNER JOIN dimensiuni ON " + "arbori.dimensiuni=dimensiuni.ID WHERE arbori.clasa = \""+tarbore.getValue()+"\" AND " + "dimensiuni.peste < " + fiArbore.getText() + " AND dimensiuni.pana_la_inclusiv >=" + fiArbore.getText(); String sqlTreaptaAlezaj = "SELECT tolerante_fundamentale.valoare from tolerante_fundamentale " + "INNER JOIN dimensiuni_tol_fund ON tolerante_fundamentale.dimensiuni = dimensiuni_tol_fund.ID" + " WHERE tolerante_fundamentale.treapta = \""+italezaj.getValue()+"\" AND " + "dimensiuni_tol_fund.peste < " + fiArbore.getText() + " AND dimensiuni_tol_fund.pana_la_inclusiv >=" + fiArbore.getText(); String sqlTreaptaArbore = "SELECT tolerante_fundamentale.valoare from tolerante_fundamentale " + "INNER JOIN dimensiuni_tol_fund ON tolerante_fundamentale.dimensiuni = dimensiuni_tol_fund.ID" + " WHERE tolerante_fundamentale.treapta = \""+itarbore.getValue()+"\" AND " + "dimensiuni_tol_fund.peste < " + fiArbore.getText() + " AND dimensiuni_tol_fund.pana_la_inclusiv >=" + fiArbore.getText(); String sqlAlezajSpecial = "SELECT abateriSpecificeAlezaje.valoare, abateriSpecificeAlezaje.delta\r\n" + "FROM ((abateriSpecificeAlezaje INNER JOIN alezaje ON abateriSpecificeAlezaje.clasa = alezaje.clasa )INNER JOIN" + " dimensiuni ON abateriSpecificeAlezaje.dimensiuni = dimensiuni.ID)\r\n" + "WHERE abateriSpecificeAlezaje.clasa= \"" + talezaj.getValue() +"\" AND abateriSpecificeAlezaje.treapta LIKE"+ "\"*,"+italezaj.getValue()+",*\"\r\n" + "AND dimensiuni.peste <" + fiArbore.getText() + " AND dimensiuni.pana_la_inclusiv >= "+ fiArbore.getText() +" GROUP BY " + "abateriSpecificeAlezaje.delta, abateriSpecificeAlezaje.valoare ;\r\n" + ""; String sqlArboreSpecial = "SELECT abateriSpecificeArbori.valoare\r\n" + "FROM ((abateriSpecificeArbori INNER JOIN arbori ON abateriSpecificeArbori.clasa = arbori.clasa )INNER JOIN dimensiuni ON abateriSpecificeArbori.dimensiuni = dimensiuni.ID)\r\n" + "WHERE abateriSpecificeArbori.clasa= \"" + tarbore.getValue() +"\" AND abateriSpecificeArbori.treapta LIKE"+ "\"*,"+itarbore.getValue()+",*\"\r\n" + "AND dimensiuni.peste <" + fiArbore.getText() + " AND dimensiuni.pana_la_inclusiv >= "+ fiArbore.getText() +" GROUP BY abateriSpecificeArbori.valoare ;\r\n" + ""; String sqlDelta = "SELECT delta.valoare FROM delta INNER JOIN dimensiuni ON dimensiuni.ID = delta.dimensiuni " + "WHERE delta.treapta = " + "\"" + italezaj.getValue() + "\""+ " AND dimensiuni.peste <" + fiArbore.getText() + " AND dimensiuni.pana_la_inclusiv >= " + fiArbore.getText() ; //fiArbore = fiAlezaj = dimensiunea nominala s.execute(sqlAlezaj); ResultSet rsAlezaj = s.getResultSet(); s.execute(sqlArbore); ResultSet rsArbore = s.getResultSet(); s.execute(sqlTreaptaAlezaj); ResultSet rsTreaptaAlezaj = s.getResultSet(); s.execute(sqlTreaptaArbore); ResultSet rsTreaptaArbore = s.getResultSet(); if(talezaj.getValue().equals("JS")) { valoareAbatereAlezaj = 0; tipAbatereAlezaj = "JS"; }else if(talezaj.getValue().equals("H")){ valoareAbatereAlezaj = 0; tipAbatereAlezaj = "H"; } else { while(rsAlezaj!=null && rsAlezaj.next()) { if(rsAlezaj.getBoolean(3)) { valoareAbatereAlezaj = Integer.parseInt(rsAlezaj.getString(1)); }else { s.execute(sqlAlezajSpecial); ResultSet rsAlezajSpecial = s.getResultSet(); while(rsAlezajSpecial!=null && rsAlezajSpecial.next()) { valoareAbatereAlezaj = (double) Integer.parseInt(rsAlezajSpecial.getString(1)); if(rsAlezajSpecial.getBoolean(2)) { s.execute(sqlDelta); ResultSet rsDelta = s.getResultSet(); while(rsDelta!=null && rsDelta.next()) { valoareAbatereAlezaj += Double.parseDouble(rsDelta.getString(1)); } } } } tipAbatereAlezaj = rsAlezaj.getString(2); if(rsAlezaj.getString(3)!="toate" && checkTolerante(rsAlezaj.getString(3),italezaj.getValue())) { alerta("Nu exista valori in standard pentru : IT" + italezaj.getValue()); } } } System.out.println("valoare abatere alezaj = "+ valoareAbatereAlezaj); if(valoareAbatereAlezaj == -1) { alerta("nu exista dimensiuni pentru diametrul dat"); return; } if(tarbore.getValue().equals("js")) { valoareAbatereArbore = 0; tipAbatereArbore = "js"; }else if(tarbore.getValue().equals("h")){ valoareAbatereArbore = 0; tipAbatereArbore = "h"; }else{ while(rsArbore!=null && rsArbore.next()) { if(rsArbore.getBoolean(3)) { valoareAbatereArbore = Integer.parseInt(rsArbore.getString(1)); }else { s.execute(sqlArboreSpecial); ResultSet rsArboreSpecial = s.getResultSet(); while(rsArboreSpecial!=null && rsArboreSpecial.next()) { valoareAbatereArbore = Integer.parseInt(rsArboreSpecial.getString(1)); } } System.out.println("valoare abatere arbore :" + valoareAbatereArbore); tipAbatereArbore = rsArbore.getString(2); } } if(valoareAbatereArbore == -1) { alerta("nu exista dimensiuni pentru diametrul dat"); return; } while(rsTreaptaAlezaj!=null && rsTreaptaAlezaj.next()) { if(rsTreaptaAlezaj.getString(1).equals("")) { alerta("Nu exista valori pentru :" + italezaj.getValue()); return; } campTolerantaAlezaj = Double.parseDouble(rsTreaptaAlezaj.getString(1)); System.out.println("campTolerantaAlezaj " + campTolerantaAlezaj); } if(campTolerantaAlezaj == -1) { alerta("nu exista dimensiuni pentru diametrul dat"); return; } while(rsTreaptaArbore!=null && rsTreaptaArbore.next()) { campTolerantaArbore = Double.parseDouble(rsTreaptaArbore.getString(1)); System.out.println("campTolerantaArbore " + campTolerantaArbore); } if(campTolerantaArbore == -1) { alerta("nu exista dimensiuni pentru diametrul dat"); System.out.println("Adfadf"); return; } Model5 model = new Model5(); model.setText(text); model.setAnchor(anchor); showResults = model.calcAjustaj(Integer.parseInt(fiArbore.getText()), valoareAbatereArbore, valoareAbatereAlezaj, campTolerantaArbore, campTolerantaAlezaj, tipAbatereArbore, tipAbatereAlezaj); raspuns("Ajustajul este: " + model.tipAjustaj((int) showResults[showResults.length - 1]),model.ajustajMess(showResults)); valoareAbatereAlezaj = -1; valoareAbatereArbore = -1; campTolerantaAlezaj = -1; tipAbatereArbore = null; campTolerantaArbore = -1; showResults = null; } catch(Exception e ) { System.out.println(e); } } } void alerta(String message) { Alert alert = new Alert(AlertType.ERROR); alert.setTitle("Error"); alert.setContentText(message); alert.showAndWait(); } void raspuns(String header, String message) { Alert alert = new Alert(AlertType.INFORMATION); alert.setTitle("Raspuns"); alert.setHeaderText(header); alert.setContentText(message); alert.show(); } Statement dbConn (String dbName) throws URISyntaxException, SQLException { URI uri = new URI("jdbc:ucanaccess",Paths.get(dbName).toUri().getPath(),null); System.out.println(uri.toString()); System.out.println(uri.toString().replaceAll("/","//")); Connection conn = DriverManager.getConnection(uri.toString().replaceAll("/","//"), "", ""); Statement st = conn.createStatement(); return st; } Boolean checkTolerante(String dbTolerante,String inputTolerante) { String str[] = dbTolerante.split(","); for(String elem : str) { if(elem == inputTolerante) return true; } return false; } }
[ "adrian_claudiu.lupu@stud.imst.upb.ro" ]
adrian_claudiu.lupu@stud.imst.upb.ro
e2044a4aa3db14a9df36e57e10a5b85eeaf7c682
2b64436768a7c811efa57e1cb0f9d47501c11f0f
/app/src/main/java/com/coolweather/android/WeatherActivity.java
6fc1e90b857ac3b6b578ea9aad1044797fab0744
[ "Apache-2.0" ]
permissive
SuZHui/coolweather
ce43ec756c7bec3ba0f07cfe049b527a6b39f006
4d08a60fb29f85d66252497b02371a0037686460
refs/heads/master
2021-07-23T15:41:30.628280
2017-11-02T02:52:38
2017-11-02T02:52:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
9,457
java
package com.coolweather.android; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Build; import android.preference.PreferenceManager; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.coolweather.android.gson.Forecast; import com.coolweather.android.gson.Weather; import com.coolweather.android.service.AutoUpdateReceiver; import com.coolweather.android.util.HttpUtil; import com.coolweather.android.util.Utility; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class WeatherActivity extends AppCompatActivity { // local variable public String weatherId; // layout object private ScrollView weatherLayout; private TextView titleCity; private TextView titleUpdateTime; private TextView degreeText; private TextView weatherInfoText; private LinearLayout forecastLayout; private TextView aqiText; private TextView pm25Text; private TextView comfortText; private TextView carWashText; private TextView sportText; private ImageView bingPicImg; public SwipeRefreshLayout swipeRefresh; private Button navButton; public DrawerLayout drawerLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= 21) { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); getWindow().setStatusBarColor(Color.TRANSPARENT); } setContentView(R.layout.activity_weather); // initialize view weatherLayout = findViewById(R.id.weather_layout); titleCity = findViewById(R.id.title_city); titleUpdateTime = findViewById(R.id.title_update_time); degreeText = findViewById(R.id.degree_text); weatherInfoText = findViewById(R.id.weather_info_text); forecastLayout = findViewById(R.id.forecast_layout); aqiText = findViewById(R.id.aqi_text); pm25Text = findViewById(R.id.pm25_text); comfortText = findViewById(R.id.comfort_text); carWashText = findViewById(R.id.car_wash_text); sportText = findViewById(R.id.sport_text); bingPicImg = findViewById(R.id.bing_pic_img); swipeRefresh = findViewById(R.id.swipe_refresh); drawerLayout = findViewById(R.id.drawer_layout); navButton = findViewById(R.id.nav_button); swipeRefresh.setColorSchemeResources(R.color.colorPrimary); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); String weatherString = prefs.getString("weather", null); // final String weatherId; if (weatherString != null) { // 本地有缓存天气数据 Weather weather = Utility.handleWeatherResponse(weatherString); weatherId = weather.basic.weatherId; showWeatherInfo(weather); } else { // 无缓存,从服务器获取 weatherId = getIntent().getStringExtra("weather_id"); weatherLayout.setVisibility(View.INVISIBLE); //隐藏 requestWeather(weatherId); } // refresh event swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { Log.d("1111", "onRefresh: "+weatherId); requestWeather(weatherId); } }); // drawer button event navButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { drawerLayout.openDrawer(GravityCompat.START); } }); // fetch background img String bingPic = prefs.getString("bing_pic", null); if (bingPic != null) { Glide.with(this).load(bingPic).into(bingPicImg); } else { loadBingPic(); } } /** * 加载背景图 */ private void loadBingPic() { String requestBingPic = "http://guolin.tech/api/bing_pic"; HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { final String bingPic = response.body().string(); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit(); editor.putString("bing_pic", bingPic); editor.apply(); runOnUiThread(new Runnable() { @Override public void run() { Glide.with(WeatherActivity.this).load(bingPic).into(bingPicImg); } }); } }); } /** * 根据天气id请求城市天气信息 * @param weatherId */ public void requestWeather(final String weatherId) { String weatherUrl = "http://guolin.tech/api/weather?cityid="+weatherId+"&key=dfddde40abce4da7b33ae3378579cac6"; HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT) .show(); swipeRefresh.setRefreshing(false); } }); } @Override public void onResponse(Call call, Response response) throws IOException { final String responseText = response.body().string(); final Weather weather = Utility.handleWeatherResponse(responseText); runOnUiThread(new Runnable() { @Override public void run() { if (weather != null && "ok".equals(weather.status)) { SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(WeatherActivity.this).edit(); editor.putString("weather", responseText); editor.apply(); showWeatherInfo(weather); } else { Toast.makeText(WeatherActivity.this, "获取天气信息失败", Toast.LENGTH_SHORT).show(); } swipeRefresh.setRefreshing(false); } }); } }); loadBingPic(); } /** * 处理、展示Weather实体类的数据 * @param weather */ private void showWeatherInfo(Weather weather) { String cityName = weather.basic.cityName; String updateTime = weather.basic.update.updateTime.split(" ")[1]; //13:47 String degree = weather.now.temperature + "℃"; String weatherInfo = weather.now.more.info; titleCity.setText(cityName); titleUpdateTime.setText(updateTime); degreeText.setText(degree); weatherInfoText.setText(weatherInfo); forecastLayout.removeAllViews(); for (Forecast forecast : weather.forecastList) { View view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false); TextView dateText = view.findViewById(R.id.date_text); TextView infoText = view.findViewById(R.id.info_text); TextView maxText = view.findViewById(R.id.max_text); TextView minText = view.findViewById(R.id.min_text); dateText.setText(forecast.date); infoText.setText(forecast.more.info); maxText.setText(forecast.temperature.max); minText.setText(forecast.temperature.min); forecastLayout.addView(view); } if (weather.aqi != null) { aqiText.setText(weather.aqi.city.aqi); pm25Text.setText(weather.aqi.city.pm25); } String comfort = "舒适度: " + weather.suggestion.comfort.info; String carWash = "洗车指数: " + weather.suggestion.carWash.info; String sport = "运动指数: " + weather.suggestion.sport.info; comfortText.setText(comfort); carWashText.setText(carWash); sportText.setText(sport); weatherLayout.setVisibility(View.VISIBLE); Intent intent = new Intent(this, AutoUpdateReceiver.class); startService(intent); } }
[ "362680581@qq.com" ]
362680581@qq.com
349557ef6bdf2652fdf9f5c8e078e122d7104090
f381142e30758f9dd97f34dfe160fe28416fd638
/app/src/main/java/com/example/waracci/teams/ui/PlayersActivity.java
3132425efc709ab1e68bdc79cd2671aa0bcff386
[]
no_license
lolisme/Sports-team
aa7eeb0088bade69fb60e4adbbf1f69ffaa653cb
1cf52d34ebad3be37c4ba95d23491ab6977eaa4e
refs/heads/master
2021-07-06T13:41:34.488655
2017-10-03T04:58:03
2017-10-03T04:58:03
104,491,315
0
0
null
2017-10-03T05:00:36
2017-09-22T15:40:46
Java
UTF-8
Java
false
false
4,738
java
package com.example.waracci.teams.ui; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.example.waracci.teams.Constants; import com.example.waracci.teams.R; import com.example.waracci.teams.adapters.PlayerListAdapter; import com.example.waracci.teams.models.Player; import com.example.waracci.teams.services.PlayerService; import java.io.IOException; import java.util.ArrayList; import butterknife.Bind; import butterknife.ButterKnife; import okhttp3.Call; import okhttp3.Callback; import okhttp3.Response; public class PlayersActivity extends AppCompatActivity { //shared preferences initialize values private SharedPreferences mSharedPreferences; private SharedPreferences.Editor mEditor; private String mRecentTeam; @Bind(R.id.playersListView) ListView mPlayersListView; @Bind(R.id.teamDisplay) TextView mTeamDsiplay; @Bind(R.id.recyclerView) public RecyclerView mRecyclerView; private PlayerListAdapter mAdapter; private ArrayList<Player> mPlayers = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_players); ButterKnife.bind(this); Intent intent = getIntent(); String team = intent.getStringExtra("team"); mTeamDsiplay.setText("Team search for: " + team); getPlayers(team); //test for shared preferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mRecentTeam = mSharedPreferences.getString(Constants.PREFERENCES_TEAM_KEY, null); //if there is no recent team searched for if (mRecentTeam != null) { getPlayers(mRecentTeam); } //log the recent team saved, to LogCat // Log.d("Shared pref location", mRecentTeam); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_search, menu); ButterKnife.bind(this); mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); mEditor = mSharedPreferences.edit(); MenuItem menuItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { addToSharedPreferences(query); getPlayers(query); return false; } @Override public boolean onQueryTextChange(String newText) { return false; } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } private void getPlayers(String team) { final PlayerService playerService = new PlayerService(); playerService.findPlayers(team, new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response){ mPlayers = playerService.processResults(response); PlayersActivity.this.runOnUiThread(new Runnable() { @Override public void run() { mAdapter = new PlayerListAdapter(getApplicationContext(), mPlayers); mRecyclerView.setAdapter(mAdapter); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(PlayersActivity.this); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setHasFixedSize(true); // } }); } }); } private void addToSharedPreferences(String team) { mEditor.putString(Constants.PREFERENCES_TEAM_KEY, team).apply(); } }
[ "morriswarachi0@gmail.com" ]
morriswarachi0@gmail.com
5f514f95e7887d27b7d428151e21370ff94ef9f1
e7c4b091e13e9220dfdf100043273484aa16c442
/Flicks/app/src/main/java/com/codepath/flicks/activity/DetailsActivity.java
01e7c54c8ca5dd7331197b6a7dff60ae8027fa2d
[ "Apache-2.0" ]
permissive
stebrice/WeekOneProject
72d921c79e8692b1899f052b47bc12e08aa94b8a
31252289ca6d5bebba4e3483b9fe19ecd6cb2c17
refs/heads/master
2021-01-01T17:43:46.717092
2017-07-24T02:25:57
2017-07-24T02:25:57
98,139,183
0
0
null
null
null
null
UTF-8
Java
false
false
2,300
java
package com.codepath.flicks.activity; import android.content.Context; import android.content.res.Configuration; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ImageView; import android.widget.TextView; import com.codepath.flicks.R; import com.squareup.picasso.Picasso; import jp.wasabeef.picasso.transformations.RoundedCornersTransformation; /** * Created by STEPHAN987 on 7/23/2017. */ public class DetailsActivity extends AppCompatActivity { Long idMovie; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_details); ImageView ivFullBackdrop = (ImageView) findViewById(R.id.ivFullBackdrop); ImageView ivOriginalBackdrop = (ImageView) findViewById(R.id.ivOriginalBackdrop); TextView tvTitle = (TextView) findViewById(R.id.tvTitle); TextView tvOverview = (TextView) findViewById(R.id.tvOverview); TextView tvRating = (TextView) findViewById(R.id.tvRating); idMovie = this.getIntent().getLongExtra("ID",0); String backdropPath = this.getIntent().getStringExtra("backdropPath"); tvTitle.setText(this.getIntent().getStringExtra("originalTitle")); tvOverview.setText(this.getIntent().getStringExtra("overview")); tvRating.setText(String.valueOf(this.getIntent().getDoubleExtra("rating",0.0))); Context currentContext = getBaseContext(); if(currentContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){ Picasso.with(currentContext).load(backdropPath) .error(R.drawable.no_image_big) .placeholder(R.drawable.loading_placeholder) .transform(new RoundedCornersTransformation(20, 20)).into(ivFullBackdrop); } else if (currentContext.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE){ Picasso.with(currentContext).load(backdropPath) .error(R.drawable.no_image_big) .placeholder(R.drawable.loading_placeholder) .transform(new RoundedCornersTransformation(20, 20)).into(ivOriginalBackdrop); } } }
[ "stephan.brice@gmail.com" ]
stephan.brice@gmail.com
146293bc6da3cc7a187c7441d3c8ce8c85e67715
282817835b4b7b42614a32e236f566ea6f0e3876
/관리자용/waste sorting (manager)/app/src/main/java/com/example/wastesortingapp/OnDatabaseCallback.java
4bb49d8f2e26be0f5a66ba6ec682b5c0bb10cfb1
[]
no_license
qor4/Separation-collection-application-using-barcode-scanning
664beb12e737472b84c03e3e84d1e6a2db284528
b6c188d1c10bf62a81f84ab3b4a7a0b58c1f674b
refs/heads/master
2023-02-26T14:37:38.784654
2021-02-08T00:14:51
2021-02-08T00:14:51
307,444,825
1
1
null
null
null
null
UTF-8
Java
false
false
217
java
package com.example.wastesortingapp; import java.util.ArrayList; public interface OnDatabaseCallback { public void insert(String num, String title, String contents); public ArrayList<BarInfo> selectAll(); }
[ "qor_4@naver.com" ]
qor_4@naver.com
00d28822b9a2dcd17b32aaaa588f60cae0b25986
ab8e8d7dafe2d1d4c6dcb7d80401b44c85c3f067
/src/test/java/controller/test/StoreControllerTest.java
ef5ba635158dcf2873c40c080b18da2d907541e6
[]
no_license
zhangjingpu/tourist
3ff1ae79b2467b554781cca1197b3315904101b8
7e633777e5c442a8c6c543371257e98b9a12d570
refs/heads/master
2021-05-10T16:16:23.441644
2017-11-14T13:25:14
2017-11-14T13:25:14
118,573,744
1
0
null
2018-01-23T07:24:48
2018-01-23T07:24:48
null
UTF-8
Java
false
false
3,137
java
package controller.test; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; /** * Springmvc 单元测试类 * * @author 13 2015-8-17 */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration({"classpath*:/spring-context.xml", "classpath*:/spring-context-mvc.xml", "classpath*:/mybatis-config.xml"}) @TransactionConfiguration(defaultRollback = false) @Transactional public class StoreControllerTest { @Autowired private WebApplicationContext wac; private MockMvc mockMvc; @Before public void setup() { this.mockMvc = webAppContextSetup(this.wac).build(); } @Test public void testSave() throws Exception { //创建书架创建的请求 //请求方式为post MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.post("/store/save.do"); //添加编号为MockMvc的书架 mockHttpServletRequestBuilder.param("number", "MockMvc"); //书架为两层 mockHttpServletRequestBuilder.param("level", "2"); mockMvc.perform(mockHttpServletRequestBuilder).andExpect(status().isOk()) .andDo(print()); } @Test public void testList() throws Exception { //创建书架创建的请求 //请求方式为post MockHttpServletRequestBuilder mockHttpServletRequestBuilder = MockMvcRequestBuilders.post("/store/list.do"); //有些参数我注释掉了,你可以自行添加相关参数,得到不同的测试结果 //status为0的记录 //mockHttpServletRequestBuilder.param("status", "0"); //书架编号为dd的记录 //mockHttpServletRequestBuilder.param("number", "dd"); //第一页 mockHttpServletRequestBuilder.param("page", "1"); //每页10条记录 mockHttpServletRequestBuilder.param("rows", "10"); mockMvc.perform(mockHttpServletRequestBuilder).andExpect(status().isOk()) .andDo(print()); //控制台会打印如下结果: //MockHttpServletResponse: //Status = 200 即为后端成功相应 //返回数据 } }
[ "598437682@qq.com" ]
598437682@qq.com
b43e571d5b3170dd8e543fa3b59588417684a134
fb2c6dc79a18031d95f6f99759d4817a400d081b
/src/net/jurka/arrow/util/Util.java
012dfd008fa500bbd8637e243c313ef68fd27f88
[]
no_license
jurkascode/ArrowScript
3eab390b47c86e489e6e983105d08830291db53a
b95d46395f11b2fc64b3b53711e74f8afe2529d0
refs/heads/master
2016-09-06T09:29:54.905579
2014-01-25T20:15:10
2014-01-25T20:15:10
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,921
java
package net.jurka.arrow.util; public class Util { /** * Formats time from milliseconds to HH:MM:SS format * @param startTime long * @return String time */ public static String formatTime(long startTime) { // Taken from ShantayX all credits to author final long runTimeMilliseconds = System.currentTimeMillis() - startTime; final long secondsTotal = runTimeMilliseconds / 1000; final long minutesTotal = secondsTotal / 60; final long hoursTotal = minutesTotal / 60; int currentTimeHMS[] = new int[3]; currentTimeHMS[2] = (int) (secondsTotal % 60); currentTimeHMS[1] = (int) (minutesTotal % 60); currentTimeHMS[0] = (int) (hoursTotal % 500); return String.format("%02d:%02d:%02d", currentTimeHMS[0], currentTimeHMS[1], currentTimeHMS[2]); } /** * Recursive implementation, invokes itself for each factor of a thousand, increasing the class on each invokation. * From http://stackoverflow.com/questions/4753251/how-to-go-about-formatting-1200-to-1-2k-in-java * @param n the number to format * @param iteration in fact this is the class from the array c * @return a String representing the number n formatted in a cool looking way. */ public static String coolFormat(double n, int iteration) { char[] c = new char[]{'k', 'm', 'b', 't'}; double d = ((long) n / 100) / 10.0; boolean isRound = (d * 10) %10 == 0;//true if the decimal part is equal to 0 (then it's trimmed anyway) return (d < 1000? //this determines the class, i.e. 'k', 'm' etc ((d > 99.9 || isRound || (!isRound && d > 9.99)? //this decides whether to trim the decimals (int) d * 10 / 10 : d + "" // (int) d * 10 / 10 drops the decimal ) + "" + c[iteration]) : coolFormat(d, iteration+1)); } }
[ "jurkacode@live.com" ]
jurkacode@live.com
4f12b030a89c5c8432a3af740f18f03814f99694
93cfee22d776d9ea1df2fae912b2fd57c16d4e30
/Proyectos/Proyecto_4/src/main/java/ast/patron/compuesto/LTNodo.java
45f602ba424b3d12c0dd484283d4e5b75afbd998
[]
no_license
RGT91/legendary-barnacle
e9a6a9a945a7a09ea1199aa30c82f6e2ee8b6ea7
ae7061117e7df428051461cb30aaacef6e4eade2
refs/heads/master
2018-07-20T08:34:29.596868
2018-06-02T03:49:44
2018-06-02T03:49:44
120,832,192
0
2
null
2018-06-02T03:49:45
2018-02-08T23:46:36
Java
UTF-8
Java
false
false
223
java
package ast.patron.compuesto; import ast.patron.visitante.*; public class LTNodo extends NodoBinario { public LTNodo(Nodo l, Nodo r){ super(l,r); } public void accept(Visitor v){ v.visit(this); } }
[ "sanjorgek@ciencias.unam.mx" ]
sanjorgek@ciencias.unam.mx
1f18e68ccbb3118db889acfd30324e16a734ff7a
58743a934a98b28b2943f620b96ba090a2170292
/AutoRepo/src/Inheritance/User.java
311cf8cd1fea8d84041b57211f3dcbd0eddfdfc6
[]
no_license
zealgks2/AutoRepo
460a12495df95f96201b87514186da6f733819a4
4aae2967a48a16ce8b3f905ec62781e6c918b98a
refs/heads/master
2020-12-20T02:45:59.917942
2020-03-05T03:59:23
2020-03-05T03:59:23
235,937,980
0
0
null
null
null
null
UTF-8
Java
false
false
356
java
package Inheritance; public class User { public static void main(String[] args) { // TODO Auto-generated method stub Telephone ph = new Telephone(); ph.calling(); Mobile mob = new Mobile (); mob.calling(); mob.texting(); Smartphone s = new Smartphone(); s.calling(); s.texting(); s.internet(); } }
[ "zealgks2@outlook.com" ]
zealgks2@outlook.com
aeb4facd0b808e853f7ef1b9a0145d4e6d7718cb
56cf34c40c5048b7b5f9a257288bba1c34b1d5e2
/src/org/xpup/signjoint/util/SignTools.java
fcf2254ae8f926cbbec04e50f9983da73189573f
[]
no_license
witnesslq/zhengxin
0a62d951dc69d8d6b1b8bcdca883ee11531fbb83
0ea9ad67aa917bd1911c917334b6b5f9ebfd563a
refs/heads/master
2020-12-30T11:16:04.359466
2012-06-27T13:43:40
2012-06-27T13:43:40
null
0
0
null
null
null
null
GB18030
Java
false
false
2,275
java
package org.xpup.signjoint.util; import java.util.ArrayList; import java.util.List; import java.util.Iterator; import java.io.*; import org.xpup.signjoint.dto.ConfigDTO; /** * 工具类 * @author yinchao * */ public class SignTools { public static XmlOutput xo=new XmlOutput();//XML输出类 /** * 转换数据格式 * @param 带有分隔符的字符串 * @return 从字符中提取的List */ public static List Compart(String temp) { List list=new ArrayList(); String mark=null; int pointer=0; for(int i=0;i<temp.length();i++) { mark=temp.substring(i,i+1); if(mark.equals(xo.getConfig().getMark())) { list.add(temp.substring(pointer,i)); pointer=i+1; } } //list.add(temp.substring(pointer,temp.length()));//末尾不加分隔符 return list; } /** * 将传进来的List中的数据合并成一个String * @param 存着数据项的List * @return 将其合并成一个特定格式的字符串 */ public static String Combination(List temp) { Iterator iter=temp.iterator(); StringBuffer sb= new StringBuffer(); String mark=xo.getConfig().getMark(); while(iter.hasNext()) { sb.append(((String)iter.next()+mark)); } return sb.toString(); //return sb.toString().substring(1);//如果末尾不加分隔符 } /** * 将含有两位小数的金额转换成银行格式 * @param money保留两为小数的金额 * @return 银行接收的格式(去掉小数点) */ public static long DoubletoLong(double money) { money=money*100; return (long)money; } /** * 将流中数据去掉分隔符 * @param 输入流 * @return 存储着从输入流中提取数据的List */ public static List Compart(InputStream in) { InputStreamReader isr=new InputStreamReader(in); BufferedReader bin=new BufferedReader(isr); int ch; StringBuffer sb= new StringBuffer(); try { while((ch=bin.read())!=-1) { sb.append(ch); } } catch (IOException e) { e.printStackTrace(); } return Compart(sb.toString()); } }
[ "yuelaotou@gmail.com" ]
yuelaotou@gmail.com
71f2680d2901fcea1e9c135de81126d23ff89055
8a319176b995154d66015f3ad2f4e60a130fddeb
/business/manager/master/src/main/java/sharemer/business/manager/master/remoteapi/AcFunRemoteApi.java
52e15a643ab68e0ab28ce3e9e05813445b4dfb92
[]
no_license
exceting/sharemer
814252e5c755652546bc3c7938c62f0adfc266b5
ac49aa5650e6ef6549c168e968e654b1ffab6cf7
refs/heads/master
2021-06-09T12:00:05.796726
2021-04-08T06:39:19
2021-04-08T06:39:19
141,031,601
5
2
null
null
null
null
UTF-8
Java
false
false
341
java
package sharemer.business.manager.master.remoteapi; import retrofit2.http.GET; import retrofit2.http.Path; import sharemer.component.http.client.ReqCall; /** * Create by 18073 on 2018/7/5. */ public interface AcFunRemoteApi { @GET("/v/ac{ac}") ReqCall<String> getAvideoByAcId(@Path("ac") int ac);//根据acId获取A站资源 }
[ "sunqinwen@bilibili.com" ]
sunqinwen@bilibili.com
b1246020af4ba088664ab18477a33ef82572e6b5
153abcf20c9d96fdaa1c3c7298abb3afaa9bb458
/src/main/java/org/ztest/test8/Main.java
fda4b13f207650ca1ad0713e679fc5f814e62248
[]
no_license
Lichio/TestProject
5d600c8f0b01a588cd42cdd03ebd1431553292e5
f9f874e32b9e622b66b23823c093f8a4c1353afb
refs/heads/master
2022-10-08T11:33:49.753480
2019-06-02T11:30:40
2019-06-02T11:30:40
175,182,928
0
0
null
2022-10-04T23:51:39
2019-03-12T10:00:10
Java
UTF-8
Java
false
false
9,625
java
package org.ztest.test8; import java.util.*; /** * TestProject org.test.test25 * * @author Lichaojie * @version 2018/5/11 19:50 * */ public class Main { public static void main(String[] args){ Scanner in = new Scanner(System.in); } public static void ssort(int[] source,int[] s2){ int k; int flag = source.length; while (flag > 0){ k = flag; flag = 0; for (int i = 0; i < k - 1;i ++){ if(source[i] > source[i + 1]){ int temp = source[i]; source[i] = source[i + 1]; source[i + 1] = temp; temp = s2[i]; s2[i] = s2[i + 1]; s2[i + 1] = temp; flag = i + 1; } } } } public static void main9(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int m= in.nextInt(); int[] s = new int[n]; int[] t = new int[n]; for (int i = 0; i < n; i ++){ s[i] = in.nextInt(); t[i] = in.nextInt(); if(s[i] < 0 || s[i] > m || t[i] < 0 || t[i] > m) return; } ssort(s,t); int[] dp = new int[n]; for (int i = 0; i < n; i ++){ dp[i] = 1; } for (int i = 1; i < n; i++){ for (int j =0; j < i; j ++){ if(t[j] <= s[i] && s[j] < t[j]){ if(t[i] > s[i] || t[i] <= s[j]){ if(dp[j] + 1 > dp[i]){ dp[i] = dp[j] + 1; } } } } } int max = 0; for (int i = 0 ; i < n; i ++){ if(dp[i] > max) max = dp[i]; } System.out.println(max); } public static void main8(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); long[] a = new long[n]; long[] b = new long[n]; for (int i = 0 ; i < n; i ++){ a[i] = in.nextInt(); } for (int i = 0 ; i < n; i ++){ b[i] = in.nextInt(); } int l,r; int i = 0; int sum = 0; while (i < n){ while (i < n && a[i] >= b[i]){ i ++; } l = i; while (i < n && a[i] < b[i]){ i ++; } r = i; for (int j = 1; j < r - l + 1; j ++){ sum += j; } } System.out.println(sum); } public static void main7(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); long[] a = new long[n]; long[] b = new long[n]; for (int i = 0 ; i < n; i ++){ a[i] = in.nextInt(); } for (int i = 0 ; i < n; i ++){ b[i] = in.nextInt(); } long[] maxA = new long[n]; long[] minB = new long[n]; int sum = 0; for (int i = 0 ; i < n ; i ++){ if(a[i] >= b[i]) continue; for (int j = i; j < n; j++){ if(j == i){ maxA[j] = a[j]; minB[j] = b[j]; } if(j > i && a[j] < maxA[j - 1]){ maxA[j] = maxA[j - 1]; }else { maxA[j] = a[j]; } if(j > i && b[j] > minB[j - 1]){ minB[j] = minB[j - 1]; }else { minB[j] = b[j]; } } for (int j = i; j < n; j ++){ if(maxA[j] < minB[j]) sum ++; } } System.out.println(sum); } public static void main6(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] a = new int[n]; for (int i = 0; i < n; i ++){ a[i] = in.nextInt(); } int m = in.nextInt(); int[] q = new int[m]; for (int i = 0 ; i < m; i ++){ q[i] = in.nextInt(); } for (int i = 1; i < n; i ++){ a[i] = a[i - 1] + a[i]; } for (int i = 0 ; i < m; i ++){ // for (int j = 0 ; j < n; j ++){ // if(q[i] <= a[j]) { // System.out.println(j + 1); // break; // } // } System.out.println(search(a,q[i]) + 1); } } public static int search(int[] array,int n){ int l = 0; int r = array.length - 1; if(n > array[r]) return -1; while (l <= r){ int m = l + (r - l) / 2; if(n > array[m]){ l = m + 1; }else if(n < array[m]){ if(m == 0 || n > array[m - 1]) return m; r = m - 1; }else { return m; } } return -1; } public static void main5(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] score = new int[n]; int[] flag = new int[n]; for (int i = 0; i < n; i ++){ score[i] = in.nextInt(); } for (int i = 0; i < n; i ++){ flag[i] = in.nextInt(); } int sum = 0; for (int i = 0; i < n; i ++){ if(flag[i] == 1) sum += score[i]; } //int[] scores = new int[n - k + 1]; int max = 0; for (int i = 0; i < n - k + 1; i ++){ int j = i; int result = 0; while (j < i + k){ if(flag[j] == 0){ result += score[j]; } j ++; } if(max < result) max = result; } System.out.println(max + sum); } public static void main4(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int k = in.nextInt(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i ++){ sb.append("a"); } for (int i = 0 ; i < m; i ++){ sb.append("z"); } ArrayList<String> list = Permutation(sb.toString()); if(k > list.size()){ System.out.println(-1); }else { System.out.println(list.get(k - 1)); } } public static ArrayList<String> Permutation(String str) { if(str == null) return null; if(str.length() == 0) return new ArrayList<>(); if(str.length() == 1){ ArrayList<String> list = new ArrayList<>(1); list.add(str); return list; } char c = str.charAt(0); ArrayList<String> list = Permutation(str.substring(1,str.length())); HashSet<String> strSet = new HashSet<>(); for (String s : list){ strSet.add(c + s); char[] chars = s.toCharArray(); for (int i = 0 ; i < chars.length ; i ++){ char ct = chars[i]; chars[i] = c; strSet.add(ct + new String(chars)); chars[i] = ct; } } ArrayList<String> strList = new ArrayList<>(strSet.size()); strList.addAll(strSet); Collections.sort(strList); return (strList); } public static void main3(String[] args){ Scanner in = new Scanner(System.in); ArrayList<Integer> list = new ArrayList<>(); String s = in.nextLine(); if("".equals(s)){ System.out.println(0); return; } String[] ss = s.split(" "); for (String str : ss){ list.add(Integer.parseInt(str)); } Collections.sort(list); // ArrayList<Integer> list1 = new ArrayList(); // ArrayList<Integer> list2 = new ArrayList(); // ArrayList<Integer> list3 = new ArrayList(); // ArrayList<Integer> list4 = new ArrayList(); int n = 0; out1: while (!list.isEmpty()){ int length = list.size(); int flag = 0; if(list.get(length - 1) > 200){ list.remove(length - 1); n ++; continue; } if(list.get(length - 1) == 200){ if(list.get(0) == 100){ list.remove(length - 1); list.remove(0); n ++; continue; }else { list.remove(length - 1); n ++; continue; } } if(list.get(length - 1) + list.get(0) > 300){ list.remove(length - 1); n ++ ; continue ; } if(list.get(length - 1) == 100) break; out2: for (int i = length - 2; i >= 0; i --){ int W = list.get(length - 1) + list.get(i); if(W > 200 && W <= 300){ list.remove(length - 1); list.remove(i); n ++; flag = 1; break out2; }else if(W == 200){ break out1; // if(list.get(0) == 100){ // list.remove(length - 1); // list.remove(i); // list.remove(0); // n ++; // flag = 1; // break out2; // }else { // list.remove(length - 1); // list.remove(i); // n ++; // flag = 1; // break out2; // } } } if(flag == 0){ list.remove(length - 1); n ++; } } if(!list.isEmpty()){ int size = list.size(); int m = size % 3 == 0 ? size / 3 : size / 3 + 1; n = n + m; } System.out.println(n); } public static void main2(String[] args){ int n = 0; double b = 0.0; double temp = 0.0; Scanner sc = new Scanner(System.in); n = sc.nextInt(); if(n == 1) { System.out.println("Alice"); } if(n == 2) { System.out.println("Bob"); } if(n == 3) { System.out.println("Cathy"); } if(n == 4) { System.out.println("Dave"); } for (int i = 2; ; i++) { b += Math.pow(2, i); if(n - b <= Math.pow(2, i+1)) { temp = (n - b)/Math.pow(2, i+1); break; } } sc.close(); if(temp > 0 && temp <= 0.25) { System.out.println("Alice"); } if(temp > 0.25 && temp <= 0.50) { System.out.println("Bob"); } if(temp > 0.50 && temp <= 0.75) { System.out.println("Cathy"); } if(temp > 0.75 && temp <= 1) { System.out.println("Dave"); } } public static void main1(String[] args){ Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int[][] constraint = new int[m][2]; for (int i = 0 ; i < m; i ++){ constraint[i][0] = in.nextInt(); constraint[i][1] = in.nextInt(); } List<Integer> list = new ArrayList<>(); for (int i = 0; i < m - 1; i ++){ for (int j = i + 1; j < m ; j ++){ list.add(check(constraint[i][0],constraint[i][1],constraint[j][0],constraint[j][1])); } } for (int i = 0 ; i< list.size() - 1; i ++){ int t = list.get(i); if(t % 2 == 0){ for (int j = i ; j < list.size(); j ++){ if(list.get(j) == t - 1) System.out.println("no"); } }else { for (int j = i ; j < list.size(); j ++){ if(list.get(j) == t + 1) System.out.println("no"); } } } System.out.println("yes"); } public static int check(int a1,int a2,int b1,int b2){ if(a1 == b1){ if(a2 % 2 == 0 && b2 + 1 == a2 || b2 % 2 == 0 && a2 + 1 == b1) return a1; } if(a1 == b2){ if(a2 % 2 == 0 && b1 + 1 == a2 || b1 % 2 == 0 && a2 + 1 == b1) return a1; } if(a2 == b1){ if(a1 % 2 == 0 && b2 + 1 == a1 || b2 % 2 == 0 && a1 + 1 == b2) return a2; } if(a2 == b2){ if(a1 % 2 == 0 && b1 + 1 == a1 || b1 % 2 == 0 && a1 + 1 == b1) return a2; } return 0; } }
[ "lich_hb@163.com" ]
lich_hb@163.com
2cb09f9d9a12d4bf6a6b231f5ebd788289ef85eb
a13068e5afc2ce716b46faacc9766e1f50bd00ee
/src/main/java/com/codeborne/selenide/commands/ScrollTo.java
1ec3d87941e409228984eac2570ab0a63bced3ef
[ "MIT", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-free-unknown" ]
permissive
mikawajos/selenide
e4d435fc7dfa79e2c69a01cb5343d6f267e95f68
d5ba4e457e724807941dae45224610c32bc65cd5
refs/heads/master
2021-05-25T20:37:36.260713
2020-04-07T17:43:00
2020-04-07T17:43:00
253,911,416
1
0
MIT
2020-04-07T21:03:20
2020-04-07T21:03:20
null
UTF-8
Java
false
false
609
java
package com.codeborne.selenide.commands; import com.codeborne.selenide.Command; import com.codeborne.selenide.SelenideElement; import com.codeborne.selenide.impl.WebElementSource; import org.openqa.selenium.Point; import org.openqa.selenium.WebElement; public class ScrollTo implements Command<WebElement> { @Override public WebElement execute(SelenideElement proxy, WebElementSource locator, Object[] args) { Point location = locator.getWebElement().getLocation(); locator.driver().executeJavaScript("window.scrollTo(" + location.getX() + ", " + location.getY() + ')'); return proxy; } }
[ "andrei.solntsev@gmail.com" ]
andrei.solntsev@gmail.com
64064a75eaad1017bcb063864e677eac50492043
632b5737d23d4a31b363ce4ea5971c858928b1bc
/nodes/src/test/java/io/aexp/nodes/graphql/scenarios/RequestBuilderTest.java
26775854e7e0b64e575b9337fcd0426b17ee66ea
[ "Apache-2.0" ]
permissive
privoro/nodes
34db4a53159aea93ce9f7f2a439b5220c1376212
bc5469841ad17b66c135e40361f0ea1472ddbe3a
refs/heads/master
2020-03-22T14:29:07.045192
2018-07-07T16:30:17
2018-07-07T16:30:17
140,183,242
0
0
Apache-2.0
2018-07-08T16:13:03
2018-07-08T16:13:03
null
UTF-8
Java
false
false
13,034
java
/* * Copyright (c) 2018 American Express Travel Related Services Company, 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 io.aexp.nodes.graphql.scenarios; import io.aexp.nodes.graphql.GraphQLRequestEntity; import io.aexp.nodes.graphql.Variable; import io.aexp.nodes.graphql.models.TestModel; import io.aexp.nodes.graphql.models.TestModelExtended; import io.aexp.nodes.graphql.models.TestModels; import io.aexp.nodes.graphql.Argument; import io.aexp.nodes.graphql.Arguments; import io.aexp.nodes.graphql.exceptions.GraphQLException; import io.aexp.nodes.graphql.InputObject; import org.junit.Test; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class RequestBuilderTest { enum STATUS { active } private String EXAMPLE_URL = "https://graphql.example.com"; @Test public void simpleQuery() throws MalformedURLException { GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder() .url(EXAMPLE_URL) .request(TestModel.class) .build(); assertEquals("query ($andAnothaVariable:status,$anothaVariable:Int,$andAListVariable:[String],$variableName:String!){ test (id:null) { testShort testCharacter testList { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testInteger testBoolean nestedTest { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testByte testString : testString(anotherOne:null,default:\"default\",defaultList:null) testArrayList testFloat testDouble testLong } } ", requestEntity.getRequest()); assertTrue(requestEntity.getVariables().isEmpty()); } @Test public void stringParameterizedQuery() throws GraphQLException, MalformedURLException { List<String> argumentList = new ArrayList<String>(); argumentList.add("string1"); argumentList.add("string2"); GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder() .url(EXAMPLE_URL) .arguments( new Arguments("test", new Argument<String>("id", "1")), new Arguments("test.testString", new Argument<List>("defaultList", argumentList))) .request(TestModel.class) .build(); assertEquals("query ($andAnothaVariable:status,$anothaVariable:Int,$andAListVariable:[String],$variableName:String!){ test (id:\"1\") { testShort testCharacter testList { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testInteger testBoolean nestedTest { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testByte testString : testString(anotherOne:null,default:\"default\",defaultList:[\"string1\",\"string2\"]) testArrayList testFloat testDouble testLong } } ", requestEntity.getRequest()); assertTrue(requestEntity.getVariables().isEmpty()); } @Test public void numberParameterizedQuery() throws GraphQLException, MalformedURLException { List<Integer> argumentList = new ArrayList<Integer>(); argumentList.add(1); argumentList.add(2); GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder() .url(EXAMPLE_URL) .arguments( new Arguments("test", new Argument<Integer>("id", 1)), new Arguments("test.testString", new Argument<List>("defaultList", argumentList))) .request(TestModel.class) .build(); assertEquals("query ($andAnothaVariable:status,$anothaVariable:Int,$andAListVariable:[String],$variableName:String!){ test (id:1) { testShort testCharacter testList { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testInteger testBoolean nestedTest { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testByte testString : testString(anotherOne:null,default:\"default\",defaultList:[1,2]) testArrayList testFloat testDouble testLong } } ", requestEntity.getRequest()); assertTrue(requestEntity.getVariables().isEmpty()); } @Test public void enumParameterizedQuery() throws GraphQLException, MalformedURLException { GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder() .url(EXAMPLE_URL) .arguments(new Arguments("test", new Argument<STATUS>("id", STATUS.active))) .request(TestModel.class) .build(); assertEquals("query ($andAnothaVariable:status,$anothaVariable:Int,$andAListVariable:[String],$variableName:String!){ test (id:active) { testShort testCharacter testList { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testInteger testBoolean nestedTest { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testByte testString : testString(anotherOne:null,default:\"default\",defaultList:null) testArrayList testFloat testDouble testLong } } ", requestEntity.getRequest()); assertTrue(requestEntity.getVariables().isEmpty()); } @Test public void extendedModel() throws GraphQLException, MalformedURLException { GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder() .url(EXAMPLE_URL) .request(TestModelExtended.class) .build(); assertEquals("query ($andAnothaVariable:status,$anothaVariable:Int,$andAListVariable:[String],$variableName:String!){ test { testInteger testBoolean nestedTest { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } test testByte testFloat testLong testShort testCharacter testList { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testPrimitiveArray testString : testString(anotherOne:null,default:\"default\",defaultList:null) testArrayList testDouble } } ", requestEntity.getRequest()); assertTrue(requestEntity.getVariables().isEmpty()); } @Test public void multiModel() throws GraphQLException, MalformedURLException { GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder() .url(EXAMPLE_URL) .request(TestModels.class) .build(); assertEquals("query ($andAnothaVariable:status,$anothaVariable:Int,$andAListVariable:[String],$variableName:String!){ test2 : test(id:null,test:\"test2\",testBool:false,testInt:2,testFloat:2.2) { testShort testCharacter testList { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testInteger testBoolean nestedTest { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testByte testString : testString(anotherOne:null,default:\"default\",defaultList:null) testArrayList testFloat testDouble testLong } test1 : test(id:null,test:\"test1\",testBool:true,testInt:1,testFloat:1.1) { testShort testCharacter testList { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testInteger testBoolean nestedTest { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testByte testString : testString(anotherOne:null,default:\"default\",defaultList:null) testArrayList testFloat testDouble testLong } } ", requestEntity.getRequest()); assertTrue(requestEntity.getVariables().isEmpty()); } @Test public void queryWithArgumentsAndVariables() throws GraphQLException, MalformedURLException { List<Argument> argumentList = new ArrayList<Argument>(); List<Arguments> argumentsList = new ArrayList<Arguments>(); List<Variable> variables = new ArrayList<Variable>(); List<String> listVariable = new ArrayList<String>(); argumentList.add(new Argument<String>("id", "1")); Arguments arguments = new Arguments("test", argumentList); argumentsList.add(arguments); listVariable.add("string1"); listVariable.add("string2"); variables.add(new Variable<String>("variableName", "name")); variables.add(new Variable<Integer>("anothaVariable", 1234)); variables.add(new Variable<STATUS>("andAnothaVariable", STATUS.active)); variables.add(new Variable<List>("andAListVariable", listVariable)); GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder() .url(EXAMPLE_URL) .arguments(argumentsList) .variables(variables) .request(TestModel.class) .build(); assertEquals("query ($andAnothaVariable:status,$anothaVariable:Int,$andAListVariable:[String],$variableName:String!){ test (id:\"1\") { testShort testCharacter testList { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testInteger testBoolean nestedTest { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testByte testString : testString(anotherOne:null,default:\"default\",defaultList:null) testArrayList testFloat testDouble testLong } } ", requestEntity.getRequest()); assertEquals("{variableName=name, anothaVariable=1234, andAnothaVariable=active, andAListVariable=[string1, string2]}", requestEntity.getVariables().toString()); } @Test public void queryWithInputObjectArguments() throws GraphQLException, MalformedURLException { List<String> stringList = new ArrayList<String>(); stringList.add("string1"); stringList.add("string2"); stringList.add("string3"); InputObject nestedObj = new InputObject.Builder<Object>() .put("input1", 1) .put("input2", true) .put("input3", stringList) .put("input4", "string") .build(); InputObject idObj = new InputObject.Builder<InputObject>() .put("nestedObj", nestedObj) .build(); GraphQLRequestEntity requestEntity = GraphQLRequestEntity.Builder() .url(EXAMPLE_URL) .arguments(new Arguments("test", new Argument("id", idObj))) .request(TestModel.class) .build(); assertEquals("query ($andAnothaVariable:status,$anothaVariable:Int,$andAListVariable:[String],$variableName:String!){ test (id:{nestedObj:{input4:\"string\",input3:[\"string1\",\"string2\",\"string3\"],input2:true,input1:1}}) { testShort testCharacter testList { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testInteger testBoolean nestedTest { anotherTestString (variableName:$variableName) andAnothaOne (anothaVariable:$anothaVariable,andAnothaVariable:$andAnothaVariable,andAListVariable:$andAListVariable) } testByte testString : testString(anotherOne:null,default:\"default\",defaultList:null) testArrayList testFloat testDouble testLong } } ", requestEntity.getRequest()); } }
[ "Andrew.K.Pratt@aexp.com" ]
Andrew.K.Pratt@aexp.com
4430a35f1684a90b23eda579e32f776081e9a26e
94a6b0f064fd34749986fe87f9730ba6e417bd77
/src/com/raghav/corejava/Exception/ExceptionDemo.java
dd7b52a4922ce6b900ce56976450e13b58892e09
[]
no_license
spragha/TestGit
d0493cef41790c2b78a8b6b8101dba4b9063f30e
b64ddb3efb12772bfdb646f1a66891a9e74e161c
refs/heads/master
2020-04-06T06:55:31.939106
2016-09-07T19:46:58
2016-09-07T19:46:58
61,171,692
0
0
null
null
null
null
UTF-8
Java
false
false
410
java
package com.raghav.corejava.Exception; public class ExceptionDemo { /** * @param args */ public static void main(String[] args) { System.err.println("Error message"); try { //Protected code System.exit(0); // only by this way finally wont be executed }catch(Exception e1) { //Catch block }finally { //The finally block always executes. } } }
[ "sraghavan4031@gmail.com" ]
sraghavan4031@gmail.com
f45386535524c58e3061e914f389f3f75cd08815
1ccf9c674a55b230bce91c877a6ef67aba7d635c
/src/main/java/com/Core/vaadin/arduino/arduino_2/PrincipalArduino2.java
09aa59dc8ac261659a43cf6066ce09eb25fe979d
[]
no_license
rucko24/MVP
d784cabc49b512fd7ed7fbbc2ecd5d353ddfbd87
d8622c8dab25127b8fcc40dbee4cb1c6b2b3faa6
refs/heads/master
2020-05-21T04:52:36.632714
2017-06-05T04:08:41
2017-06-05T04:08:41
53,697,799
0
0
null
null
null
null
UTF-8
Java
false
false
909
java
package com.Core.vaadin.arduino.arduino_2; import com.Core.vaadin.arduino.grafica.HighChartsPanel; import com.vaadin.ui.Label; import com.vaadin.ui.Notification; import com.vaadin.ui.Notification.Type; import com.vaadin.ui.VerticalLayout; import jssc.SerialPortException; public class PrincipalArduino2 extends VerticalLayout { private JSSC_AC a; public static Label labelEstadoArduino = new Label(); public static HighChartsPanel panel = new HighChartsPanel(); public PrincipalArduino2() { setSizeFull(); setSpacing(true); setMargin(true); init(); addComponents(labelEstadoArduino,panel); setExpandRatio(panel, 1); } private void init() { try { a = new JSSC_AC("/dev/ttyS0"); } catch (SerialPortException e) { // TODO Auto-generated catch block Notification.show("Error al iniciar Conexion: "+e.getMessage(),Type.ERROR_MESSAGE); e.printStackTrace(); } } }
[ "rucko24@gmail.com" ]
rucko24@gmail.com
70e524343a1f6c168fea609ea6415b70f232dd19
e9a1c638bdbd862c0998addd50e2dce5561a3244
/functionalj-core/src/test/java/functionalj/pipeable/PipeLineTest.java
a4959b3e237bb2e42660a2d8842f3799441ed6e0
[ "MIT" ]
permissive
tanhuazh/FunctionalJ
c1f024ad2e9e7357caaadfbbc198f8bd074eee85
d4778044065d4a68eb1f10d227f4481f881ca48e
refs/heads/master
2023-04-28T09:12:48.707534
2019-09-25T04:34:29
2019-09-25T04:34:29
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,132
java
// ============================================================================ // Copyright (c) 2017-2019 Nawapunth Manusitthipol (NawaMan - http://nawaman.net). // ---------------------------------------------------------------------------- // MIT License // // 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 functionalj.pipeable; import static functionalj.lens.Access.$I; import static functionalj.lens.Access.$S; import static functionalj.lens.Access.theInteger; import static functionalj.lens.Access.theString; import static functionalj.pipeable.WhenNull.defaultTo; import static org.junit.Assert.assertEquals; import org.junit.Test; import lombok.val; @SuppressWarnings("javadoc") public class PipeLineTest { @Test public void testBasic() { val pipeLine = PipeLine .from(theString.length()) .then(theInteger.multiply(2)) .then(theInteger.asString()) .thenReturn(); val pipeLine2 = PipeLine .from(theString.toUpperCase()) .thenReturn(); val str = Pipeable.of("Test"); assertEquals("8", pipeLine.apply("Test")); assertEquals("TEST", pipeLine2.apply("Test")); assertEquals("8", str.pipeTo(pipeLine)); assertEquals("TEST", str.pipeTo(pipeLine2)); assertEquals("8", str.pipeTo(pipeLine, pipeLine2)); val strNull = Pipeable.of((String)null); assertEquals(null, pipeLine.applyToNull()); assertEquals(null, pipeLine2.applyToNull()); assertEquals(null, strNull.pipeTo(pipeLine)); assertEquals(null, strNull.pipeTo(pipeLine2)); assertEquals(null, strNull.pipeTo(pipeLine, pipeLine2)); } @Test public void testHandlingNull() { val pipeLine = PipeLine.ofNullable(String.class) .then(theString.length()) .then(theInteger.multiply(2)) .then(theInteger.asString()) .thenReturnOrElse("<none>"); val pipeLine2 = PipeLine .from(theString.toUpperCase()) .thenReturn(); assertEquals("<none>", pipeLine.applyToNull()); assertEquals(null, pipeLine2.applyToNull()); val str = Pipeable.of((String)null); assertEquals("<none>", str.pipeTo(pipeLine)); assertEquals(null, str.pipeTo(pipeLine2)); assertEquals("<NONE>", str.pipeTo(pipeLine, pipeLine2)); } @Test public void testHandlingNullCombine() { val pipeLine = PipeLine.ofNullable(String.class) .then($S.length()) .then($I.multiply(2)) .then($I.asString()) .then(defaultTo("<none>")) .then($S.toUpperCase()) .thenReturn(); assertEquals("<NONE>", pipeLine.applyToNull()); val str = Pipeable.of((String)null); assertEquals("<NONE>", str.pipeTo(pipeLine)); } }
[ "nawa@nawaman.net" ]
nawa@nawaman.net
c401bfdae76f3db04aee7f711bc7e7683b294762
98f2db59360976de0b5113c0f8382e2a9f89cf21
/esblog/src/main/java/com/wenjie/esblog/controller/AuthcController.java
ffcd756f08cc30353a0f45dde962ce3c24ef8814
[]
no_license
wenjieObject/boot-learn
4f29a950dde86cccd76f186a3824cd2d61fb2b0d
b38c2a6e4618463627efa51365532e319912481a
refs/heads/master
2022-12-17T08:14:56.849711
2020-09-09T04:49:43
2020-09-09T04:49:43
290,422,917
0
0
null
null
null
null
UTF-8
Java
false
false
952
java
package com.wenjie.esblog.controller; import com.wenjie.esblog.pojo.User; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("authc") public class AuthcController { @GetMapping("index") public Object index() { Subject subject = SecurityUtils.getSubject(); User user = (User) subject.getSession().getAttribute("user"); return user.toString(); } @GetMapping("admin") public Object admin() { return "Welcome Admin"; } // delete @GetMapping("removable") public Object removable() { return "removable"; } // insert & update @GetMapping("renewable") public Object renewable() { return "renewable"; } }
[ "connyoursis@163.com" ]
connyoursis@163.com
2959594c0ed6b7623d4a09a0da56145502f86713
5c49c5e15d3a05f17409a7da87e13797b45ae296
/server/src/test/java/de/blogspot/mszalbach/iss/domain/SecurityStateMachineTest.java
772d60ab791a0163f4aa81c9d027bf147db5e74a
[ "MIT" ]
permissive
mszalbach/IssuerSelfService
c7bd9fa31fc04ac497fd3de6cd20493ab9794d23
c5eacce489d527d64809d35057e21445aa045e2d
refs/heads/master
2023-01-27T12:32:49.867938
2019-11-23T11:18:57
2019-11-23T11:18:57
71,040,934
0
1
MIT
2023-01-20T13:19:54
2016-10-16T09:27:33
Java
UTF-8
Java
false
false
1,623
java
package de.blogspot.mszalbach.iss.domain; import de.blogspot.mszalbach.iss.statemachine.SecurityStateMachineAdapter; import de.blogspot.mszalbach.iss.statemachine.SecurityStateMachineFactory; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.squirrelframework.foundation.fsm.StateMachine; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * Created by Marcel Szalbach on 21.11.16. */ @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes = {SecurityStateMachineAdapter.class, SecurityStateMachineFactory.class}) public class SecurityStateMachineTest { StateMachine machine; @Autowired private SecurityStateMachineAdapter stateMachineFactory; @Before public void init() { machine = stateMachineFactory.create(); } @Test public void should_start_in_open_state() throws Exception { assertThat(machine.getCurrentState(), is("Open")); } @Test public void should_change_to_requested_when_using_request_on_open_state() { machine.fire("request"); assertThat(machine.getCurrentState(), is("Requested")); } @Test public void should_not_be_able_to_use_cancel_on_open_state() { assertThat(machine.canAccept("cancel"), is(false)); machine.fire("cancel"); assertThat(machine.getCurrentState(), is("Open")); } }
[ "4-bar-killa@web.de" ]
4-bar-killa@web.de
fe56b076c26514207258baba8fc87e4dc7b47437
906a1bb973d70754a59d4fd3b1645bd189b9eb59
/src/jruby4max/util/Logger.java
87eb59d23cb08459e164c4649aa23ef4bfe0f130
[]
no_license
adamjmurray/jruby_for_max
51f553031fcd0629446ae0d330527fd2416622ad
8f3d3074ad17cd647e14efcb455a9931033b8507
refs/heads/master
2021-11-25T22:10:48.666449
2014-09-27T18:34:41
2014-09-27T18:34:41
1,127,923
32
7
null
2021-11-09T06:36:03
2010-12-01T06:18:34
Max
UTF-8
Java
false
false
1,554
java
package jruby4max.util; /* Copyright (c) 2008, Adam Murray (adam@compusition.com). All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Simple logging interface. * * @author Adam Murray (adam@compusition.com) */ public interface Logger { void debug( String message ); void info( String message ); void err( String message ); }
[ "adamjmurray@gmail.com" ]
adamjmurray@gmail.com
7e088d9b0c03fca6d7424f68daaa5d4fd3eb6094
6b37e4b63511a8afc3cbca6ecd05c6c085a77f0c
/src/main/java/sv/edu/uesocc/ingenieria/prn335_2017/datos/acceso/TipoPostFacade.java
39f3d1e31a5e0fcabea3cc6a80b53cc9526fddb2
[]
no_license
SG14011-PRN335/guia07
78435ea4d2f089e3376a19502c0ad2c46c1a96c0
302c3a18a98dbe7e63fdd7d644b6fd763b98f429
refs/heads/master
2021-07-25T22:28:02.500666
2017-11-09T02:35:21
2017-11-09T02:35:21
108,885,893
0
0
null
null
null
null
UTF-8
Java
false
false
866
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package sv.edu.uesocc.ingenieria.prn335_2017.datos.acceso; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import sv.edu.uesocc.ingenieria.prn335_2017.datos.definiciones.TipoPost; /** * * @author juancarlos */ @Stateless public class TipoPostFacade extends AbstractFacade<TipoPost> implements TipoPostFacadeLocal { @PersistenceContext(unitName = "sv.edu.uesocc.ingenieria.prn335.2017_guia06_war_1.0-SNAPSHOTPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public TipoPostFacade() { super(TipoPost.class); } }
[ "juancarlos@jcdebian.lan" ]
juancarlos@jcdebian.lan
dd35232a2452e1e5c25132c17d4ea1822a124e6c
2d13663fe920874f0c173be5b2453957d49182db
/asset-common/src/main/java/com/glf/exception/base/BaseException.java
3117b715b905d279809587217b1f4f063d5b2a87
[]
no_license
macrohongs/macro
9124db627e519dcedb6f6093df608bcb4e43d4e6
c37eaa552f0abe2869226042cacb25bcc290248f
refs/heads/master
2022-12-18T22:24:12.130650
2020-09-21T02:38:45
2020-09-21T02:38:45
297,200,994
0
0
null
null
null
null
UTF-8
Java
false
false
1,884
java
package com.glf.exception.base; import com.glf.utils.MessageUtils; import com.glf.utils.StringUtils; /** * 基础异常 */ public class BaseException extends RuntimeException { private static final long serialVersionUID = 1L; /** * 所属模块 */ private String module; /** * 错误码 */ private String code; /** * 错误码对应的参数 */ private Object[] args; /** * 错误消息 */ private String defaultMessage; public BaseException(String module, String code, Object[] args, String defaultMessage) { this.module = module; this.code = code; this.args = args; this.defaultMessage = defaultMessage; } public BaseException(String module, String code, Object[] args) { this(module, code, args, null); } public BaseException(String module, String defaultMessage) { this(module, null, null, defaultMessage); } public BaseException(String code, Object[] args) { this(null, code, args, null); } public BaseException(String defaultMessage) { this(null, null, null, defaultMessage); } @Override public String getMessage() { String message = null; if (!StringUtils.isEmpty(code)) { message = MessageUtils.message(code, args); } if (message == null) { message = defaultMessage; } return message; } public String getModule() { return module; } public String getCode() { return code; } public Object[] getArgs() { return args; } public String getDefaultMessage() { return defaultMessage; } }
[ "macro@macro-PC" ]
macro@macro-PC
8b450658f3db940a6541e24282cf3c0703e7bf27
984022c1966d13723090352b0e2d47439d40d774
/presentation/src/test/java/csci3310/stalkyourfriends/presentation/presenter/NoteEditPresenterTest.java
65ad1ad0c781d86367ae15c951c10b94821263ec
[]
no_license
StalkYourFriend/StalkYourFriendsDroid_androidBase
6e6b0d55adf26381fb8ac8226af0e73d39b60376
4762e7a00a7695877a8bc0af001622b5c497cb5a
refs/heads/master
2020-12-30T13:19:51.887175
2017-05-15T13:48:42
2017-05-15T13:48:42
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,609
java
package csci3310.stalkyourfriends.presentation.presenter; import csci3310.stalkyourfriends.data.net.error.RestApiErrorException; import csci3310.stalkyourfriends.domain.entity.NoteEntity; import csci3310.stalkyourfriends.domain.interactor.note.DeleteNoteUseCase; import csci3310.stalkyourfriends.domain.interactor.note.GetNoteUseCase; import csci3310.stalkyourfriends.domain.interactor.note.UpdateNoteUseCase; import csci3310.stalkyourfriends.presentation.view.NoteEditView; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import io.reactivex.Observable; import static junit.framework.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.verify; public class NoteEditPresenterTest { @Mock GetNoteUseCase getNoteUseCase; @Mock UpdateNoteUseCase updateNoteUseCase; @Mock DeleteNoteUseCase deleteNoteUseCase; @Mock NoteEditView mockNoteEditView; @Mock Observable mockObservable; private NoteEditPresenter noteEditPresenter; private NoteEditPresenter.GetNoteSubscriber getNoteSubscriber; private NoteEditPresenter.UpdateNoteSubscriber updateNoteSubscriber; private NoteEditPresenter.DeleteNoteSubscriber deleteNoteSubscriber; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); this.noteEditPresenter = new NoteEditPresenter(this.updateNoteUseCase, this.getNoteUseCase, this.deleteNoteUseCase); this.noteEditPresenter.initWithView(this.mockNoteEditView); this.getNoteSubscriber = this.noteEditPresenter.new GetNoteSubscriber(); this.updateNoteSubscriber = this.noteEditPresenter.new UpdateNoteSubscriber(); this.deleteNoteSubscriber = this.noteEditPresenter.new DeleteNoteSubscriber(); } @Test public void testDestroy() { this.noteEditPresenter.destroy(); verify(this.getNoteUseCase).unsubscribe(); verify(this.updateNoteUseCase).unsubscribe(); assertNull(this.noteEditPresenter.noteEditView); assertNull(this.noteEditPresenter.view); } @Test public void testGetNote() throws Exception { verify(this.mockNoteEditView).getNoteId(); verify(this.mockNoteEditView).showLoader(); verify(this.getNoteUseCase).setParams(any(int.class)); verify(this.getNoteUseCase).execute(any(NoteEditPresenter.GetNoteSubscriber.class)); } @Test public void testGetSubscriberOnCompleted() { this.getNoteSubscriber.onComplete(); verify(this.mockNoteEditView).hideLoader(); } @Test public void testGetSubscriberOnError() { this.getNoteSubscriber.onError(new RestApiErrorException("Error message", 500)); verify(this.mockNoteEditView).hideLoader(); verify(this.mockNoteEditView).handleError(any(Throwable.class)); } @Test @SuppressWarnings("unchecked") public void testGetSubscriberOnNext() { this.getNoteSubscriber.onNext(new NoteEntity(1, "", "")); verify(this.mockNoteEditView).showLoader(); verify(this.mockNoteEditView).hideLoader(); verify(this.mockNoteEditView).showNote(any(NoteEntity.class)); } @Test public void testUpdateNote() { this.noteEditPresenter.updateNote("", ""); verify(this.mockNoteEditView, atLeast(1)).getNoteId(); verify(this.mockNoteEditView, atLeast(1)).showLoader(); verify(this.updateNoteUseCase).setParams(any(NoteEntity.class)); verify(this.updateNoteUseCase).execute(any(NoteEditPresenter.UpdateNoteSubscriber.class)); } @Test public void testUpdateSubscriberOnCompleted() { this.updateNoteSubscriber.onComplete(); verify(this.mockNoteEditView).hideLoader(); } @Test public void testUpdateSubscriberOnError() { this.updateNoteSubscriber.onError(new RestApiErrorException("Error message", 500)); verify(this.mockNoteEditView).hideLoader(); verify(this.mockNoteEditView).handleError(any(Throwable.class)); } @Test @SuppressWarnings("unchecked") public void testUpdateSubscriberOnNext() { this.updateNoteSubscriber.onNext(new NoteEntity(1, "", "")); verify(this.mockNoteEditView).showLoader(); verify(this.mockNoteEditView).hideLoader(); verify(this.mockNoteEditView).close(); } @Test public void testDeleteNoteButtonPressed() { this.noteEditPresenter.deleteNoteButtonPressed(); verify(this.mockNoteEditView, atLeast(1)).getNoteId(); verify(this.deleteNoteUseCase).setParams(anyInt()); verify(this.deleteNoteUseCase).execute(any(NoteEditPresenter.DeleteNoteSubscriber.class)); } @Test public void testDeleteSubscriberOnCompleted() { this.deleteNoteSubscriber.onComplete(); verify(this.mockNoteEditView).hideLoader(); } @Test public void testDeleteSubscriberOnError() { this.deleteNoteSubscriber.onError(new RestApiErrorException("Error message", 500)); verify(this.mockNoteEditView).hideLoader(); verify(this.mockNoteEditView).handleError(any(Throwable.class)); } @Test @SuppressWarnings("unchecked") public void testDeleteSubscriberOnNext() { this.deleteNoteSubscriber.onNext(null); verify(this.mockNoteEditView).hideLoader(); verify(this.mockNoteEditView).close(); } }
[ "root@LENOVO-PC.localdomain" ]
root@LENOVO-PC.localdomain
0dae38f13a3b49ea7bc637f6cf8f880a5ab22b0e
54a87be201aa23ae6cbd91498600d335d647d5a7
/src/main/java/sulb/abm/org/config/DateTimeFormatConfiguration.java
feca53e140ae4f3dfb8d2aaf8915debde45c8f45
[]
no_license
Ricardorios08/sulb
bd19cac0457132697162b337f43c11b7b659d3fd
877c6aedfe6b4d28cf6c0475c1d25598a0bbc24c
refs/heads/main
2023-03-14T23:34:40.829052
2021-03-18T13:01:00
2021-03-18T13:01:00
349,075,248
0
0
null
null
null
null
UTF-8
Java
false
false
719
java
package sulb.abm.org.config; import org.springframework.context.annotation.Configuration; import org.springframework.format.FormatterRegistry; import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * Configure the converters to use the ISO format for dates by default. */ @Configuration public class DateTimeFormatConfiguration implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { DateTimeFormatterRegistrar registrar = new DateTimeFormatterRegistrar(); registrar.setUseIsoFormat(true); registrar.registerFormatters(registry); } }
[ "jhipster-bot@jhipster.tech" ]
jhipster-bot@jhipster.tech
1e4f691d045e72e94eca4b0e6ee26b8c54a108ff
2801515040ce99a8947cf624602ff47c9cd41c7c
/JlifterSimulater/disabled/Jlifter.java
8d3e57680155c8ad39771d87ba09ebd00a844b2b
[ "Apache-2.0" ]
permissive
yindaheng98/LittleProgramSet
9bf789d0b3cd127ebdc2f808ad9b4d1b2607912f
e45d76c5f082ec91def63089f5a10473b6762cf1
refs/heads/master
2023-01-09T09:31:27.570710
2022-12-27T14:53:07
2022-12-27T14:53:07
183,003,323
0
0
null
null
null
null
UTF-8
Java
false
false
7,569
java
package Jlifter; import java.util.Date; import java.util.LinkedList; import java.util.Queue; /** * 这是一个带有基本控制单元的电梯类 */ public class Jlifter extends Jlifter_basic { /** * Order类存储呼叫信息 * waittime的单位是毫秒 */ public class Order { int floor; long waittime; public Order(int floor, long waittime) { this.floor = floor; this.waittime = waittime; } } private Queue<Order> orders; private Date currenttime; private int recordtime; /** * 构造函数 * * @param vmax 最大运行速度 * @param acceleration 运行时加速度 * @param h_prefloor 层高 * @param topfloor 最高层数 * @param bottomfloor 最低层数 * @param recordt 采样周期,单位毫秒 * @param starttime 起始时间 */ public Jlifter(double vmax, double acceleration, double h_prefloor, int topfloor, int bottomfloor, int recordt, Date starttime) { super(vmax, acceleration, h_prefloor, topfloor, bottomfloor); if (Math.pow(vmax, 2) / acceleration > h_prefloor) throw new IllegalArgumentException("电梯在任何楼层之间的运行都要能加速到最大速度"); orders = new LinkedList<Order>(); currenttime = starttime; recordtime = recordt; } public Jlifter(double vmax, double acceleration, double h_prefloor, int topfloor, int bottomfloor, int recordt) { super(vmax, acceleration, h_prefloor, topfloor, bottomfloor); if (Math.pow(vmax, 2) / acceleration > h_prefloor) throw new IllegalArgumentException("电梯在任何楼层之间的运行都要能加速到最大速度"); orders = new LinkedList<Order>(); currenttime = new Date(); recordtime = recordt; } public Jlifter(double vmax, double acceleration, double h_prefloor, int topfloor, int bottomfloor) { super(vmax, acceleration, h_prefloor, topfloor, bottomfloor); orders = new LinkedList<Order>(); currenttime = new Date(); recordtime = 500; } /** * 设置采样周期 * * @param recordtime 采样周期,单位毫秒 */ public void setRecordtime(int recordtime) { this.recordtime = recordtime; } /** * 设置当前状态 * * @param time 当前时间 * @param floor 当前停在哪一层 */ public void setCondition(Date time, int floor) { if (floor > top_floor || floor < bottom_floor) throw new IllegalArgumentException("不存在此楼层"); super.setCondition(floor * height_prefloor, 0, 0, CommandList.stop, time); currenttime = time; } /** * 向预定队列插入数据 * * @param floor 预定所在楼层 * @param waittime 预计等待时间 */ public void giveOrder(int floor, long waittime) { if (floor > top_floor || floor < bottom_floor) throw new IllegalArgumentException("不存在此楼层"); orders.add(new Order(floor, waittime)); } /** * 存储电梯状态信息的类 * 只用在getState函数的返回值中 */ class States { public final double h; public final double v; public final int floor; public final Date time; public States(Date currenttime, double[] r) { time = currenttime; h = r[0]; v = r[1]; floor = (int) (h / height_prefloor); } } /** * 获取指定时间的电梯状态 * * @param time 指定的时间 * @return Status类型, 包含当前时间,当前楼层,当前位置速度加速度 */ public States getState(Date time) { if (time.before(currenttime)) throw new IllegalArgumentException("无法获取" + currenttime.toString() + "之前的电梯状态"); return new States(time, getCondition(time)); } /** * 从预定队列中取出一个order运行一次 */ public void runOne() { Order order = orders.poll(); if (order != null) run(order); else throw new NullPointerException("没有更多的指令可以运行"); } /** * 运行预定队列里的所有order */ public void runAll() { for (Order order = orders.poll(); order != null; order = orders.poll()) run(order); } /** * 运行一个order并生成历史记录 * * @param order 要运行的order */ private void run(Order order) { if (order.floor > top_floor || order.floor < bottom_floor) throw new IllegalArgumentException("不存在此楼层"); States states = getState(currenttime); int floor_diff = order.floor - states.floor; if (floor_diff == 0)//如果就在当前位置有预定 runStop(order.waittime); else//要上或要下 runNotStop(order, floor_diff); } /** * 如果不需要上行或下行 * * @param waittime 等待时间 */ private void runStop(long waittime) { giveCommand(currenttime, CommandList.stop); Date endtime = new Date(currenttime.getTime() + waittime); for (Date t = currenttime; t.before(endtime); t.setTime(t.getTime() + recordtime)) Record(getState(t)); currenttime = endtime; } /** * 如果需要上行或下行 * * @param order 要响应的order * @param floor_diff 上/下楼层数 */ private void runNotStop(Order order, int floor_diff) { // 上行/下行时间 long dt_run; long dt_stop; //总的移动距离 double dh = Math.abs(floor_diff * height_prefloor); if (dh < 2 * height_brake)//如果运行过程到不了最大速度 { dt_run = (long) (Math.sqrt(dh / a) * 1000); dt_stop = dt_run; } else { dt_run = (long) ((accelerate_time + (dh - height_brake * 2) / vMax) * 1000); dt_stop = (long) (accelerate_time * 1000); } //减速命令时间点 Date t_stopcmd = new Date(currenttime.getTime() + dt_run); //停机校准时间点 Date t_calibration = new Date(t_stopcmd.getTime() + dt_stop); //停止测量时间点 Date t_end = new Date(t_calibration.getTime() + order.waittime); giveCommand(currenttime, floor_diff > 0 ? CommandList.up : CommandList.down); for (Date t = currenttime; t.before(t_stopcmd); t.setTime(t.getTime() + recordtime)) Record(getState(t)); giveCommand(t_stopcmd, CommandList.stop); for (Date t = currenttime; t.before(t_calibration); t.setTime(t.getTime() + recordtime)) Record(getState(t)); setCondition(t_calibration, order.floor); for (Date t = currenttime; t.before(t_end); t.setTime(t.getTime() + recordtime)) Record(getState(t)); setCondition(t_end, order.floor); } protected void Record(States states) { String out = ""; out += "当前时间"; out += states.time.toString(); out += "当前楼层"; out += states.floor; out += "当前位置"; out += states.h; out += "当前速度"; out += states.v; System.out.println(out); } }
[ "yindaheng98@163.com" ]
yindaheng98@163.com
45a44200f69a884f07f1c8efc0bdb5a1bf236564
093fc671e53e41e1c2513f3f1e7b818ebf5d6428
/Project_android/app/src/main/java/project/innovation/com/project/ordered_details.java
4c8bc4bec1cce5cbe2ef1760690f28cc46813c97
[]
no_license
201711060/BookMytable
c0e2138e8b4fb5295dceeab41dfa7269c510c16c
d5f43afe06b95c054d00fd8beea3b034339ae0db
refs/heads/master
2020-03-27T06:33:03.424138
2018-08-25T17:32:46
2018-08-25T17:32:46
146,114,495
0
0
null
null
null
null
UTF-8
Java
false
false
7,503
java
package project.innovation.com.project; import android.app.ProgressDialog; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.json.JSONArray; import org.json.JSONObject; import cz.msebera.android.httpclient.Header; import project.innovation.com.project.Helper.GlobVars; public class ordered_details extends AppCompatActivity { JSONObject jo_main, jo_data; JSONArray ja_booking_items; TextView tvName, tvDate, tvTime, tvPhn, tvTblNm, tvRstNm, tvRstAddr, tvRstEmail, tvYourItems, tvItemsQty; ListView lvDetails; ProgressDialog pd; GlobVars gv; String URL = "http://aisomex.net/trainee_projects/table_booking/api/get_booking_details.php"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_ordered_details); setTitle("Your Booking Details"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); prepare_variables(); fill_data(); } private void fill_data() { AsyncHttpClient client = new AsyncHttpClient(); RequestParams params = new RequestParams(); params.put("tbk_id", gv.booking_id); client.get(this, URL, params, new AsyncHttpResponseHandler() { @Override public void onStart() { show_progress(); } @Override public void onFinish() { hide_progress(); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { jo_main = new JSONObject(new String(responseBody)); if (jo_main.getString("status").equals("success")) { jo_data = jo_main.getJSONObject("data"); set_data(); ja_booking_items = jo_data.getJSONArray("booking_items"); lvDetails.setAdapter(new DetailsAdapter()); } else { } } catch (Exception e) { Log.v("mye", "fill_data() :: ORDER DETAILS = " + e.toString()); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } }); } private void set_data() { try { tvName.setText(jo_data.getString("tbk_nm")); tvDate.setText(jo_data.getString("tbk_date")); tvTime.setText(jo_data.getString("tbk_time_slot")); tvPhn.setText(jo_data.getString("tbk_phn")); tvRstNm.setText(jo_data.getString("rst_nm")); tvRstAddr.setText(jo_data.getString("rst_addr") + "\n" + jo_data.getString("rst_phn1")); tvRstEmail.setText(jo_data.getString("rst_email")); tvTblNm.setText("Your table no. is: "+jo_data.getString("tbl_nm")); } catch (Exception e) { Log.v("mye","set_data :: ORDERED DETAILS = " + e.toString()); } } class DetailsAdapter extends BaseAdapter { @Override public int getCount() { return ja_booking_items.length(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater lf = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View v = lf.inflate(R.layout.design_layout_order_details_list, parent, false); TextView tvItem = (TextView) v.findViewById(R.id.tvOrderItem_design_details); TextView tvItemQty = (TextView) v.findViewById(R.id.tvOrderItemQty_design_details); try { String item = ja_booking_items.getJSONObject(position).getString("mitm_title"); if(item.length() > 10) { item = item.substring(0,10) + "..."; } tvItem.setText(item); tvItemQty.setText(ja_booking_items.getJSONObject(position).getString("tbi_mitm_qty")); } catch (Exception e) { Log.v("mye","DetailsAdapter :: ORDERED DETAILS = " + e.toString()); } return v; } } private void prepare_variables() { tvName = (TextView) findViewById(R.id.tvName_details); tvDate = (TextView) findViewById(R.id.tvDate_details); tvTime = (TextView) findViewById(R.id.tvTime_details); tvPhn = (TextView) findViewById(R.id.tvPhn_details); tvRstNm = (TextView) findViewById(R.id.tvRstNm_details); tvRstAddr = (TextView) findViewById(R.id.tvRstAddrPhn_details); tvRstEmail = (TextView) findViewById(R.id.tvRstEmail_details); tvTblNm = (TextView) findViewById(R.id.tvTblNm_details); tvYourItems = (TextView) findViewById(R.id.tvYourItems_disp); tvItemsQty = (TextView) findViewById(R.id.tvItemsQty_disp); lvDetails = (ListView) findViewById(R.id.lvDetails); gv = (GlobVars) getApplication(); if(getIntent().getStringExtra("ordered").equals("yes")) { tvYourItems.setVisibility(View.VISIBLE); tvItemsQty.setVisibility(View.VISIBLE); lvDetails.setVisibility(View.VISIBLE); } else { tvYourItems.setVisibility(View.VISIBLE); tvYourItems.setText("You have ordered nothing !"); tvItemsQty.setVisibility(View.GONE); lvDetails.setVisibility(View.GONE); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuItem miDone = menu.add(0,1,1,"Done"); miDone.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); miDone.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Intent i=new Intent(getApplicationContext(),ThankYouActivity.class); startActivity(i); return false; } }); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); break; default: break; } return super.onOptionsItemSelected(item); } private void show_progress() { pd = new ProgressDialog(this); pd.setMessage("Loading..."); pd.setCancelable(false); pd.show(); } private void hide_progress() { pd.dismiss(); } }
[ "shailjajesal@gmail.com" ]
shailjajesal@gmail.com
0b3e994f10bf16813aaf9c1d1d4c88d654d3a1a3
ca82198ea38572cf36ba98bbfa4ca3641ad6294c
/app/src/main/java/com/blartenix/proyecto_as_pm/Constants.java
31b4da65df744508cae9229a95530bae38690229
[]
no_license
sebastiancaicedo/Proyecto-AS-PM
3454ddf37056a4aa08e6293bbbd4e89c88f0705f
b57648ef75fca07bb87d14b36b552166f5815da1
refs/heads/master
2021-07-07T20:18:44.495344
2017-09-25T20:49:41
2017-09-25T20:49:41
102,995,268
0
0
null
null
null
null
UTF-8
Java
false
false
7,756
java
package com.blartenix.proyecto_as_pm; import android.content.Context; import android.text.TextUtils; import android.util.TypedValue; import java.util.ArrayList; import java.util.HashMap; import com.google.gson.*; /** * Created by lusec on 22/09/2017. */ public class Constants { public static Gson GsonHelper = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); public static String[] TAGS_NIVELES = new String[4]; static { TAGS_NIVELES[0]= "L1"; TAGS_NIVELES[1]= "L2"; TAGS_NIVELES[2]= "L3"; TAGS_NIVELES[3]= "L4"; } public static HashMap<String, Float> EQUIVALENCIA_NIVELES; static { EQUIVALENCIA_NIVELES = new HashMap<>(); EQUIVALENCIA_NIVELES.put(TAGS_NIVELES[0], 5.0f); EQUIVALENCIA_NIVELES.put(TAGS_NIVELES[1], 3.5f); EQUIVALENCIA_NIVELES.put(TAGS_NIVELES[2], 2.0f); EQUIVALENCIA_NIVELES.put(TAGS_NIVELES[3], 1.0f); } public static String singleDivider = "|"; //para vistas public static int convertDpToPixels(float dp, Context context) { int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()); return px; } //Para tamaño de textos public static int convertSpToPixels(float sp, Context context) { int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics()); return px; } public static Usuario getUsuarioDeserializado(String serial){ String c = ";u;"; String[] campos = serial.split(c); String codigo = campos[0]; String nombre = campos[1]; String email = campos[2]; String contrasena = campos[3]; ArrayList<Asignatura> asignaturas = getAsignturasDeserializadas(campos[4]);//Falta verificar si son nulas; ArrayList<Rubrica> rubricas = getRubricasDeserializadas(campos[5]); ArrayList<Evaluacion> evaluaciones = getEvaluacionesDeserializadas(campos[6]); return new Usuario(codigo, nombre, email, contrasena, asignaturas, rubricas, evaluaciones); } public static ArrayList<Asignatura> getAsignturasDeserializadas(String serial){ ArrayList<Asignatura> result = new ArrayList<>(); if(!TextUtils.equals(serial, "-")) { String[] asignaturas = serial.split(singleDivider); for (int indice = 0; indice < asignaturas.length; indice++) { result.add(getAsignaturaDeserializada(asignaturas[indice])); } } return result; } public static Asignatura getAsignaturaDeserializada(String serial){ String c = ";a;"; String[] campos = serial.split(c); String codigo = campos[0]; String nombre = campos[1]; ArrayList<Estudiante> estudiantes = getEstudiantesDeserializados(campos[2]); return new Asignatura(codigo, nombre, estudiantes); } public static ArrayList<Estudiante> getEstudiantesDeserializados(String serial){ ArrayList<Estudiante> result = new ArrayList<>(); if(TextUtils.equals(serial, "-")){ String[] estudiantes = serial.split(singleDivider); for (int indice = 0; indice < estudiantes.length; indice++){ result.add(getEstudianteDeserializado(estudiantes[indice])); } } return result; } public static Estudiante getEstudianteDeserializado(String serial){ String c = ";es;"; String[] campos = serial.split(c); String codigo = campos[0]; String nombre = campos[1]; return new Estudiante(codigo, nombre); } public static ArrayList<Rubrica> getRubricasDeserializadas(String serial){ ArrayList<Rubrica> result = new ArrayList<>(); if(!TextUtils.equals(serial, "-")){ String[] rubricas = serial.split(singleDivider); for (int indice = 0; indice < rubricas.length; indice++){ result.add(getRubricaDeserializada(rubricas[indice])); } } return result; } public static Rubrica getRubricaDeserializada(String serial){ String c = ";r;"; String[] campos = serial.split(c); String codigo = campos[0]; String nombre = campos[1]; //Siempre tenra por lo menos 1 cat y un elem ArrayList<Rubrica.CategoriaRubrica> categorias = new ArrayList<>(); String[] serialesCategs = campos[2].split(singleDivider); for (int indiceCat = 0; indiceCat < serialesCategs.length; indiceCat++){ String cC = ";cr;"; String[] camposCatg = serialesCategs[indiceCat].split(cC); String nombreCatg = camposCatg[0]; String pesoCatg = camposCatg[1]; ArrayList<Rubrica.ElementoCategoria> elementos = new ArrayList<>(); String[] serialesElems = camposCatg[2].split(singleDivider); for (int indiceElem = 0; indiceElem < serialesElems.length; indiceElem++){ String cE = ";ec;"; String[] camposElem = serialesElems[indiceElem].split(cE); String nombreElem = camposElem[0]; String pesoElem = camposElem[1]; String[] niveles = camposElem[2].split(";;"); elementos.add(new Rubrica.ElementoCategoria(indiceElem, nombreElem, pesoElem, niveles)); } categorias.add(new Rubrica.CategoriaRubrica(indiceCat, nombre, pesoCatg, elementos)); } return new Rubrica(codigo, nombre, categorias); } public static ArrayList<Evaluacion> getEvaluacionesDeserializadas(String serial){ ArrayList<Evaluacion> result = new ArrayList<>(); if(!TextUtils.equals(serial, "-")){ String[] serialesEvals = serial.split(singleDivider); for (int indice = 0;indice < serialesEvals.length; indice++){ String c = ";ev;"; String[] camposEval = serialesEvals[indice].split(c); String codigo = camposEval[0]; String nombre = camposEval[1]; Asignatura asignatura = getAsignaturaDeserializada(camposEval[2]); Rubrica rubrica = getRubricaDeserializada(camposEval[3]); //Siempre tendra calificaciones, sino no existira; ArrayList<Evaluacion.Calificacion> calificaciones = new ArrayList<>(); String[] serialesCalifs = camposEval[4].split(singleDivider); for (int indiceCalif= 0; indiceCalif < serialesCalifs.length; indiceCalif++){ String cC= ";ce;"; String[] camposCalif = serialesCalifs[indiceCalif].split(cC); Estudiante estudiante = getEstudianteDeserializado(camposCalif[0]); float califDef = Float.parseFloat(camposCalif[1]); String cMN = ";cn;"; String[] serialesMatrizNotas = camposCalif[2].split(cMN); Evaluacion.Calificacion.Nota[] matrizNotas = new Evaluacion.Calificacion.Nota[serialesMatrizNotas.length]; for (int indiceMatNota = 0; indiceMatNota < serialesMatrizNotas.length; indiceMatNota++){ String cN = ";;"; matrizNotas[indiceMatNota] = new Evaluacion.Calificacion.Nota(serialesMatrizNotas[indiceMatNota].split(cN)); } calificaciones.add(new Evaluacion.Calificacion(rubrica,indice, estudiante, califDef, matrizNotas)); } result.add(new Evaluacion(codigo, nombre, asignatura, rubrica, calificaciones)); } } return result; } }
[ "sebastiancaicedo@uninorte.edu.co" ]
sebastiancaicedo@uninorte.edu.co
5c5691a07956b81f6b409b3d3644b28a2acdfb33
563e8db7dba0131fb362d8fb77a852cae8ff4485
/Blagosfera/core/src/main/java/ru/radom/kabinet/web/flowofdocuments/dto/DataSourceAssociationFormDto.java
af8e30ac37c0172cf4c5fae40546cc9a579eeb2e
[]
no_license
askor2005/blagosfera
13bd28dcaab70f6c7d6623f8408384bdf337fd21
c6cf8f1f7094ac7ccae3220ad6518343515231d0
refs/heads/master
2021-01-17T18:05:08.934188
2016-10-14T16:53:38
2016-10-14T16:53:48
70,894,701
0
0
null
null
null
null
UTF-8
Java
false
false
923
java
package ru.radom.kabinet.web.flowofdocuments.dto; import lombok.Data; import ru.askor.blagosfera.domain.listEditor.ListEditorItem; import ru.radom.kabinet.model.rameralisteditor.RameraListEditorItem; /** * * Created by vgusev on 09.04.2016. */ @Data public class DataSourceAssociationFormDto { private Long id; private String name; public DataSourceAssociationFormDto(RameraListEditorItem listEditorItem) { if (listEditorItem != null) { setId(listEditorItem.getId()); setName(listEditorItem.getText()); } else { setId(-1l); setName(""); } } public DataSourceAssociationFormDto(ListEditorItem listEditorItem) { if (listEditorItem != null) { setId(listEditorItem.getId()); setName(listEditorItem.getText()); } else { setId(-1l); setName(""); } } }
[ "askor2005@yandex.ru" ]
askor2005@yandex.ru
f7edab3e39414723b8e93a48de97b9caef1a1d0f
cd532f41f6c7c4d648f362002152034179e2bb05
/RBMSystem/src/dao/tables/Stream.java
533a35c160a4b62aec9a941fbde5749dbc80b42f
[]
no_license
MirrorOath/RBMSystem
d475ca4ecc04e924d22d72600c2209853244810f
eb1e1ab6d0b3ab74132dcefbda9a671b28861982
refs/heads/master
2020-03-12T04:16:43.391793
2018-06-01T14:40:27
2018-06-01T14:40:27
130,442,038
0
0
null
null
null
null
UTF-8
Java
false
false
962
java
package dao.tables; public class Stream { private Integer id; private Integer streamId; private Integer tableId; private Integer peopleCount; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getStreamId() { return streamId; } public void setStreamId(Integer streamId) { this.streamId = streamId; } public Integer getTableId() { return tableId; } public void setTableId(Integer tableId) { this.tableId = tableId; } public Integer getPeopleCount() { return peopleCount; } public void setPeopleCount(Integer peopleCount) { this.peopleCount = peopleCount; } @Override public String toString() { return "SeatRotation [id=" + id + ", streamId=" + streamId + ", tableId=" + tableId + ", peopleCount=" + peopleCount + "]"; } }
[ "465717240@qq.com" ]
465717240@qq.com
8551828d167d68c83a4398e584d5073850005a1a
c1e2b249b403628c8bb6e3dabfce9360831650d1
/Blog_Server/src/com/Blog_Server/Dao/ly/DBHelper.java
0e8c24b599376768d98ee40b4ec061ac8844d4b6
[]
no_license
1149377117/git
2698e8e9a2c4e6f20142229281cc80dcdef1b73b
78247d4dc41a98ebe4ce19a793eef414ed2e9112
refs/heads/master
2020-04-08T01:56:03.894883
2018-11-24T08:14:39
2018-11-24T08:14:39
158,914,905
1
0
null
null
null
null
UTF-8
Java
false
false
17,194
java
package com.Blog_Server.Dao.ly; import java.io.BufferedInputStream; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Blob; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Vector; /** * 数据库操作助手类,实现上下文监听器接口,可加载数据库参数 * * @author 廖彦 * */ public class DBHelper { public static String URL = "jdbc:mysql://127.0.0.1/blog"; public static String USR = "root"; public static String PWD = "a"; public static String DRV = "com.mysql.jdbc.Driver"; static { init(); } private static void init() { try { System.out.println("数据库URL??" + URL); Class.forName(DRV); } catch (ClassNotFoundException ex) { throw new RuntimeException(ex); } } public static Connection getCon() { try { return DriverManager.getConnection(URL, USR, PWD); } catch (SQLException ex) { throw new RuntimeException(ex); } } public static void close(Connection con) { try { if (con != null) { con.close(); } } catch (SQLException e) { throw new RuntimeException(e); } } public static int update1(String sql, Object... paramArray) throws SQLException { Connection con = getCon(); PreparedStatement ps = null; ps = con.prepareStatement(sql); for (int i = 0; i < paramArray.length; i++) { ps.setObject(i + 1, paramArray[i]); } int count = ps.executeUpdate(); System.out.println(sql); /*for (Object o : paramArray) { System.out.print(o + ","); }*/ con.close(); return count; } public static int update(String sql, Object... params) { Connection con = getCon(); PreparedStatement pstm = null; try { System.out.println("SQL:" + sql); pstm = con.prepareStatement(sql); doParams(pstm, params); int rows = pstm.executeUpdate(); System.out.println("update rows " + rows); return rows; } catch (SQLException e) { throw new RuntimeException(e); } finally { close(con); } } @SuppressWarnings("unchecked") private static void doParams(PreparedStatement pstm, Object... params) { try { int i = 1; for (Object o : params) { // 如果元素是一个集合,则取出所有集合里的元素作为参?? // 不确定的参数类型,直接使用setObject,让jdbc去转?? if (o != null && o instanceof Collection) { for (Object p : (Collection<Object>) o) { System.out.println("参数" + i + "=" + p); pstm.setObject(i++, p); } } else if (o != null && o.getClass().isArray()) { for (Object p : (Object[]) o) { System.out.println("参数" + i + "=" + p); pstm.setObject(i++, p); } } else { System.out.println("参数" + i + "=" + o); pstm.setObject(i++, o); } } } catch (Exception e) { throw new RuntimeException(e); } } /** * 查询结果,返?? 集合类型?? Vector ,元素类型类型也?? Vector 的结果集 * * @param sql * @param params * @return */ @SuppressWarnings("unchecked") public static Vector<Vector<Object>> queryForVector(String sql, Object... params) { return select(sql, new Vector<Vector<Object>>().getClass(), new Vector<Object>().getClass(), params); } /** * 查询结果,以指定的实例类作为元素类型返回 List 结果?? * * @param sql * @param b * @param params * @return */ @SuppressWarnings("unchecked") public static <B> List<B> select(String sql, Class<B> b, Object... params) { return (List<B>) select(sql, new ArrayList<B>().getClass(), b, params); } /** * 查询结果,以Map作为元素类型返回 List 结果?? * * @param sql * @param params * @return */ @SuppressWarnings("unchecked") public static List<Map<String, Object>> select(String sql, Object... params) { return (List<Map<String, Object>>) select(sql, new ArrayList<HashMap<String, Object>>().getClass(), new HashMap<String, Object>().getClass(), params); } /** * @param sql * 执行的查询语?? * @param c * 返回集合的类型,如:ArrayList、Vector * @param b * 返回元素的类型,如:HashMap、Vector、ArrayList、实体类 * @param params * 参数:可变数组参数,没有参数则不?? * @return */ @SuppressWarnings("unchecked") public static <C extends Collection<B>, B> C select(String sql, Class<C> c, Class<B> b, Object... params) { Collection<B> list; Connection con = getCon(); ResultSet rs; PreparedStatement pstmt; try { System.out.println("SQL:" + sql); pstmt = con.prepareStatement(sql); doParams(pstmt, params); rs = pstmt.executeQuery(); list = toList(rs, c, b); } catch (Exception e) { throw new RuntimeException(e); } finally { close(con); } System.out.println("select rows " + list.size()); return (C) list; } /** * insert 方法,新增完成后返回自增主键值,注意:该方法不支持批?? insert * * @param sql * @param params * @return 返回第一个自增列的??? */ @SuppressWarnings("unchecked") public static List<List<Object>> insert(String sql, Object... params) { Connection con = getCon(); PreparedStatement pstm = null; try { System.out.println("SQL:" + sql); pstm = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); doParams(pstm, params); pstm.executeUpdate(); // 获取自增列???结果集 ResultSet rs = pstm.getGeneratedKeys(); return toList(rs, new ArrayList<ArrayList<Object>>().getClass(), new ArrayList<Object>().getClass()); } catch (Exception e) { throw new RuntimeException(e); } finally { close(con); } } /** * 构建 where 后面?? col1=? and col2=? 语句?? * * @param entity * @param paramList * @param containColumns * @return */ public static String buildWhere(Object entity, List<Object> paramList, String... containColumns) { StringBuilder sb = new StringBuilder(); if (entity != null) { for (Field f : BeanUtils.getAllFields(entity.getClass())) { // 包含下划线的属???是操作属??? if (f.getName().contains("_") == false && (containColumns.length == 0 || BeanUtils.contains(f.getName(), containColumns))) { String condition = buildCondition(entity, paramList, f); sb.append(condition); } } } return sb.length() == 0 ? " 1=1" : sb.toString().substring(4); } private static String buildCondition(Object entity, List<Object> paramList, Field field) { field.setAccessible(true); Object value = null; try { value = field.get(entity); } catch (Exception e) { e.printStackTrace(); } String expression = (String) BeanUtils.getValue(entity, field.getName() + "_expression"); String operator = (String) BeanUtils.getValue(entity, field.getName() + "_operator"); String condition = " and "; if (expression == null) { if (operator != null) { operator = " " + operator; } else if (value != null) { operator = " ="; } else { return ""; } String columnName = castDBName(field.getName()); condition += columnName + operator + " ?"; paramList.add(value); } else { String regex = "(\\$\\{([\\w\\.]+)\\})"; List<String[]> groups = StringUtils.getGroupList(expression, regex); expression = StringUtils.replaceAll(expression, regex, "?"); for (String[] group : groups) { Object v = BeanUtils.getValue(entity, group[1]); paramList.add(v); } condition += expression + " "; } return condition; } /** * 构建 update 语句后面?? set col1=?,col2=?,col3=? where id=? 语句?? * * @param entity * @param paramList * @param keyColumns * @return */ public static String buildUpdate(Object entity, List<Object> paramList, String... keyColumns) { Class<?> cls = entity.getClass(); String tablename = castDBName(cls.getSimpleName()); StringBuilder sb = new StringBuilder("UPDATE " + tablename + " SET "); for (Field f : BeanUtils.getAllFields(cls)) { f.setAccessible(true); Object value = null; try { value = f.get(entity); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if (value != null && BeanUtils.contains(f.getName(), keyColumns) == false) { String columnName = castDBName(f.getName()); sb.append(columnName).append(" = "); if (paramList == null) { if (value instanceof String) { sb.append("'").append(value).append("',"); } else { sb.append(value).append(","); } } else { sb.append("?,"); paramList.add(value); } } } String sql = sb.substring(0, sb.length() - 1).toString(); sql += " where " + buildWhere(entity, paramList, keyColumns); return sql; } /** * 构建 insert 语句后面?? (col1,col2,col3) values (?,?,?) 语句?? * * @param entity * @param paramList * @param containColumns * @return */ public static String buildInsert(Object entity, List<Object> paramList, String... containColumns) { Class<?> cls = entity.getClass(); StringBuilder sb1 = new StringBuilder(); StringBuilder sb2 = new StringBuilder(); for (Field f : BeanUtils.getAllFields(cls)) { f.setAccessible(true); Object value = null; try { value = f.get(entity); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } if (value != null && (containColumns.length == 0 || BeanUtils.contains(f.getName(), containColumns))) { String columnName = castDBName(f.getName()); sb1.append(columnName).append(","); if (paramList == null) { if (value instanceof String) { sb2.append("'").append(value).append("',"); } else { sb2.append(value).append(","); } } else { sb2.append("?,"); paramList.add(value); } } } String tablename = castDBName(cls.getSimpleName()); String sql = "INSERT INTO " + tablename + " (" + sb1.substring(0, sb1.length() - 1) + ") VALUES (" + sb2.substring(0, sb2.length() - 1) + ")"; return sql; } /** * ?? 结果?? ?? toList * * @param rs * @param c * @param b * @return * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException * @throws SQLException * @throws InstantiationException */ @SuppressWarnings("unchecked") private static <C extends Collection<B>, B> C toList(ResultSet rs, Class<C> c, Class<B> b) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, SQLException, InstantiationException { Collection<B> list; try { list = c.newInstance(); } catch (InstantiationException | IllegalAccessException e1) { throw new RuntimeException(e1); } Method[] ms = b.getMethods(); ResultSetMetaData md = rs.getMetaData(); String[] colnames = new String[md.getColumnCount()]; for (int i = 0; i < colnames.length; i++) { colnames[i] = md.getColumnName(i + 1); } B t; String mname = null; String cname = null; while (rs.next()) { t = (B) b.newInstance(); /** * 将结果集设置?? Collection 集合?? */ if (t instanceof Collection) { Collection<Object> coll = (Collection<Object>) t; for (int i = 0; i < colnames.length; i++) { coll.add(rs.getObject(colnames[i])); } /** * 将结果集设置?? Map 集合?? */ } else if (t instanceof Map) { Map<String, Object> map = (Map<String, Object>) t; for (int i = 0; i < colnames.length; i++) { map.put(colnames[i], rs.getObject(colnames[i])); } /** * 将结果集设置到实体对象中 */ } else { for (int i = 0; i < colnames.length; i++) { // 空???忽?? Object value = rs.getObject(colnames[i]); if (value == null) { continue; } cname = castJavaName(colnames[i]); // System.out.println(cname + "==" + colnames[i]); cname = "set" + cname.substring(0, 1).toUpperCase() + cname.substring(1).toLowerCase(); if (ms != null && ms.length > 0) { for (Method m : ms) { mname = m.getName(); if (cname.equalsIgnoreCase(mname)) { Class<?> cls = m.getParameterTypes()[0]; String clsName = cls.getSimpleName().toLowerCase(); switch (clsName) { case "byte": m.invoke(t, rs.getByte(colnames[i])); break; case "short": m.invoke(t, rs.getShort(colnames[i])); break; case "integer": m.invoke(t, rs.getInt(colnames[i])); break; case "long": m.invoke(t, rs.getLong(colnames[i])); break; case "float": m.invoke(t, rs.getFloat(colnames[i])); break; case "double": m.invoke(t, rs.getDouble(colnames[i])); break; case "string": m.invoke(t, rs.getString(colnames[i])); break; case "boolean": m.invoke(t, rs.getBoolean(colnames[i])); break; case "date": m.invoke(t, rs.getDate(colnames[i])); break; case "timestamp": m.invoke(t, rs.getTimestamp(colnames[i])); break; case "byte[]": BufferedInputStream is = null; byte[] bytes = null; Blob blob = rs.getBlob(colnames[i]); try { is = new BufferedInputStream(blob.getBinaryStream()); bytes = new byte[(int) blob.length()]; is.read(bytes); } catch (Exception e) { e.printStackTrace(); } m.invoke(t, bytes); break; default: System.out.println("未知类型??" + clsName + "===>" + value + ",听天由命了??"); m.invoke(t, value); } break; } } } } } list.add(t); } return (C) list; } public static String castJavaName(String columnName) { columnName = columnName.toLowerCase(); StringBuilder sb = new StringBuilder(); boolean b = false; for (Character c : columnName.toCharArray()) { if (c.equals('_')) { b = true; continue; } else if (b) { sb.append(sb.length() == 0 ? c : Character.toUpperCase(c)); b = false; } else { sb.append(c); } } return sb.toString(); } public static String castDBName(String fieldName) { StringBuilder sb = new StringBuilder(); for (Character c : fieldName.toCharArray()) { if (Character.isUpperCase(c)) { if (sb.length() == 0) { sb.append(Character.toLowerCase(c)); } else { sb.append("_").append(Character.toLowerCase(c)); } } else { sb.append(c); } } return sb.toString(); } /** * 将sql语句返回的第??行记录,转换?? Map 对象返回 * * @param sql * @param params * @return */ public static Map<String, Object> unique(String sql, Object... params) { List<Map<String, Object>> data = DBHelper.select(sql, params); if (data == null || data.isEmpty()) { return null; } else if (data.size() > 1) { throw new RuntimeException("返回的结果不是唯????"); } else { return data.get(0); } } /** * 将sql语句返回的第??行记录,转换成指定的实体类(cls)对象返?? * * @param sql * @param cls * @param params * @return */ public static <T> T unique(String sql, Class<T> cls, Object... params) { List<T> data = DBHelper.select(sql, cls, params); if (data == null || data.isEmpty()) { return null; } else if (data.size() > 1) { throw new RuntimeException("返回的结果不是唯????"); } else { return data.get(0); } } /** * 返回sql语句返回的第??行记录的指定字段(cnt)的?? * * @param sql * @param column * @param params * @return */ public static Object unique(String sql, String column, Object... params) { List<Map<String, Object>> data = DBHelper.select(sql, params); if (data == null || data.isEmpty()) { return null; } else if (data.size() > 1) { throw new RuntimeException("返回的结果不是唯????"); } else { return data.get(0).get(column); } } /** * * @param sql 查询sql * @param page 页数 * @param size 行数 * @param params 查询sql带的参数 * @return */ /*public static Page<Map<String, Object>> pageForMysql(String sql, Integer page, Integer size, Object... params) { // 查询分页数据 String querySql = sql + " limit ?, ?"; *//** * 注意参数的顺序,分页参数放在后面 *//* List<Map<String, Object>> data = DBHelper.select(querySql, params, size * (page - 1), size); // 查询总的记录?? String countSql = "select count(*) cnt from (" + sql + ") a"; // 返回sql语句返回的第??行记录的指定字段(cnt)的?? long total = (long) unique(countSql, "cnt", params); // 返回分页对象 return new Page<Map<String, Object>>(data, total); }*/ }
[ "18184366942@163.com" ]
18184366942@163.com
660b4c5c111496af92d16a274e5b5ece96824bf4
0da34459dd2eae26752dfe3e397dc78d086c5852
/src/main/java/com/example/richardsondeleon/quizlet/WordList.java
9847749e2abd63e1049402296386266952b1d9ff
[]
no_license
Isaaclipse/STEMtastic
a59b32ebee881f3089e2a67b6f2dd2669a7f54fd
28a2e0f9763b78ff6898fde4ca39ebdb667276ab
refs/heads/master
2020-04-03T05:59:20.702411
2018-10-28T16:42:29
2018-10-28T16:42:29
155,061,965
1
0
null
null
null
null
UTF-8
Java
false
false
608
java
package com.example.richardsondeleon.quizlet; import java.util.LinkedList; public class WordList<String> extends LinkedList<String> { public WordList(){ populateWordList(); } private void populateWordList() { this.addLast((String)"Engineering"); this.addLast((String)"Science"); this.addLast((String)"Geography"); this.addLast((String)"Math"); this.addLast((String)"Database"); this.addLast((String)"Technology"); for(int i=0; i<this.size(); i++){ this.set(i, (String)((i+1)+" "+this.get(i))); } } }
[ "noreply@github.com" ]
noreply@github.com
7a4b0cd15e97fd72731b7ff8ce7faa0039234049
0e26b937998e5612c8a4408dff6ce0b8cc440043
/src/util/storage/pair/DblIntPair.java
5cce709d385f11723c2d3d398e24dec0c6e95330
[]
no_license
dotnet54/TS-CHIEF
bd8931fd1ec57fc11f97853247ce8eab5f63c4e0
4a1f509b5bab51bb3a71f705ad7268e23323b81b
refs/heads/master
2022-08-12T02:04:40.409766
2022-07-28T01:31:15
2022-07-28T01:31:15
168,066,854
48
12
null
2022-05-20T22:00:58
2019-01-29T01:24:47
Java
UTF-8
Java
false
false
325
java
package util.storage.pair; public class DblIntPair{ public double key; public int value; public DblIntPair(double key, int value) { this.key = key; this.value = value; } // @Override // public int compareTo(K o) { // return key.compareTo(o); // } public String toString() { return key + " => " + value; } }
[ "dotnet54@gmail.com" ]
dotnet54@gmail.com
86a553c9de4d4d6f7508ad88738f94689a48ad5f
9fc132e3c5e32f9149e1e86f0dbbd0dacac757c6
/src/main/java/com/mc6007/t1/config/audit/AuditEventConverter.java
72d366da902f23cf4afafa058227d55f152c3e41
[]
no_license
leonardoavs/mc6007-T1
ce095ebefb56a706997f13228332005ac58e6c66
35c8137456881cb3370ee7e4801307dcdfa5b17b
refs/heads/master
2022-07-28T04:43:55.726149
2019-09-05T07:07:18
2019-09-05T07:07:18
205,459,787
0
0
null
null
null
null
UTF-8
Java
false
false
3,285
java
package com.mc6007.t1.config.audit; import com.mc6007.t1.domain.PersistentAuditEvent; import org.springframework.boot.actuate.audit.AuditEvent; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Component; import java.util.*; @Component public class AuditEventConverter { /** * Convert a list of {@link PersistentAuditEvent}s to a list of {@link AuditEvent}s. * * @param persistentAuditEvents the list to convert. * @return the converted list. */ public List<AuditEvent> convertToAuditEvent(Iterable<PersistentAuditEvent> persistentAuditEvents) { if (persistentAuditEvents == null) { return Collections.emptyList(); } List<AuditEvent> auditEvents = new ArrayList<>(); for (PersistentAuditEvent persistentAuditEvent : persistentAuditEvents) { auditEvents.add(convertToAuditEvent(persistentAuditEvent)); } return auditEvents; } /** * Convert a {@link PersistentAuditEvent} to an {@link AuditEvent}. * * @param persistentAuditEvent the event to convert. * @return the converted list. */ public AuditEvent convertToAuditEvent(PersistentAuditEvent persistentAuditEvent) { if (persistentAuditEvent == null) { return null; } return new AuditEvent(persistentAuditEvent.getAuditEventDate().toInstant(), persistentAuditEvent.getPrincipal(), persistentAuditEvent.getAuditEventType(), convertDataToObjects(persistentAuditEvent.getData())); } /** * Internal conversion. This is needed to support the current SpringBoot actuator {@code AuditEventRepository} interface. * * @param data the data to convert. * @return a map of {@link String}, {@link Object}. */ public Map<String, Object> convertDataToObjects(Map<String, String> data) { Map<String, Object> results = new HashMap<>(); if (data != null) { for (Map.Entry<String, String> entry : data.entrySet()) { results.put(entry.getKey(), entry.getValue()); } } return results; } /** * Internal conversion. This method will allow to save additional data. * By default, it will save the object as string. * * @param data the data to convert. * @return a map of {@link String}, {@link String}. */ public Map<String, String> convertDataToStrings(Map<String, Object> data) { Map<String, String> results = new HashMap<>(); if (data != null) { for (Map.Entry<String, Object> entry : data.entrySet()) { // Extract the data that will be saved. if (entry.getValue() instanceof WebAuthenticationDetails) { WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) entry.getValue(); results.put("remoteAddress", authenticationDetails.getRemoteAddress()); results.put("sessionId", authenticationDetails.getSessionId()); } else { results.put(entry.getKey(), Objects.toString(entry.getValue())); } } } return results; } }
[ "leonardoavs@gmail.com" ]
leonardoavs@gmail.com
4bd1aa236234ff3818970707e9a2f11357cbb271
c1c8a1d6dd537d3f0b8d5a66ac8fd6096badf47b
/src/main/java/com/bayer/tacocloud/repositiory/IngredientRepository.java
2aa9d9fbc1dd11643f14b242d41c598d16e90381
[]
no_license
Bakejayer/taco-cloud
ed6dd8cf570b419f38dd314924cebafa558e9483
225d083da860d6b3256ab77c3b6969d5f4e40adc
refs/heads/master
2023-03-08T08:33:45.538125
2021-02-23T18:40:46
2021-02-23T18:40:46
328,497,522
0
0
null
null
null
null
UTF-8
Java
false
false
232
java
package com.bayer.tacocloud.repositiory; import com.bayer.tacocloud.model.Ingredient; import org.springframework.data.repository.CrudRepository; public interface IngredientRepository extends CrudRepository<Ingredient, String> { }
[ "jbbuilder8@yahoo.com" ]
jbbuilder8@yahoo.com
982f95380f62713982e653f7b72fbb0be08a1b18
d1877b54fc73375a870f95a33c9c2f657b05a487
/src/main/java/io/pivotal/pal/tracker/TimeEntryHealthIndicator.java
6359071e13ab549dc9698a29a58e2d5bcdef0244
[]
no_license
jtakahas/pal-tracker
53632072fe7e6ce5b523ca9d276b72b4ec2d2e33
856d0695300018782b9b8e20c18341808579cdcb
refs/heads/master
2020-03-31T15:33:00.082148
2018-10-12T05:10:25
2018-10-12T05:10:25
152,341,856
0
0
null
null
null
null
UTF-8
Java
false
false
793
java
package io.pivotal.pal.tracker; import org.springframework.boot.actuate.health.Health; import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.stereotype.Component; @Component public class TimeEntryHealthIndicator implements HealthIndicator { private static final int MAX_TIME_ENTRIES = 5; private final TimeEntryRepository timeEntryRepo; public TimeEntryHealthIndicator(TimeEntryRepository timeEntryRepo) { this.timeEntryRepo = timeEntryRepo; } @Override public Health health() { Health.Builder builder = new Health.Builder(); if(timeEntryRepo.list().size() < MAX_TIME_ENTRIES) { builder.up(); } else { builder.down(); } return builder.build(); } }
[ "takahashi.ju-07@jp.fujitsu.com" ]
takahashi.ju-07@jp.fujitsu.com
f2c07b5a3e246555062d375b868bf4579f8260c3
d51f142ddb941ad57a43f62f5ff918b9a9639316
/PictureStatistic/src/ch/boxi/pictureStatistic/loader/exifTagReader/readers/CameraModelReader.java
5ac2fab7226575c8b94d6852131c9361012014d3
[]
no_license
theBoxi/PictureStatistic
2494ef3b87c614442390670b823440f1c8b87d45
f5f4927a2769883a44b7dd9d3599668ee220e683
refs/heads/master
2016-09-05T08:46:01.176360
2011-12-11T13:39:22
2011-12-11T13:39:22
2,957,595
0
0
null
null
null
null
UTF-8
Java
false
false
737
java
package ch.boxi.pictureStatistic.loader.exifTagReader.readers; import ch.boxi.pictureStatistic.loader.Camera; import ch.boxi.pictureStatistic.loader.FileData; import ch.boxi.pictureStatistic.loader.exifTagReader.ExifTagReader; import com.drew.metadata.MetadataException; import com.drew.metadata.Tag; public class CameraModelReader implements ExifTagReader { private static final String tagName = "Model"; @Override public void readTag(Tag tag, FileData data) throws MetadataException { Camera cam = new Camera(tag.getDescription()); data.setC(cam); } @Override public boolean canReadTag(Tag tag) { return tag.getTagName().equalsIgnoreCase(tagName); } @Override public String getTagName() { return tagName; } }
[ "boxi@Linde" ]
boxi@Linde
36a5f84de26b07f1f561a30a3ec8a55c2c193804
5501c71a94413a1cd6286ac2405ca125b2b0f5dc
/appdeck-android/app/src/main/java/com/mobideck/appdeck/SmartWebViewInterface.java
20772d05e644f6806cbb9d4a6f73068e1e7fdbdc
[]
no_license
kleitz/appdeck
2f6ef68c3382fc031a264fd695a3beeec26e1fcd
7483cdafe85807d35a8d885f87224e4dfcd7c30a
refs/heads/master
2021-01-12T22:31:25.671759
2015-04-07T14:31:17
2015-04-07T14:31:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,567
java
package com.mobideck.appdeck; import android.os.Bundle; /** * Created by mathieudekermadec on 19/02/15. */ public interface SmartWebViewInterface { public void setTouchDisabled(boolean touchDisabled); public boolean getTouchDisabled(); public void pause(); public void resume(); public void clean(); public void unloadPage(); public boolean smartWebViewRestoreState(Bundle savedInstanceState); public boolean smartWebViewSaveState(Bundle outState); public String resolve(String relativeURL); public void loadUrl(String absoluteURL); public void reload(); public void stopLoading(); public void setForceCache(boolean forceCache); void evaluateJavascript(java.lang.String script, android.webkit.ValueCallback<java.lang.String> callback); //public void copyScrollTo(SmartWebView target); public int fetchHorizontalScrollOffset(); public int fetchVerticalScrollOffset(); public void scrollTo(int x, int y); /*{ SmartWebViewCrossWalk target = (SmartWebViewCrossWalk)_target; computeScroll(); int x = computeHorizontalScrollOffset(); int y = computeVerticalScrollOffset(); target.scrollTo(x, y); }*/ public void setRootAppDeckFragment(AppDeckFragment root); // Webview API public void smartWebViewGoBack(); public void smartWebViewGoForward(); public String smartWebViewGetTitle(); public String smartWebViewGetUrl(); public boolean smartWebViewCanGoBack(); public boolean smartWebViewCanGoForward(); }
[ "mathieu@mobideck.net" ]
mathieu@mobideck.net
48fd2fd87a9036af6ca0322ca43236c2140413f7
4ae6c1de5d2ff16c43f6fac95c98eaea67eb1627
/HelloWorld/src/Hello.java
de370df3d150c71c195af4916a0c1cf75238ed13
[]
no_license
spemer/study_java
010d5c4e50a07a1f2d4006c1a2049a3d718adbee
732c1c28bd6eaf38b49648e2abd55e0c658fe2a1
refs/heads/master
2021-01-17T20:52:44.367967
2017-06-27T18:11:38
2017-06-27T18:11:38
95,586,944
1
0
null
null
null
null
UHC
Java
false
false
190
java
public class Hello //클래스 Hello 가 시작되는 문장 { public static void main(String[] args) // 메소드 main 이 시작되는 문장 { System.out.println("Hello World"); } }
[ "ghsspower@naver.com" ]
ghsspower@naver.com
fb1e1434a3bfc2ed04bbae4e61996da5c3ea88e4
ce59a95b92234a40785b6e5cee62c1e7e9f61a9a
/OBSH_client/src/main/java/presentation/view/UserView.java
50a9dcdbfdffa25ba5d13f619f0d2096b68796e8
[]
no_license
OBSH-SoftAttract/OBSH
51b467b02a0745258d79ccaa94f3d935d3ef6b8f
02b77767e36e3d3e2b36bdaffefee3f125982f92
refs/heads/master
2021-01-24T08:55:08.360282
2016-12-31T15:53:55
2016-12-31T15:53:55
69,249,058
0
1
null
null
null
null
UTF-8
Java
false
false
11,298
java
package presentation.view; import java.rmi.RemoteException; import ResultMessage.ResultMessage; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.stage.Stage; import javafx.stage.StageStyle; import presentation.controller.UserViewControllerImpl; public class UserView { private Button login; private Button register = new Button("注册"); private Scene scene; private Scene searchscene; private TextField usernametf = new TextField(); private PasswordField passwordtf = new PasswordField(); private UserViewControllerImpl userviewService; public UserView(UserViewControllerImpl controller) { this.userviewService = controller; } public Stage Main() { Stage primaryStage = new Stage(); usernametf.setPromptText("username"); usernametf.setMaxSize(150, 20); primaryStage.initStyle(StageStyle.TRANSPARENT); passwordtf.setPromptText("password"); passwordtf.setMaxSize(150, 20); register.setFont(Font.font("黑体", 15)); register.setTextFill(Color.WHITE); register.setMaxSize(65, 15); login = new Button("登录"); login.setFont(Font.font("黑体", 15)); login.setTextFill(Color.WHITE); login.setMaxSize(65, 15); register.setStyle("-fx-background-color:#7bbfea;"); login.setStyle("-fx-background-color:#7bbfea;"); HBox hbBtn = new HBox(20); hbBtn.getChildren().add(login); hbBtn.getChildren().add(register); hbBtn.setSpacing(20); hbBtn.setMaxSize(300, 200); hbBtn.setAlignment(Pos.CENTER); HBox top = new HBox(); Button close = new Button(); close.setMaxSize(30, 30); close.setMinSize(30, 30); top.getChildren().add(close); top.setMaxHeight(30); top.setPadding(new Insets(0, 0, 0, 0)); close.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.exit(0); } }); VBox loginvb = new VBox(usernametf, passwordtf, hbBtn); BorderPane root = new BorderPane(); loginvb.setSpacing(30); root.setTop(top); top.setAlignment(Pos.TOP_LEFT); loginvb.setAlignment(Pos.CENTER); root.setCenter(loginvb); scene = new Scene(root); scene.getStylesheets().add("presentation/view/application.css"); close.getStyleClass().add("CloseButton"); InitStage(primaryStage, scene); // 注册按钮的事件 register.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { // 跳转至注册界面 BorderPane register = jumptoRegisterFrame(primaryStage); Scene registerscene = new Scene(register); registerscene.getStylesheets().add("presentation/view/Register.css"); primaryStage.setScene(registerscene); // InitStage是将所有的stage都设置成一个大小的方法 InitStage(primaryStage, registerscene); } }); // 登录按钮的事件 login.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { String userId = usernametf.getText(); String password = passwordtf.getText(); ResultMessage re = null; try { re = userviewService.Login(userId, password); } catch (RemoteException e) { e.printStackTrace(); } switch (re) { case FormatWrong: LoginFail("用户名错误,请重新输入", primaryStage); break; case NotExist: LoginFail("用户名不存在,请重新输入", primaryStage); break; case WrongPassword: LoginFail("密码错误,请重新输入", primaryStage); break; case NULL: LoginFail("请输入完整", primaryStage); break; default:// 登录成功 try { userviewService.setUserID(Integer.parseInt(userId)); } catch (NumberFormatException e) { e.printStackTrace(); } catch (RemoteException e) { e.printStackTrace(); } UserMainFrame umf = new UserMainFrame(userviewService); BorderPane mainFrame = umf.jumptoUserMainFrame(); searchscene = new Scene(mainFrame); searchscene.getStylesheets().add("presentation/view/login.css"); primaryStage.setScene(searchscene); // InitStage是将所有的stage都设置成一个大小的方法 InitStage(primaryStage, searchscene); } } }); return primaryStage; } public void LoginFail(String s, Stage primaryStage) { // 显示登录失败 BorderPane failbp = new BorderPane(); usernametf.setDisable(true); passwordtf.setDisable(true); VBox tip = new VBox(); VBox vb = new VBox(); tip.setAlignment(Pos.CENTER); vb.setAlignment(Pos.CENTER); Button confirm = new Button(); confirm.setText("确定"); confirm.getStyleClass().add("Button"); vb.setSpacing(10); vb.getChildren().addAll(addText("登录失败"), addText(s)); tip.setSpacing(10); tip.getChildren().addAll(vb, confirm); VBox vbox = new VBox(usernametf, passwordtf, tip); vbox.setSpacing(40); vbox.setAlignment(Pos.CENTER); HBox top = new HBox(); Button close = new Button(); close.setMaxSize(30, 30); close.setMinSize(30, 30); top.getChildren().add(close); top.setMaxHeight(30); top.setPadding(new Insets(0, 0, 0, 0)); close.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.exit(0); } }); failbp.setTop(top); failbp.setCenter(vbox); Scene failloginscene = new Scene(failbp); failloginscene.getStylesheets().add("presentation/view/faillogin.css"); close.getStyleClass().add("CloseButton"); InitStage(primaryStage, failloginscene); confirm.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { // 返回登录界面 primaryStage.close(); usernametf.setDisable(false); passwordtf.setDisable(false); Main(); } }); } // 对text的字体设定 public Text addText(String s) { Text text = new Text(s); text.setFont(Font.font("冬青黑体简体中文", 15)); return text; } public HBox addTop() { HBox top = new HBox(); top.setMaxHeight(30); top.setMinHeight(30); top.setPadding(new Insets(5, 700, 5, 840)); return top; } public void InitStage(Stage primaryStage, Scene scene) { primaryStage.setScene(scene); primaryStage.setTitle("酒店线上预订系统OBSH"); primaryStage.setHeight(700); primaryStage.setWidth(900); primaryStage.setResizable(false); primaryStage.show(); } // 回到登录主界面 public void backtoMain(Stage primaryStage) { usernametf = new TextField(); usernametf.setPromptText("username"); usernametf.setMaxSize(150, 20); passwordtf = new PasswordField(); passwordtf.setPromptText("password"); passwordtf.setMaxSize(150, 20); register = new Button("注册"); register.setFont(Font.font("黑体", 15)); register.setTextFill(Color.WHITE); register.setMaxSize(65, 15); login = new Button("登录"); login.setFont(Font.font("黑体", 15)); login.setTextFill(Color.WHITE); login.setMaxSize(65, 15); register.setStyle("-fx-background-color:#7bbfea;"); login.setStyle("-fx-background-color:#7bbfea;"); HBox hbBtn = new HBox(20); hbBtn.getChildren().add(login); hbBtn.getChildren().add(register); hbBtn.setSpacing(20); hbBtn.setMaxSize(300, 200); hbBtn.setAlignment(Pos.CENTER); VBox root = new VBox(usernametf, passwordtf, hbBtn); root.setMaxSize(300, 200); root.setSpacing(40); root.setAlignment(Pos.CENTER); scene = new Scene(root); scene.getStylesheets().add("presentation/view/application.css"); primaryStage.setScene(scene); } // 跳转到注册界面 public BorderPane jumptoRegisterFrame(Stage primaryStage) { TextField userNametf; TextField passwtf; TextField conpasstf; TextField phonenumtf; GridPane grid = new GridPane(); grid.setVgap(15); grid.setHgap(15); grid.setAlignment(Pos.CENTER); Text username = new Text("名称"); Text phonenum = new Text("手机号"); Text password = new Text("密码"); Text confirmpassword = new Text("确认密码"); Text notion = new Text("提示:内容不可为空"); userNametf = new TextField(); passwtf = new TextField(); conpasstf = new TextField(); phonenumtf = new TextField(); grid.add(username, 0, 0); grid.add(userNametf, 0, 1); grid.add(phonenum, 1, 0); grid.add(phonenumtf, 1, 1); grid.add(password, 0, 2); grid.add(passwtf, 0, 3); grid.add(confirmpassword, 1, 2); grid.add(conpasstf, 1, 3); HBox button = new HBox(); button.setSpacing(15); button.setPadding(new Insets(20, 0, 20, 0)); button.setAlignment(Pos.CENTER); Button confirm = new Button("确定"); button.getChildren().addAll(confirm); button.setMaxSize(200, 20); HBox top = new HBox(); Button close = new Button(); close.setMaxSize(30, 30); close.setMinSize(30, 30); top.getChildren().add(close); top.setMaxHeight(30); top.setPadding(new Insets(0, 0, 0, 0)); close.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.exit(0); } }); VBox root = new VBox(); root.setAlignment(Pos.CENTER); root.setPadding(new Insets(230, 0, 0, 0)); root.getChildren().addAll(grid, button, notion); confirm.getStyleClass().add("Button"); close.getStyleClass().add("CloseButton"); confirm.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { String username = userNametf.getText(); String password = passwtf.getText(); String conpassword = conpasstf.getText(); String phonenum = phonenumtf.getText(); // 处理用户输入 if (!password.equals(conpassword)) { notion.setText("密码不一致"); } else if (password.length() > 12) notion.setText("密码位数过长"); else { int userId = 0; try { userId = userviewService.Register(username, password, phonenum); } catch (RemoteException e) { e.printStackTrace(); } if (username.equals("") || password.equals("") || phonenum.equals("")) notion.setText("内容不能为空"); else { registerSuccess(userId); } } } }); BorderPane border = new BorderPane(); border.setTop(top); border.setCenter(root); return border; } public void registerSuccess(int userID) { Stage stage = new Stage(); Text text = new Text("注册成功!欢迎您:" + userID + "(请记住账号)"); Button button = new Button("确定"); VBox vb = new VBox(); vb.setSpacing(10); vb.getChildren().addAll(text, button); vb.setMinSize(200, 200); vb.setMaxSize(200, 200); vb.setAlignment(Pos.CENTER); Scene scene = new Scene(vb); stage.setScene(scene); stage.show(); button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { stage.close(); UserViewControllerImpl user = new UserViewControllerImpl(); UserView umf = new UserView(user); Stage stage = umf.Main(); stage.show(); } }); } }
[ "530660508@qq.com" ]
530660508@qq.com
b994b60f04109c67a7c259f82e8e62b9882cafe6
84d4c12d7dffe314cc49a4cda5dd1ee7e80d4676
/grpc-server-spring-boot-autoconfigure/src/main/java/net/devh/boot/grpc/server/security/authentication/AnonymousAuthenticationReader.java
43c5e2b38749a2bcff6c959bc6c1106fbd67b12f
[ "MIT" ]
permissive
followwwind/grpc-spring-boot-starter
3b7103279dcf7edce76c979abb1dfd51e035bcc3
a6ff30c466e097368f6c7b135385d2ebe6e5a4cd
refs/heads/master
2022-11-24T07:45:07.386720
2020-07-29T03:47:44
2020-07-29T03:47:44
283,687,228
1
0
MIT
2020-07-30T06:21:37
2020-07-30T06:21:36
null
UTF-8
Java
false
false
3,405
java
/* * Copyright (c) 2016-2020 Michael Zhang <yidongnan@gmail.com> * * 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 net.devh.boot.grpc.server.security.authentication; import static java.util.Objects.requireNonNull; import java.util.Collection; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import io.grpc.Metadata; import io.grpc.ServerCall; import lombok.extern.slf4j.Slf4j; /** * The AnonymousAuthenticationReader allows users without credentials to get an anonymous identity. * * @author Daniel Theuke (daniel.theuke@heuboe.de) */ @Slf4j public class AnonymousAuthenticationReader implements GrpcAuthenticationReader { private final String key; private final Object principal; private final Collection<? extends GrantedAuthority> authorities; /** * Creates a new AnonymousAuthenticationReader with the given key and {@code "anonymousUser"} as principal with the * {@code ROLE_ANONYMOUS}. * * @param key The key to used to identify tokens that were created by this instance. */ public AnonymousAuthenticationReader(final String key) { this(key, "anonymousUser", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")); } /** * Creates a new AnonymousAuthenticationReader with the given key,principal and authorities. * * @param key The key to used to identify tokens that were created by this instance. * @param principal The principal which will be used to represent anonymous users. * @param authorities The authority list for anonymous users. */ public AnonymousAuthenticationReader(final String key, final Object principal, final Collection<? extends GrantedAuthority> authorities) { this.key = requireNonNull(key, "key"); this.principal = requireNonNull(principal, "principal"); this.authorities = requireNonNull(authorities, "authorities"); } @Override public Authentication readAuthentication(final ServerCall<?, ?> call, final Metadata headers) { log.debug("Continue with anonymous auth"); return new AnonymousAuthenticationToken(this.key, this.principal, this.authorities); } }
[ "ST-DDT@gmx.de" ]
ST-DDT@gmx.de
1b7fc893896f7b060eb7384b00c4781fc8b9aa33
5faccff6289b2f706b67373cd8ece24658c9baf6
/presentation-service/src/main/java/com/handson/presentationservice/pojo/Employee.java
171ce21e3da965c2f122419a9c91e56b67de9ec6
[]
no_license
dineshchothe2020/Assignments
80f5bd1e0db0431c268130be15a59f1301590079
9e080fdce9998e70d7a67da6ec3be37ac93b06e0
refs/heads/master
2022-11-05T00:23:26.196753
2020-06-16T14:45:47
2020-06-16T14:45:47
272,723,135
0
0
null
null
null
null
UTF-8
Java
false
false
1,410
java
package com.handson.presentationservice.pojo; import java.time.LocalDate; public class Employee { private String name; private String address; private String phoneNumber; private LocalDate dateOfJoining; private String techStack; public String getName() { return name; } public String getAddress() { return address; } public String getPhoneNumber() { return phoneNumber; } public LocalDate getDateOfJoining() { return dateOfJoining; } public String getTechStack() { return techStack; } public void setName(String name) { this.name = name; } public void setAddress(String address) { this.address = address; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public void setDateOfJoining(LocalDate dateOfJoining) { this.dateOfJoining = dateOfJoining; } public void setTechStack(String techStack) { this.techStack = techStack; } @Override public String toString() { return "Employee{" + "name='" + name + '\'' + ", address='" + address + '\'' + ", phoneNumber='" + phoneNumber + '\'' + ", dateOfJoining=" + dateOfJoining + ", techStack='" + techStack + '\'' + '}'; } }
[ "dchothe@gmail.com" ]
dchothe@gmail.com
daf4a9ef77707e76abc63b2fef3640eef8243a12
f551ac18a556af60d50d32a175c8037aa95ec3ac
/shop/com/enation/app/shop/core/tag/comment/MemberIsCommentTag.java
123f77659dc5ee586710f683ee2ff561c7f7e863
[]
no_license
yexingf/cxcar
06dfc7b7970f09dae964827fcf65f19fa39d35d1
0ddcf144f9682fa2847b9a350be91cedec602c60
refs/heads/master
2021-05-15T05:40:04.396174
2018-01-09T09:46:18
2018-01-09T09:46:18
116,647,698
0
5
null
null
null
null
UTF-8
Java
false
false
1,808
java
package com.enation.app.shop.core.tag.comment; import java.util.HashMap; import java.util.Map; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.enation.app.base.core.model.Member; import com.enation.app.shop.core.service.IMemberOrderItemManager; import com.enation.eop.sdk.user.UserServiceFactory; import com.enation.framework.taglib.BaseFreeMarkerTag; import freemarker.template.TemplateModelException; /** * 会员是否可以评论标签 * @author lina * 2014-2-19 */ @Component @Scope("prototype") public class MemberIsCommentTag extends BaseFreeMarkerTag { private IMemberOrderItemManager memberOrderItemManager; /** * 会员是否可以评论标签 * @param 无 * @return Map型,其中的key结构为: * goodsid:商品id * isLogin:是否登录 * isBuy:是否购买了 * isCommented:是否评论过 */ @Override protected Object exec(Map params) throws TemplateModelException { Map result = new HashMap(5); Integer goods_id =(Integer) params.get("goods_id"); result.put("goods_id",goods_id); Member member = UserServiceFactory.getUserService().getCurrentMember(); if(member == null){ result.put("isLogin",false); }else{ result.put("isLogin",true); int buyCount = memberOrderItemManager.count(member.getMember_id(), goods_id); int commentCount = memberOrderItemManager.count(member.getMember_id(), goods_id,1); result.put("isBuy", buyCount > 0); result.put("isCommented",commentCount >= buyCount); } return result; } public IMemberOrderItemManager getMemberOrderItemManager() { return memberOrderItemManager; } public void setMemberOrderItemManager( IMemberOrderItemManager memberOrderItemManager) { this.memberOrderItemManager = memberOrderItemManager; } }
[ "274674758_ye@sina.com" ]
274674758_ye@sina.com
b87b3d1171c0014c76e624d85e55b3acdb9b5bb8
47eddb07c4a35880cbef90aca3c70ede44d5dea8
/ElAulaBot/src/main/java/com/example/ElAulaBot/bl/ArchivoBl.java
95fbbebdb86cba4b4f9dad53bb80a5ab89ac319b
[]
no_license
Dylan099/AulaBot
1b12519f0b045ae6221ec387aa0b4f220d4df6f6
b5e65ba525dc8f1b13bc20ef1b92021a88eeb412
refs/heads/master
2021-07-18T01:04:03.505580
2019-12-12T22:43:30
2019-12-12T22:43:30
218,708,125
2
0
null
null
null
null
UTF-8
Java
false
false
1,976
java
package com.example.ElAulaBot.bl; import com.example.ElAulaBot.app.ElAulaBot; import com.example.ElAulaBot.dao.ArchivoRepository; import com.example.ElAulaBot.domain.Archivo; import com.example.ElAulaBot.domain.Curso; import com.example.ElAulaBot.domain.CursoHasEstudiante; import com.example.ElAulaBot.dto.Status; 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 org.telegram.telegrambots.meta.api.objects.Update; import java.util.Date; import java.util.List; @Service @Transactional public class ArchivoBl { ArchivoRepository archivoRepository; private static final Logger LOGGER = LoggerFactory.getLogger(ArchivoBl.class); @Autowired public ArchivoBl(ArchivoRepository archivoRepository){ this.archivoRepository = archivoRepository; } public Archivo crearArchivo(Curso curso, Update update, List<CursoHasEstudiante> estudiantesNotificar1){ LOGGER.info("CREANDO Archivo "+ update); Archivo newArchivo = new Archivo(); newArchivo.setIdCurso(curso); newArchivo.setNombreAr(update.getMessage().getDocument().getFileName()); newArchivo.setTamanioAr(update.getMessage().getDocument().getFileSize().toString()); newArchivo.setUrlAr(update.getMessage().getDocument().getFileId().toString()); newArchivo.setFechaPublicacionAr(new Date()); newArchivo.setTipoMime(update.getMessage().getDocument().getMimeType()); newArchivo.setTxhost("localhost"); newArchivo.setTxuser("admin"); newArchivo.setTxdate(new Date()); newArchivo.setStatus(Status.ACTIVE.getStatus()); archivoRepository.save(newArchivo); ElAulaBot elAulaBot = new ElAulaBot(); elAulaBot.notificarDocument(estudiantesNotificar1, update); return newArchivo; } }
[ "dylan.mariscal.salas@gmail.com" ]
dylan.mariscal.salas@gmail.com
ddb4b26bbb50f196755a43e40618193cade624be
5d06fb9d11d61ccd06aa0c1a3aa8c23704804a50
/Practice Day 4/src/com/hsbc/exceptions/TryingRethrow.java
c412d051baf5d3bf69cb6fa88435e35d961fe454
[]
no_license
OmAshish/Java-Programming
ab2e12acfe076c8e8261d072dea49acb1b140d0c
1ff5bd394aea13455406c58870c1ea55be4bd461
refs/heads/master
2022-12-21T00:04:48.200691
2020-09-28T14:48:21
2020-09-28T14:48:21
299,338,057
0
0
null
null
null
null
UTF-8
Java
false
false
454
java
package com.hsbc.exceptions; public class TryingRethrow { public static void main(String[] args) { try { show(); } catch (Exception e) { System.out.print("In main catch bolck"); e.printStackTrace(); } } public static void show() throws Exception { try { throw new NullPointerException(); } catch (NullPointerException e) { System.out.println("I got null value"); throw new Exception(e); } } }
[ "omashish100@gmail.com" ]
omashish100@gmail.com
4d79ef1d7e9010e91943f1f9b822628bb54b3239
e99c56f9b5b0852a5afc7a8e3220e7b7cd05c223
/demo/src/main/java/com/sellnews/demo/ResponseMap.java
c4664cad28fa235a7307c0a4c2d6aed8390a8ee4
[ "Apache-2.0" ]
permissive
Rahulkukadiya/DemoOfDropwizard
89f587f9ded4b9cc4b2b35532f24dabb74bbb34d
7892a8b4c2c33bf4f113b3d4042409e3221939a7
refs/heads/master
2021-01-15T13:37:14.494539
2016-09-20T12:21:20
2016-09-20T12:21:20
68,704,679
1
0
null
null
null
null
UTF-8
Java
false
false
331
java
package com.sellnews.demo; import java.util.HashMap; import java.util.Map; public class ResponseMap { static Map<String, String> hashMap = new HashMap<String, String>(); public static Map<String, String> generatMap(String message) { hashMap.clear(); hashMap.put("message", message); return hashMap; } }
[ "noreply@github.com" ]
noreply@github.com
1f26551aeec080542235e09b5cad8f13adea2774
7db6fa9a281114c6f2d283430d328499847b13f5
/src/model/Caminhao.java
31fc6d99f530fcf23949ec343375dffd7854eb87
[]
no_license
jolubanco/locadora-de-veiculos-JDBC
9240f0b9995b204a964392ce0b42838124e7586f
c4129e207531777b501f641b2b481c7045b04569
refs/heads/main
2023-04-12T23:01:15.398736
2021-04-26T01:44:16
2021-04-26T01:44:16
350,445,550
0
0
null
null
null
null
UTF-8
Java
false
false
178
java
package model; public class Caminhao extends Veiculo { public Caminhao(String marca, String placa, double valorVeiculo){ super(marca,placa, valorVeiculo); } }
[ "jolubanco@gmail.com" ]
jolubanco@gmail.com
0ed8eada92dda6856b512ae5b489b7281a5467c5
9644428ecc81a537a24ed1689d4c57b80e792d01
/src/GUI/DeleteProduct.java
43f77690f74a04372dcb061d668f2c35780c09bb
[]
no_license
AymanAyyad/Final-Project
30ea85de78ffad8f27971969246f63c05ad3ed3c
990d5f094ad76d8ec4bf8cb2bcff892b9a9eb121
refs/heads/master
2021-08-31T04:29:39.221659
2017-12-20T10:53:08
2017-12-20T10:53:08
114,120,547
0
0
null
null
null
null
UTF-8
Java
false
false
5,795
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package GUI; import Products.Product; import ProductsManager.Manager; import com.mysql.fabric.xmlrpc.base.Data; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; /** * * @author Ayman A Ayyad */ public class DeleteProduct extends javax.swing.JPanel { /** * Creates new form DeleteProduct */ DefaultTableModel model = null ; public DeleteProduct() throws Exception { initComponents(); fillTable(); } public void fillTable() throws Exception{ JTable aJTable = this.jTable1; model = (DefaultTableModel) aJTable.getModel(); for (int i = 0; i < model.getRowCount(); i++) { model.removeRow(i); } model = new DefaultTableModel(new Object [][] { }, new String [] { "ID", "Name", "Quantity", "price of carton", "Prodate", "Expdate", "Flavor", "Type" }); aJTable.setModel(model); List <Products.Product> aProduct = DataBase.DBFacade.getProductsDBOperation().getProduct(null); for(Product product :aProduct){ Object[] row = { product.getId(), product.getName(),product.getQuantity(), product.getPriceOfcarton() ,product.getProdate(),product.getExpdate(),product.getFlavor(),(product.equals("Drink"))? "Drink" : "Cake" }; model.addRow(row); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "ID", "Name", "Quantity", "price of carton", "Prodate", "Expdate", "Flavor", "Type" } ) { Class[] types = new Class [] { java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class }; public Class getColumnClass(int columnIndex) { return types [columnIndex]; } }); jScrollPane1.setViewportView(jTable1); jButton1.setText("Delete"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(53, 53, 53) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 661, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(292, 292, 292) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(64, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(22, 22, 22) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(50, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: int row = jTable1.getSelectedRow(); if(row >= 0){ int id = (int) model.getValueAt(row, 0); System.out.println(); try { DataBase.DBFacade.getProductsDBOperation().DeleteProduct(id); fillTable(); } catch (Exception ex) { System.out.println("Delete Error"); Logger.getLogger(UpdateManager.class.getName()).log(Level.SEVERE, null, ex); } }else{ JOptionPane.showMessageDialog(this, "Select the product which want to delete"); } }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; // End of variables declaration//GEN-END:variables }
[ "Ayman A Ayyad@DESKTOP-S2041DH" ]
Ayman A Ayyad@DESKTOP-S2041DH
da7b9b11cf9146ea94ae69b0d3f8eb4423498577
a35fb129173a3d526cbe3db9a17ca12de39146a7
/src/main/java/com/cc/wechat/wxpn/dto/req/BaseMessage.java
778a945100c6fa5038142d78288924d6f4da8084
[]
no_license
zhangchichi/wechat-public-number
fbf99d919e5a6287cb95b70d7e566e9705c88e66
812c05f045c37fed7bf062655320a2d7afae0dcb
refs/heads/master
2023-05-24T12:29:44.982150
2019-05-23T08:44:37
2019-05-23T08:44:37
188,188,632
0
0
null
2023-05-23T20:11:10
2019-05-23T07:59:56
HTML
UTF-8
Java
false
false
509
java
package com.cc.wechat.wxpn.dto.req; import lombok.Data; /** * created by CC on 2019/5/22 * mail 279020185@qq.com */ @Data public class BaseMessage { // 开发者微信号 private String ToUserName; // 发送方帐号(一个 OpenID) private String FromUserName; // 消息创建时间 (整型) private long CreateTime; // 消息类型(text/image/location/link/video/shortvideo) private String MsgType; // 消息 id,64 位整型 private long MsgId; }
[ "chi.zhang@chance-data.com" ]
chi.zhang@chance-data.com
60775e2cea325059ddd44727c47299b191cdfdc1
8803e73957b609e8f4b38026b549611260d5adb0
/src/test/java/com/gmail/imshhui/medium/GasStationTest.java
3a883a20d20b447392dbb78950d0e2baf0bf6746
[ "MIT" ]
permissive
xbest/leetcode
a35ff5bd8552f2e4c6562b02abdb6ee697f61b1f
36bb5455de9ec0e3e3c3f6f81e548fbeca4e23e0
refs/heads/master
2023-05-25T23:00:02.097397
2023-05-10T12:37:47
2023-05-10T12:37:47
141,574,785
0
0
MIT
2020-10-13T06:42:12
2018-07-19T12:14:55
Java
UTF-8
Java
false
false
407
java
package com.gmail.imshhui.medium; import org.junit.Assert; import org.junit.Test; /** * User: liyulin * Date: 2019/9/16 */ public class GasStationTest { GasStation client = new GasStation(); @Test public void gasStationTest() { int[] gas = {3, 3, 4}; int[] cost = {3, 4, 4}; Assert.assertEquals(-1, client.canCompleteCircuit(gas, cost)); } }
[ "imshhui@gmail.com" ]
imshhui@gmail.com
72ee300b6cb320e765614a861d5b80d5560140d3
b97082b4bd7f7d9d9ad8ad01de94b21aeacb9896
/light-framework-utils/src/main/java/org/light4j/framework/util/ReflectionUtil.java
313263ba0fd905a6ca09e830f65fc964bc4515bd
[ "Apache-2.0" ]
permissive
longjiazuo/light-framework
843698139d3d427deb3a38874825a5d644fef5d1
6f30a19b603c1be88d37caa86e9920dfbf5e4f0a
refs/heads/master
2021-01-18T16:45:24.052673
2017-06-04T00:42:01
2017-06-04T00:42:01
60,668,675
2
2
null
null
null
null
UTF-8
Java
false
false
1,371
java
package org.light4j.framework.util; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 反射工具类 * * @author longjiazuo * */ public final class ReflectionUtil { private static final Logger LOGGER = LoggerFactory .getLogger(ReflectionUtil.class); /** * 创建实例 * * @param cls * @return */ public static Object newInstance(Class<?> cls) { Object instance; try { instance = cls.newInstance(); } catch (Exception e) { LOGGER.error("new instance failure", e); throw new RuntimeException(); } return instance; } /** * 调用方法 * * @param obj * @param method * @param args * @return */ public static Object invokeMethod(Object obj, Method method, Object args) { Object result; method.setAccessible(true); try { result = method.invoke(obj, args); } catch (Exception e) { LOGGER.error("invoke method failure", e); throw new RuntimeException(); } return result; } /** * 设置成员变量的值 * * @param obj * @param field * @param value */ public static void setField(Object obj, Field field, Object value) { try { field.setAccessible(true); field.set(obj, value); } catch (Exception e) { LOGGER.error("set field failure", e); throw new RuntimeException(); } } }
[ "812198178@qq.com" ]
812198178@qq.com
b6caf209dbaa8d5cb7d410752bc52cf39294dbe1
2cab630bff8d7dea77324d6209792c35d0313ac0
/01_java-basic/src/day10/Test02.java
e10442f211f095bc4b4feef51d0d12bb81ceb8fe
[]
no_license
diesel88/bitLecture
dc3819412d8d95dc43398d320e073aa87d6c74b6
936f4a48d1f9a2a97f4c4771385fbcc1dde36a7a
refs/heads/master
2021-01-25T08:07:54.652967
2017-07-04T12:12:21
2017-07-04T12:12:21
93,721,734
0
0
null
null
null
null
UTF-8
Java
false
false
475
java
package day10; class Food { } class Cake extends Food { } class Fruit extends Food { } public class Test02 { public static void main(String[] args) { Cake c = new Cake(); Fruit f = new Fruit(); // Fruit f2 = c; // 상속 관계가 없음... Food food = c; // Fruit f2 = food; //명시적 형변환 관계 // Fruit f2 = (Fruit)food; // 실행시 오류발생 food = new Fruit(); Fruit f2 = (Fruit)food; } }
[ "Bit503-15@Bit503-15-PC" ]
Bit503-15@Bit503-15-PC
88fc5c19c8fcfbaf7fbb025d87e27b48e7250604
37772581b46743499a354d6ae6d4fc19599c665b
/src/main/java/acp/db/service/VarManagerEdit.java
bea1df6a76266a7b9db098a1b9e30b80f6ed0722
[]
no_license
sbshab1969/mss09_02
286412d0f2b2220c78f50e1a48104cd5e520aa76
40177fe3e0b0c0a8bac0d340b3c723482af9f73e
refs/heads/master
2022-11-27T03:16:03.701248
2020-08-10T16:02:49
2020-08-10T16:02:49
286,515,133
0
0
null
null
null
null
UTF-8
Java
false
false
7,127
java
package acp.db.service; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.sql.Types; import java.util.Date; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import acp.db.DbConnect; import acp.db.utils.*; import acp.forms.dto.VarDto; import acp.utils.*; public class VarManagerEdit { private Connection dbConn; private static Logger logger = LoggerFactory.getLogger(VarManagerEdit.class); public VarManagerEdit() { dbConn = DbConnect.getConnection(); } public VarDto select(Long objId) { // ------------------------------------------------------ StringBuilder sbQuery = new StringBuilder(); sbQuery.append("select mssv_id, mssv_name, mssv_type, mssv_valuen, mssv_valuev, mssv_valued"); sbQuery.append(" from mss_vars"); sbQuery.append(" where mssv_id=?"); String strQuery = sbQuery.toString(); // ------------------------------------------------------ VarDto varObj = null; try { PreparedStatement ps = dbConn.prepareStatement(strQuery); ps.setLong(1, objId); ResultSet rsq = ps.executeQuery(); if (rsq.next()) { String rsqName = rsq.getString("mssv_name"); String rsqType = rsq.getString("mssv_type"); String strValn = rsq.getString("mssv_valuen"); Double rsqValn = null; if (strValn != null) { rsqValn = Double.valueOf(strValn); } String rsqValv = rsq.getString("mssv_valuev"); Date rsqVald = rsq.getTimestamp("mssv_valued"); // --------------------- varObj = new VarDto(); varObj.setId(objId); varObj.setName(rsqName); varObj.setType(rsqType); varObj.setValuen(rsqValn); varObj.setValuev(rsqValv); varObj.setValued(rsqVald); // --------------------- } rsq.close(); ps.close(); } catch (SQLException e) { DialogUtils.errorPrint(e,logger); varObj = null; } // ------------------------------------------------------ return varObj; } public Long insert(VarDto newObj) { // ------------------------------------------------------ Long objId = DbUtils.getValueL("select mssv_seq.nextval from dual"); // ------------------------------------------------------ StringBuilder sbQuery = new StringBuilder(); sbQuery.append("insert into mss_vars"); sbQuery.append(" (mssv_id, mssv_name, mssv_type, mssv_len,"); sbQuery.append(" mssv_valuen, mssv_valuev, mssv_valued, mssv_last_modify, mssv_owner)"); sbQuery.append(" values (?, upper(?), ?, 120, ?, ?, ?, sysdate, user)"); String strQuery = sbQuery.toString(); // ------------------------------------------------------ try { PreparedStatement ps = dbConn.prepareStatement(strQuery); ps.setLong(1, objId); ps.setString(2, newObj.getName()); ps.setString(3, newObj.getType()); Double valn = newObj.getValuen(); if (valn != null) { ps.setDouble(4, valn); } else { ps.setNull(4, Types.DOUBLE); } ps.setString(5, newObj.getValuev()); Timestamp tsValued = StrSqlUtils.util2ts(newObj.getValued()); ps.setTimestamp(6,tsValued); // -------------------------- ps.executeUpdate(); // -------------------------- ps.close(); } catch (SQLException e) { DialogUtils.errorPrint(e,logger); objId = null; } // ------------------------------------------------------ return objId; } public boolean update(VarDto newObj) { boolean res = false; // ----------------------------------------- StringBuilder sbQuery = new StringBuilder(); sbQuery.append("update mss_vars"); sbQuery.append(" set mssv_name=upper(?)"); sbQuery.append(" ,mssv_type=?"); sbQuery.append(" ,mssv_valuen=?"); sbQuery.append(" ,mssv_valuev=?"); sbQuery.append(" ,mssv_valued=?"); sbQuery.append(" ,mssv_last_modify=sysdate"); sbQuery.append(" ,mssv_owner=user"); sbQuery.append(" where mssv_id=?"); String strQuery = sbQuery.toString(); // ----------------------------------------- try { PreparedStatement ps = dbConn.prepareStatement(strQuery); ps.setString(1, newObj.getName()); ps.setString(2, newObj.getType()); Double valn = newObj.getValuen(); if (valn != null) { ps.setDouble(3, valn); } else { ps.setNull(3, Types.DOUBLE); } ps.setString(4, newObj.getValuev()); Timestamp tsValued = StrSqlUtils.util2ts(newObj.getValued()); ps.setTimestamp(5,tsValued); ps.setLong(6, newObj.getId()); // -------------------------- ps.executeUpdate(); // -------------------------- ps.close(); res = true; } catch (SQLException e) { DialogUtils.errorPrint(e,logger); res = false; } // ----------------------------------------- return res; } public boolean delete(Long objId) { boolean res = false; // ----------------------------------------------------- StringBuilder sbQuery = new StringBuilder(); sbQuery.append("delete from mss_vars where mssv_id=?"); String strQuery = sbQuery.toString(); // ----------------------------------------------------- try { PreparedStatement ps = dbConn.prepareStatement(strQuery); ps.setLong(1, objId); // -------------------------- ps.executeUpdate(); // -------------------------- ps.close(); res = true; } catch (SQLException e) { DialogUtils.errorPrint(e,logger); res = false; } // ----------------------------------------------------- return res; } public void fillVars(Map<String, String> varMap) { // ------------------------------------------------------ StringBuilder sbQuery = new StringBuilder(); sbQuery.append("select t.* from mss_vars t"); sbQuery.append(" where upper(mssv_name) like 'CERT%'"); sbQuery.append(" or upper(mssv_name) = 'VERSION_MSS' order by mssv_name"); String strQuery = sbQuery.toString(); // ------------------------------------------------------ try { Statement st = dbConn.createStatement(); ResultSet rsq = st.executeQuery(strQuery); while (rsq.next()) { String rsqName = rsq.getString("mssv_name"); String valuev = null; Date valued = null; if (rsqName.startsWith("CERT")) { valuev = rsq.getString("mssv_valuev"); varMap.put(rsqName, valuev); } else if (rsqName.equals("VERSION_MSS")) { valuev = rsq.getString("mssv_valuev"); valued = rsq.getDate("mssv_valued"); varMap.put("VERSION", valuev); varMap.put("VERSION_DATE", StrUtils.date2Str(valued)); } } rsq.close(); st.close(); } catch (SQLException e) { DialogUtils.errorPrint(e, logger); } // --------------------------------------------- } }
[ "sbshab1969@gmail.com" ]
sbshab1969@gmail.com
b524205af4a9d74834aa16f75efb1ea967db8ab4
0af8b92686a58eb0b64e319b22411432aca7a8f3
/single-large-project/src/test/java/org/gradle/test/performancenull_367/Testnull_36687.java
85973822d75b518acebd3a4f1c90348dea701ad7
[]
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
308
java
package org.gradle.test.performancenull_367; import static org.junit.Assert.*; public class Testnull_36687 { private final Productionnull_36687 production = new Productionnull_36687("value"); @org.junit.Test public void test() { assertEquals(production.getProperty(), "value"); } }
[ "cedric.champeau@gmail.com" ]
cedric.champeau@gmail.com
550efa311835debaa151849d9a0cc749a0390526
1dbfd89c71b689887405c6fbfe97d9b2ab038a9c
/src/core/Pointer.java
9aab3071102bc9e16f645aca32222fa1e06bec4b
[]
no_license
skuhl/RobotRun
4a97fc84ec92f9db99f03ad52f5ceba5f37bb7b0
988e14dabfd345c41b69aa8095fcf6af0670b339
refs/heads/master
2020-12-28T17:17:08.538169
2018-05-10T15:33:48
2018-05-10T15:33:48
57,896,597
4
2
null
2017-07-31T18:07:45
2016-05-02T14:38:40
Java
UTF-8
Java
false
false
330
java
package core; /** * A pointer to an object reference. * * @author Joshua Hooker * @param <T> The type of object referenced by this pointer */ public class Pointer<T> { private T val; public Pointer(T val) { this.val = val; } public T get() { return val; } public void set(T newVal) { val = newVal; } }
[ "jbhooker@mtu.edu" ]
jbhooker@mtu.edu
857d503605347311a353be81b70f319a4f5de1d4
7bbea063b44d212f82eff499d8291aaaca85daa1
/XmlOrigToSql/src/ws/daley/genealogy/db/record/SubmitterRecord.java
b169095c40db70f55db78323684b84e794c107b4
[]
no_license
AixNPanes/genealogy
d6bfc02c67d04341ea6faed501ffd9474cc4e408
111e89209852a8d48b3b6002bc0bbf2c2b7289cb
refs/heads/master
2022-05-26T20:00:31.342782
2021-07-20T21:27:41
2021-07-20T21:27:41
62,721,459
0
0
null
2022-05-20T20:49:27
2016-07-06T13:04:08
Java
UTF-8
Java
false
false
7,649
java
package ws.daley.genealogy.db.record; import java.util.ArrayList; import java.util.List; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import ws.daley.genealogy.db.Gedcom55; import ws.daley.genealogy.db.structure.AddressStructure; import ws.daley.genealogy.db.structure.MultimediaLinkStructure; import ws.daley.genealogy.util.Util; /** * * @author Tim.Daley * * SUBMITTER_RECORD:= n @<XREF:SUBM>@ SUBM {1:1} +1 NAME <SUBMITTER_NAME> {1:1} +1 <<ADDRESS_STRUCTURE>> {0:1} +1 <<MULTIMEDIA_LINK>> {0:M} +1 LANG <LANGUAGE_PREFERENCE> {0:3} +1 RFN <SUBMITTER_REGISTERED_RFN> {0:1} +1 RIN <AUTOMATED_RECORD_ID> {0:1} +1 <<CHANGE_DATE>> {0:1} */ /** * * @author Tim.Daley * * SUBMITTER_RECORD:= n @<XREF:SUBM>@ SUBM {1:1} +1 NAME <SUBMITTER_NAME> {1:1} +1 <<ADDRESS_STRUCTURE>> {0:1} +1 <<MULTIMEDIA_LINK>> {0:M} +1 LANG <LANGUAGE_PREFERENCE> {0:3} +1 RFN <SUBMITTER_REGISTERED_RFN> {0:1} +1 RIN <AUTOMATED_RECORD_ID> {0:1} +1 <<CHANGE_DATE>> {0:1} */ public class SubmitterRecord extends GedRecord { private static final long serialVersionUID = 1L; private Gedcom55 gedcom55; public Gedcom55 getGedcom55() {return this.gedcom55;} public void setGedcom55(Gedcom55 gedcom55) {this.gedcom55 = gedcom55;} private String submitterName; public String getSubmitterName() {return this.submitterName;} public void setSubmitterName(String submitterName) {this.submitterName = submitterName;} private String submitterRegisteredRFN; public String getSubmitterRegisteredRFN() {return this.submitterRegisteredRFN;} public void setSubmitterRegisteredRFN(String submitterRegisteredRFN) {this.submitterRegisteredRFN = submitterRegisteredRFN;} private String automatedRecordId; public String getAutomatedRecordId() {return this.automatedRecordId;} public void setAutomatedRecordId(String automatedRecordIdStructure) {this.automatedRecordId = automatedRecordIdStructure;} private String changeDate; public String getChangeDate() {return this.changeDate;} public void setChangeDate(String changeDate) {this.changeDate = changeDate;} private AddressStructure addressStructure; public AddressStructure getAddressStructure() {return this.addressStructure;} public void setAddressStructure(AddressStructure addressStructure) {this.addressStructure = addressStructure;} private String submitterLanguagePreference1; public String getSubmitterLanguagePreference1() {return this.submitterLanguagePreference1;} public void setSubmitterLanguagePreference1(String languagePreference1) {this.submitterLanguagePreference1 = languagePreference1;} private String submitterLanguagePreference2; public String getSubmitterLanguagePreference2() {return this.submitterLanguagePreference2;} public void setSubmitterLanguagePreference2(String languagePreference2) {this.submitterLanguagePreference2 = languagePreference2;} private String submitterLanguagePreference3; public String getSubmitterLanguagePreference3() {return this.submitterLanguagePreference3;} public void setSubmitterLanguagePreference3(String languagePreference3) {this.submitterLanguagePreference3 = languagePreference3;} public List<String> getSubmitterLanguagePreferences() { List<String> submitterLanguagePreferences = new ArrayList<String>(); if (this.submitterLanguagePreference1 != null) submitterLanguagePreferences.add(this.submitterLanguagePreference1); if (this.submitterLanguagePreference2 != null) submitterLanguagePreferences.add(this.submitterLanguagePreference2); if (this.submitterLanguagePreference3 != null) submitterLanguagePreferences.add(this.submitterLanguagePreference3); return submitterLanguagePreferences; } public void setSubmitterLanguagePreferences(List<String> submitterLanguagePreferences) { switch(submitterLanguagePreferences.size()) { case 3: this.submitterLanguagePreference3 = submitterLanguagePreferences.get(2); case 2: this.submitterLanguagePreference3 = submitterLanguagePreferences.get(1); case 1: this.submitterLanguagePreference3 = submitterLanguagePreferences.get(0); case 0: break; default: throw new RuntimeException("too many elements in SubmitterLanguagePreferences"); } } public void addSubmitterLanguagePreference(String submitterLanguagePreference) { if (this.submitterLanguagePreference1 == null) this.submitterLanguagePreference1 = submitterLanguagePreference; else if (this.submitterLanguagePreference2 == null) this.submitterLanguagePreference2 = submitterLanguagePreference; else if (this.submitterLanguagePreference3 == null) this.submitterLanguagePreference3 = submitterLanguagePreference; } private List<MultimediaLinkStructure> multimediaLinkStructures = new ArrayList<MultimediaLinkStructure>(); public List<MultimediaLinkStructure> getMultimediaLinkStructures() {return this.multimediaLinkStructures;} public void setMultimediaLinkStructures(List<MultimediaLinkStructure> multimediaLinkStructures) {this.multimediaLinkStructures = multimediaLinkStructures;} public void addMultimediaLinkStructure(MultimediaLinkStructure multimediaLinkStructure) {this.multimediaLinkStructures.add(multimediaLinkStructure);} public SubmitterRecord() {} public SubmitterRecord(Gedcom55 parent, Node node) { super(node); this.gedcom55 = parent; NodeList nodeList = node.getChildNodes(); for(int i = 0; i < nodeList.getLength(); i ++) { Node childNode = nodeList.item(i); if ("NAME".equals(childNode.getNodeName())) this.setSubmitterName(Util.getNodeValue(childNode)); else if ("ADDR".equals(childNode.getNodeName())) this.setAddressStructure(new AddressStructure(childNode)); else if ("PHON".equals(childNode.getNodeName())) this.getAddressStructure().addPhoneNumberStructure(Util.getNodeValue(childNode)); else if ("EMAIL".equals(childNode.getNodeName())) this.getAddressStructure().addAddressEmailStructure(Util.getNodeValue(childNode)); else if ("FAX".equals(childNode.getNodeName())) this.getAddressStructure().addAddressFaxStructure(Util.getNodeValue(childNode)); else if ("WWW".equals(childNode.getNodeName())) this.getAddressStructure().addAddressWWWStructure(Util.getNodeValue(childNode)); else if ("OBJE".equals(childNode.getNodeName())) this.addMultimediaLinkStructure(new MultimediaLinkStructure(childNode)); else if ("LANG".equals(childNode.getNodeName())) this.addSubmitterLanguagePreference(Util.getNodeValue(childNode)); else if ("RFN".equals(childNode.getNodeName())) this.setSubmitterRegisteredRFN(Util.getNodeValue(childNode)); else if ("RIN".equals(childNode.getNodeName())) this.setAutomatedRecordId(Util.getNodeValue(childNode)); else if ("CHAN".equals(childNode.getNodeName())) this.setChangeDate(Util.getNodeValueWithChild(this.getClass(), childNode)); else if ("#text".equals(childNode.getNodeName())) ; else throw new RuntimeException(childNode.getNodeName()+" not processed in "+this.getClass().getSimpleName()); } } }
[ "tim.daley@cru.org" ]
tim.daley@cru.org
f8f1c11467078f164b1534ae7597089844562b52
397a1ef6430a2b11dfad58d1549df187f9599813
/app/src/main/java/vdsMain/message/STXMessage.java
2bba23395aed4200e0acbf000cbee39b3d27ca90
[ "MIT" ]
permissive
gtoken001/Gtoken
0e35a24b574bb7ab75f654edb5341066730056eb
f1f9db7cd606c67440e45aa1ead5c60a251463e9
refs/heads/master
2022-11-18T11:06:45.505901
2020-07-14T15:46:05
2020-07-14T15:46:05
279,625,709
1
2
null
null
null
null
UTF-8
Java
false
false
1,465
java
package vdsMain.message; import androidx.annotation.NonNull; import generic.io.StreamWriter; import generic.serialized.SeriableData; import vdsMain.block.CMerkleTxBlock; import vdsMain.wallet.Wallet; import java.io.IOException; import java.util.List; import java.util.Vector; //bmi public class STXMessage extends VMessage { /* renamed from: a */ public int f11918a; /* renamed from: b */ public int f11919b; /* renamed from: h */ public List<CMerkleTxBlock> f11920h; public STXMessage(@NonNull Wallet izVar) { super(izVar, "stx"); } /* access modifiers changed from: protected */ /* renamed from: a */ public void onEncodeSerialData(StreamWriter streamWriter) throws IOException { streamWriter.writeUInt32T((long) this.f11918a); streamWriter.writeUInt32T((long) this.f11919b); writeObjectList(this.f11920h); } public void onDecodeSerialData() throws IOException { super.onDecodeSerialData(); this.f11918a = (int) readUInt32(); this.f11919b = (int) readUInt32(); int b = readVariableInt().getIntValue(); if (b < 1) { this.f11920h = null; return; } this.f11920h = new Vector(b); for (int i = 0; i < b; i++) { CMerkleTxBlock bjc = new CMerkleTxBlock(this.wallet); bjc.decodeSerialStream((SeriableData) this); this.f11920h.add(bjc); } } }
[ "13939094104@qq.com" ]
13939094104@qq.com
92a114867a85f14fb84afc29e337ea4a32794742
8ffbef5e553ef16a4e46524f16d6aa7aaaad5039
/src/main/java/be/wouterversyck/marcusapi/notes/persistence/NotesDao.java
5423b3614f2e7e8cdb7e8ffe73899360de231f07
[]
no_license
wouterversyck/marcus-api
fa4107b32aab68710595de2b2fa45ca30b543c3c
a33eabc7c31427e2d96dcdce42082c56ec992dc1
refs/heads/master
2022-11-27T11:45:45.037915
2020-08-09T10:37:12
2020-08-09T10:37:12
195,634,727
0
0
null
null
null
null
UTF-8
Java
false
false
582
java
package be.wouterversyck.marcusapi.notes.persistence; import be.wouterversyck.marcusapi.notes.models.Note; import org.springframework.data.mongodb.repository.MongoRepository; import java.util.List; import java.util.Optional; public interface NotesDao extends MongoRepository<Note, Long> { List<Note> findAllByOwner(long userId); List<Note> findAllByContributors(long contributorId); void deleteAllByOwner(long userId); Optional<Note> findByIdAndContributors(String noteId, long contributorId); void deleteByIdAndContributors(String id, long contributorId); }
[ "wouter.versyck@gmail.com" ]
wouter.versyck@gmail.com
93dc3826af5259d223a636da819882adb00baa12
ccafefc207f0e460a0185006fa9d9d3f44298559
/src/main/java/com/nadee/async/ExceptionHandlingAsyncTaskExecutor.java
6a5bb79b985c22523915eff905410cf867da6fb5
[]
no_license
BulkSecurityGeneratorProject/myelast
f1b3afa668346b7a6b7ab3f2c4d2e3c4f2d626dc
26be32b6024d5d599f3709a37fe7703ddd25878e
refs/heads/master
2022-12-16T06:47:04.798179
2016-12-16T15:54:20
2016-12-16T15:54:20
296,507,727
0
0
null
2020-09-18T03:52:21
2020-09-18T03:52:20
null
UTF-8
Java
false
false
2,284
java
package com.nadee.async; import java.util.concurrent.Callable; import java.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.core.task.AsyncTaskExecutor; public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor, InitializingBean, DisposableBean { private final Logger log = LoggerFactory.getLogger(ExceptionHandlingAsyncTaskExecutor.class); private final AsyncTaskExecutor executor; public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) { this.executor = executor; } @Override public void execute(Runnable task) { executor.execute(createWrappedRunnable(task)); } @Override public void execute(Runnable task, long startTimeout) { executor.execute(createWrappedRunnable(task), startTimeout); } private <T> Callable<T> createCallable(final Callable<T> task) { return () -> { try { return task.call(); } catch (Exception e) { handle(e); throw e; } }; } private Runnable createWrappedRunnable(final Runnable task) { return () -> { try { task.run(); } catch (Exception e) { handle(e); } }; } protected void handle(Exception e) { log.error("Caught async exception", e); } @Override public Future<?> submit(Runnable task) { return executor.submit(createWrappedRunnable(task)); } @Override public <T> Future<T> submit(Callable<T> task) { return executor.submit(createCallable(task)); } @Override public void destroy() throws Exception { if (executor instanceof DisposableBean) { DisposableBean bean = (DisposableBean) executor; bean.destroy(); } } @Override public void afterPropertiesSet() throws Exception { if (executor instanceof InitializingBean) { InitializingBean bean = (InitializingBean) executor; bean.afterPropertiesSet(); } } }
[ "arkhomk@yahoo.com" ]
arkhomk@yahoo.com
b06c2719b4ed16645ac6d66e6545756c8bd3e658
804c2f6d033c8e3320bf289fe08eaba8a8a16ef6
/src/main/java/com/tegar/implement/CartServiceImpl.java
0b6acd54966fbd9b12d354c66b2e9ec0fd9464e7
[]
no_license
tegarjokam/online_book_store
0b2816b4542f07d6e6998775cfa1e5f7265b6f25
23222688898b404838eba07b6bb40f0aa5787b2a
refs/heads/master
2021-04-17T11:56:14.754875
2020-04-30T13:16:43
2020-04-30T13:16:43
249,443,585
0
0
null
null
null
null
UTF-8
Java
false
false
4,786
java
package com.tegar.implement; import java.util.HashSet; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.client.HttpServerErrorException; import com.tegar.entity.Book; import com.tegar.entity.Cart; import com.tegar.entity.CartDetail; import com.tegar.entity.CartDetail.CartDetailStatus; import com.tegar.entity.Persistence.Status; import com.tegar.entity.User; import com.tegar.model.CartModel; import com.tegar.model.CartRequestModel; import com.tegar.repository.BookRepository; import com.tegar.repository.CartDetailRepository; import com.tegar.repository.CartRepository; import com.tegar.repository.UserRepository; import com.tegar.service.CartService; import static com.tegar.util.CartModelMapper.constructModel;; @Service public class CartServiceImpl implements CartService { @Autowired private CartRepository cartRepository; @Autowired private CartDetailRepository cartDetailRepository; @Autowired private BookRepository bookRepository; @Autowired private UserRepository userRepository; @Override public CartModel saveOrUpdate(CartModel entity) { // TODO Auto-generated method stub return null; } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public CartModel saveOrUpdate(CartRequestModel entity) { User user = userRepository.findById(entity.getUserId()).orElse(null); //check for user if (user == null) throw new HttpServerErrorException(HttpStatus.BAD_REQUEST, "User with id : " + entity.getUserId() + " not found."); Cart cart = cartRepository.findByUserId(entity.getUserId()); Set<CartDetail> cartDetails = new HashSet<CartDetail>(); //create if (cart == null) { cart = new Cart(); cart.setUser(user); cart = cartRepository.save(cart); //validate book Book book = bookRepository.findById(entity.getBookId()).orElse(null); if (book == null) throw new HttpServerErrorException(HttpStatus.BAD_REQUEST, "Book with id : " + entity.getBookId() + " not found."); CartDetail cartDetail = new CartDetail(); cartDetail.setBook(book); cartDetail.setCart(cart); cartDetail.setCartDetailStatus(CartDetailStatus.CARTED); cartDetail = cartDetailRepository.save(cartDetail); cartDetails.add(cartDetail); } else { //update Book book = bookRepository.findById(entity.getBookId()).orElse(null); if (book == null) throw new HttpServerErrorException(HttpStatus.BAD_REQUEST, "Book with id : " + entity.getBookId() + " not found."); List<CartDetail> currentCartDetails = cartDetailRepository.findByUserIdAndBookIdAndDetailStatus(user.getId(), book.getId(), CartDetailStatus.CARTED); if (currentCartDetails == null || currentCartDetails.size() == 0) { CartDetail cartDetail = new CartDetail(); cartDetail.setBook(book); cartDetail.setCart(cart); cartDetail.setCartDetailStatus(CartDetailStatus.CARTED); cartDetail = cartDetailRepository.save(cartDetail); cartDetails.add(cartDetail); } } cart.setCartDetails(cartDetails); return constructModel(cart); } @Override public CartModel delete(CartModel entity) { // TODO Auto-generated method stub return null; } @Override public CartModel deleteById(Integer id) { // TODO Auto-generated method stub return null; } @Override @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public CartModel findById(Integer id) { return constructModel(cartRepository.findById(id).orElse(null)); } @Override @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public List<CartModel> findAll() { return constructModel(cartRepository.findAll()); } @Override public Long countAll() { // TODO Auto-generated method stub return null; } @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public CartModel deleteByCartDetailId(Integer cartDetailId) { CartDetail cartDetail = cartDetailRepository.findById(cartDetailId).orElse(null); if (cartDetail == null) { throw new HttpServerErrorException(HttpStatus.BAD_REQUEST, "cart with id " + cartDetailId + " not found."); } cartDetail.setStatus(Status.NOT_ACTIVE); cartDetail = cartDetailRepository.save(cartDetail); return constructModel(cartDetail.getCart()); } @Override @Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public CartModel findByUserId(Integer userId) { return constructModel(cartRepository.findByUserId(userId)); } }
[ "dtegarjokam354@gmail.com" ]
dtegarjokam354@gmail.com
a6dadc6f4baa4ce5c67a39511c3bbf1f1ca29962
f1da13a80fce3ce924ab4e4713148e7ed99d11ef
/simulator/src/Workload/SimpleGen.java
cc4fc5cc2956dd0c10891165f4fd9ecfad3089b8
[ "Apache-2.0" ]
permissive
yogeshVU/RM-Simulator
972bff9eee4ef584a0438653a4195cce265198f5
2f850f02307430df5d0be21076c35903d9c013dd
refs/heads/master
2022-02-17T05:07:08.396777
2019-09-20T02:12:04
2019-09-20T02:12:04
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,297
java
package Workload; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Random; import Entity.Job; import Entity.VM; import Manager.Controller; import Settings.Configurations; import java.util.UUID; public class SimpleGen { //poisson distribution private static int getPoissonRandom(double mean) { Random r = new Random(); double L = Math.exp(-mean); int k = 0; double p = 1.0; do { p = p * r.nextDouble(); k++; } while (p > L); return k - 1; } /*A conceptually very simple method for generating exponential variates is based on inverse transform sampling: Given a random variate U drawn from the uniform distribution on the unit interval (0, 1) */ //exponential distribution public static double getNextExp(double lambda) { Random ran = new Random(); return Math.log(1-ran.nextDouble())/(-lambda); } public static void main(String args[]) { //Load Configurations Settings.SettingsLoader.loadSettings(); generateWorkload(); } public static void generateWorkload() { int T_A=0; PrintWriter pw = null; try { pw = new PrintWriter(new File(Configurations.simulatorHome + "/workload_jobs.csv")); } catch (FileNotFoundException e) { e.printStackTrace(); } StringBuilder sb = new StringBuilder(); Random ran = new Random(); sb.append("job-id"); sb.append(','); sb.append("C"); sb.append(','); sb.append("M"); sb.append(','); sb.append("E"); sb.append(','); sb.append("T_A"); sb.append(','); sb.append("T_est"); sb.append(','); sb.append("T_D"); sb.append('\n'); //jobs for (int i = 0; i < Configurations.jobTotal; i++) { sb.append("job-" + i); //job-id sb.append(','); sb.append(1 + ran.nextInt(6));//cores sb.append(','); sb.append(4 + ran.nextInt(9));//memory sb.append(','); sb.append(1 + ran.nextInt(8));//executors sb.append(','); T_A+=getPoissonRandom(Configurations.poissonMean); sb.append(T_A); sb.append(','); int T_est=(int)(10+ getNextExp(Configurations.lambda)); sb.append(T_est); sb.append(','); sb.append(T_A + T_est + ran.nextInt(Configurations.deadlineTolerance));//T_D sb.append('\n'); } pw.write(sb.toString()); pw.close(); } public static void generateJobSimple() { //jobs for(int i = 0; i< Configurations.jobTotal; i++) { Job job = new Job(); job.setC(4); job.setM(4); job.setE(5); //job.setJobID(UUID.randomUUID().toString()); job.setJobID("job-"+i); job.setT_A(i*10); job.setT_est(100); job.setT_D(200+job.getT_A()); job.setT_W(0); Controller.jobList.add(job); } } public static void generateJobRandom() { Random ran = new Random(); //jobs for(int i = 0; i< Configurations.jobTotal; i++) { Job job = new Job(); job.setC(1+ran.nextInt(6)); job.setM(4+ran.nextInt(9)); job.setE(1 + ran.nextInt(8)); //job.setJobID(UUID.randomUUID().toString()); job.setJobID("job-"+i); job.setT_A(1 + ran.nextInt(2000)); job.setT_est(50 + ran.nextInt(250)); job.setT_D(job.getT_A()+job.getT_est()+ran.nextInt(300)); job.setT_W(0); Controller.jobList.add(job); } } public static void generateClusterResources() { //cloud resources for(int i = 0; i< Configurations.cloudVMType1; i++) { VM vm1 = new VM(); vm1.setC_Cap(4); vm1.setC_free(4); vm1.setM_Cap(16); vm1.setM_free(16); vm1.setActive(false); vm1.setMaxT(0); vm1.setLocal(false); vm1.setPrice(Configurations.cloudVMPrice1); //vm1.setVmID(UUID.randomUUID().toString()); vm1.setVmID("C-s-"+i); vm1.setInstanceFlavor("small"); Controller.vmList.add(vm1); } for(int i = 0; i< Configurations.cloudVMType2; i++) { VM vm2 = new VM(); vm2.setC_Cap(8); vm2.setC_free(8); vm2.setM_Cap(32); vm2.setM_free(32); vm2.setActive(false); vm2.setMaxT(0); vm2.setLocal(false); vm2.setPrice(Configurations.cloudVMPrice2); //vm2.setVmID(UUID.randomUUID().toString()); vm2.setVmID("C-m-"+i); vm2.setInstanceFlavor("medium"); Controller.vmList.add(vm2); } for(int i = 0; i< Configurations.cloudVMType3; i++) { VM vm3 = new VM(); vm3.setC_Cap(12); vm3.setC_free(12); vm3.setM_Cap(48); vm3.setM_free(48); vm3.setActive(false); vm3.setMaxT(0); vm3.setLocal(false); vm3.setPrice(Configurations.cloudVMPrice3); //vm3.setVmID(UUID.randomUUID().toString()); vm3.setVmID("C-l-"+i); vm3.setInstanceFlavor("large"); Controller.vmList.add(vm3); } //local resources for(int i = 0; i< Configurations.localVMType1; i++) { VM vm1 = new VM(); vm1.setC_Cap(4); vm1.setC_free(4); vm1.setM_Cap(16); vm1.setM_free(16); vm1.setActive(false); vm1.setMaxT(0); vm1.setLocal(true); vm1.setPrice(Configurations.localVMPrice1); //vm1.setVmID(UUID.randomUUID().toString()); vm1.setVmID("L-s-"+i); vm1.setInstanceFlavor("small"); Controller.vmList.add(vm1); } for(int i = 0; i< Configurations.localVMType2; i++) { VM vm2 = new VM(); vm2.setC_Cap(8); vm2.setC_free(8); vm2.setM_Cap(32); vm2.setM_free(32); vm2.setActive(false); vm2.setMaxT(0); vm2.setLocal(true); vm2.setPrice(Configurations.localVMPrice2); //vm2.setVmID(UUID.randomUUID().toString()); vm2.setVmID("L-m-"+i); vm2.setInstanceFlavor("medium"); Controller.vmList.add(vm2); } for(int i = 0; i< Configurations.localVMType3; i++) { VM vm3 = new VM(); vm3.setC_Cap(12); vm3.setC_free(12); vm3.setM_Cap(48); vm3.setM_free(48); vm3.setActive(false); vm3.setMaxT(0); vm3.setLocal(true); vm3.setPrice(Configurations.localVMPrice3); //vm3.setVmID(UUID.randomUUID().toString()); vm3.setVmID("L-l-"+i); vm3.setInstanceFlavor("large"); Controller.vmList.add(vm3); } } }
[ "muhammedi@student.unimelb.edu.au" ]
muhammedi@student.unimelb.edu.au
411fa1cd1c900861c95c0d83e54fb10451776660
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/2/2_dd0ec10f9956b0760d51ecb95989bc5a6effa871/Program/2_dd0ec10f9956b0760d51ecb95989bc5a6effa871_Program_t.java
14deb328bf5c5c7fb8f6f224eac43b83a92a0dfb
[]
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
5,119
java
/* * Copyright 2012 Joseph Spencer * * 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.xforj.productions; import com.xforj.*; /** * * @author Joseph Spencer */ public class Program extends Production { Output programNamespaceOutput; Output importOutput; Output variableOutput; Output globalStatementsOutput; /** * Program is the entry point for all productions in the grammar. When importing * another file, Program is nested within other programs. * @param output * @param currentVariableOutput * @param previousContext May be null; */ public Program( Output output, VariableOutput currentVariableOutput, ProductionContext context, boolean isNested ){ super(output); programNamespaceOutput=new Output(); importOutput=new Output(); variableOutput=currentVariableOutput; globalStatementsOutput=new Output(); JSParameters globalParams = context.getParams(); JSParametersWrapper globalParamNames = context.getJSParametersWrapper(); output. prepend( "(function(").prepend(globalParamNames).prepend("){"). prepend(programNamespaceOutput). prepend(importOutput). prepend("(function(").prepend(globalParamNames).prepend("){"). prepend(variableOutput). prepend(globalStatementsOutput). prepend("})(").prepend(globalParamNames).prepend(");"); if(isNested){ output.prepend("})(").prepend(globalParamNames).prepend(");"); } else { if(!context.assignTemplatesGlobally){ output.prepend("return "+js_TemplateBasket); } output. prepend("})("). prepend(context.getArgumentsWrapper()). prepend(");"); globalParams.put(js_StringBuffer, //StringBuffer "function(){"+ "var r=[],i=0,t='number string boolean',f="+ "function(s){"+ "var y,v;"+ "try{"+ "v=s();"+ "}catch(e){"+ "v=s;"+ "}"+ "y=typeof(v);"+ "r[i++]=(t.indexOf(y)>-1)?v:''"+ "};"+ "f.s=function(){"+ "return r.join('')"+ "};"+ "return f"+ "}" ).put( js_TemplateBasket, ( context.assignTemplatesGlobally? "(function(){return this})()": "{}" ) ).put(js_SafeValue, "function(v){try{return v()}catch(e){return typeof(v)==='function'?void(0):v}}" ); } } private boolean hasProgramNamespace; private boolean hasGlobalVariableDeclarations; @Override public void execute(CharWrapper characters, ProductionContext context) throws Exception { String exception = "The first Production must be a ProgramNamespace."; if(characters.charAt(0) == '{' && !hasProgramNamespace){ hasProgramNamespace=true; context.addProduction(new ProgramNamespace(programNamespaceOutput)); return; } else if(hasProgramNamespace){ characters.removeSpace(); if(characters.charAt(0) == '{'){ if(characters.charAt(1) == 'i'){ if(!hasGlobalVariableDeclarations){ Output importStatementsOutput = new Output(); importOutput. prepend(importStatementsOutput); context.addProduction(new ImportStatements(importStatementsOutput)); return; } else { throw new Exception("ImportStatements must appear before GlobalVariableStatements."); } } else if(characters.charAt(1) == 'v'){ hasGlobalVariableDeclarations=true; context.addProduction(new GlobalVariableDeclarations(variableOutput)); return; } context.addProduction(new GlobalStatements(globalStatementsOutput)); return; } } throw new Exception(exception); } @Override public void close(ProductionContext context) throws Exception { if(!hasProgramNamespace){ context.handleFileError("No ProgramNamespace was declared in: "); } } }
[ "yuzhongxing88@gmail.com" ]
yuzhongxing88@gmail.com
7abaa57339761a3823a60e91dc7e277bc8416575
50072135f93fc95c9542628b3b1ec83794cb0b1e
/WebViewInAndroid/app/src/main/java/com/aptron/webviewinandroid/MainActivity.java
185f983edf7b9e238a9e081db02493a8e5666c15
[]
no_license
abhi00/AndroidStudioProjects
c00929113a863ac6fc2f6a92696da9f55bf1b2cf
bcb7f2516c121138735079629a074364731e1b99
refs/heads/master
2020-07-21T17:03:49.363558
2019-09-07T06:52:31
2019-09-07T06:52:31
206,926,609
0
0
null
null
null
null
UTF-8
Java
false
false
2,949
java
package com.aptron.webviewinandroid; import android.content.DialogInterface; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; public class MainActivity extends AppCompatActivity { WebView webView; Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webView = findViewById(R.id.web); toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); webView.loadUrl("http://aptronnoida.in"); WebSettings settings = webView.getSettings(); settings.setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); } @Override public void onBackPressed() { if (webView.canGoBack()) { webView.goBack(); } else { super.onBackPressed(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.mymenu,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.home: Toast.makeText(this, "Click On Home Screen", Toast.LENGTH_SHORT).show(); break; case R.id.set: Toast.makeText(this, "Click on Settings", Toast.LENGTH_SHORT).show(); break; case R.id.noti: Toast.makeText(this, "Click on Notification", Toast.LENGTH_SHORT).show(); break; case R.id.exit: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Exit"); builder.setMessage("App Band Karni Hai Kya?"); builder.setPositiveButton("Ha ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.setNegativeButton("Nahi", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(MainActivity.this, "Click Kyo Kiya Fir ??????", Toast.LENGTH_SHORT).show(); } }); AlertDialog alertDialog =builder.create(); alertDialog.show(); break; } return true; } }
[ "kabhishek026@gmail.com" ]
kabhishek026@gmail.com
7d4a10579b3d3f98f67b6c90bc974bc38ecfbae1
8634633d1a9b58dda142c28b8e67fbc90c351f0b
/build/generated/source/r/debug/com/amazonaws/demo/androidpubsubwebsocket/R.java
b91f06ee762718de4d9908187c317b841bbeca45
[]
no_license
emgm/AndroidPubSubWebSocket
038be2eca3c38b506b7777cce675d2f10a9f0ef0
f49a2de9ad58102061cb005f1fe53bc63d93d00c
refs/heads/master
2020-03-21T23:10:23.588800
2018-06-29T16:12:51
2018-06-29T16:12:51
139,170,771
0
0
null
null
null
null
UTF-8
Java
false
false
1,089
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * aapt tool from the resource data it found. It * should not be modified by hand. */ package com.amazonaws.demo.androidpubsubwebsocket; public final class R { public static final class drawable { public static final int ic_launcher=0x7f010000; } public static final class id { public static final int btnConnect=0x7f020000; public static final int btnDisconnect=0x7f020001; public static final int btnPublish=0x7f020002; public static final int btnSubscribe=0x7f020003; public static final int tvClientId=0x7f020004; public static final int tvLastMessage=0x7f020005; public static final int tvStatus=0x7f020006; public static final int txtMessage=0x7f020007; public static final int txtSubscribe=0x7f020008; public static final int txtTopic=0x7f020009; } public static final class layout { public static final int activity_main=0x7f030000; } public static final class string { public static final int app_name=0x7f040000; } }
[ "emgonzalezm@ufpso.edu.co" ]
emgonzalezm@ufpso.edu.co
fb0c17a559a1e794f68e1d19cb0e3311cbaab76b
56efe8d2fbac4807676aa203d9a79500d4b20673
/app/src/main/java/com/tanglang/ypt/adapter/TestBaseAdapter.java
2c7b864bb1bfba482d70f346000627ffc3dcb38e
[]
no_license
yigeyidian/ypt
a020d73406f2c86f8b4edc9320f9cdd6139859b2
a6745392c64c44c04ca1564cfeec9e6a15f45ce5
refs/heads/master
2021-01-19T10:25:27.481335
2015-10-09T07:46:44
2015-10-09T07:46:44
43,054,350
0
1
null
null
null
null
UTF-8
Java
false
false
5,479
java
package com.tanglang.ypt.adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.SectionIndexer; import android.widget.TextView; import com.tanglang.ypt.R; import java.util.ArrayList; import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter; public class TestBaseAdapter extends BaseAdapter implements StickyListHeadersAdapter, SectionIndexer { private final Context mContext; private String[] mCountries; private int[] mSectionIndices; private Character[] mSectionLetters; private LayoutInflater mInflater; public TestBaseAdapter(Context context) { mContext = context; mInflater = LayoutInflater.from(context); mCountries = context.getResources().getStringArray(R.array.drugs); mSectionIndices = getSectionIndices(); mSectionLetters = getSectionLetters(); } /*找到每个字母代表的个数*/ private int[] getSectionIndices() { ArrayList<Integer> sectionIndices = new ArrayList<Integer>(); char lastFirstChar = mCountries[0].charAt(0); sectionIndices.add(0); for (int i = 1; i < mCountries.length; i++) { if (mCountries[i].charAt(0) != lastFirstChar) { lastFirstChar = mCountries[i].charAt(0); sectionIndices.add(i); } } int[] sections = new int[sectionIndices.size()]; for (int i = 0; i < sectionIndices.size(); i++) { sections[i] = sectionIndices.get(i); } return sections; } /*每个item所代表的字母*/ private Character[] getSectionLetters() { Character[] letters = new Character[mSectionIndices.length]; for (int i = 0; i < mSectionIndices.length; i++) { letters[i] = mCountries[mSectionIndices[i]].charAt(0); } return letters; } @Override public int getCount() { return mCountries.length; } @Override public Object getItem(int position) { return mCountries[position]; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = mInflater.inflate(R.layout.test_list_item_layout, parent, false); holder.text = (TextView) convertView.findViewById(R.id.text); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } String drug = mCountries[position]; holder.text.setText(drug.substring(1, drug.length())); return convertView; } @Override public View getHeaderView(int position, View convertView, ViewGroup parent) { HeaderViewHolder holder; if (convertView == null) { holder = new HeaderViewHolder(); convertView = mInflater.inflate(R.layout.header, parent, false); holder.text = (TextView) convertView.findViewById(R.id.text1); convertView.setTag(holder); } else { holder = (HeaderViewHolder) convertView.getTag(); } // set header text as first char in name CharSequence headerChar = mCountries[position].subSequence(0, 1); holder.text.setText(headerChar); return convertView; } /** * Remember that these have to be static, postion=1 should always return * the same Id that is. */ @Override public long getHeaderId(int position) { // return the first character of the country as ID because this is what // headers are based upon return mCountries[position].subSequence(0, 1).charAt(0); } @Override public int getPositionForSection(int section) { if (mSectionIndices.length == 0) { return 0; } if (section >= mSectionIndices.length) { section = mSectionIndices.length - 1; } else if (section < 0) { section = 0; } return mSectionIndices[section]; } public int getPositionForIndex(String index) { for (int i = 0; i < mSectionIndices.length; i++) { if (mCountries[mSectionIndices[i]].substring(0, 1).equals(index)) { return mSectionIndices[i]; } } return 0; } @Override public int getSectionForPosition(int position) { for (int i = 0; i < mSectionIndices.length; i++) { if (position < mSectionIndices[i]) { return i - 1; } } return mSectionIndices.length - 1; } @Override public Object[] getSections() { return mSectionLetters; } public void clear() { mCountries = new String[0]; mSectionIndices = new int[0]; mSectionLetters = new Character[0]; notifyDataSetChanged(); } public void restore() { mCountries = mContext.getResources().getStringArray(R.array.drugs); mSectionIndices = getSectionIndices(); mSectionLetters = getSectionLetters(); notifyDataSetChanged(); } class HeaderViewHolder { TextView text; } class ViewHolder { TextView text; } }
[ "976854315@qq.cin" ]
976854315@qq.cin
11f6a2b377baae0ec7d6ea985ee35ae50aafc44d
9a4240c1b7aca469c3bf3ef48b3f162caa26f3be
/hash map/LinkedHashMap.java
530d365f8ab1a1f96c4ffd0fd5c99089641ff7e7
[]
no_license
Aparna0910/Java-dsa
81c7044e6fb778a9fe192c7a33ff86d58eed1ae1
7f8aa1adb3ad987a885432e4f35931318ce5f86f
refs/heads/main
2023-06-09T03:22:36.861756
2021-07-01T17:07:11
2021-07-01T17:07:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,473
java
import java.util.*; class LRUCache{ Set<Integer> cache; int capacity; public LRUCache(int capacity){ this.cache=new LinkedHashSet<Integer>(capacity); this.capacity=capacity; } // false if key is not present // else moves the key to front by removing it and adding it and returns true public boolean get(int key){ if(!cache.contains(key)) return false; cache.remove(key); cache.add(key); return true; } // Refer key x within the LRU Cache public void refer(int key){ if(get(key)==false) put(key); } public void display(){ LinkedList<Integer> list=new LinkedList<>(cache); // The descendingIterator() method of java.util.LinkedList // class is used to return an iterator over the elements // in this LinkedList in reverse sequential order Iterator<Integer> list= new list.descendingIterator(); while(itr.hasNext()) System.out.println(itr.next()+ " "); } public void put(int key){ if (cache.size()==capacity){ int firstKey=cache.iterator().next(); cache.remove(firstKey); } cache.add(key); } public static void main(String args[]){ LRUCache ca=new LRUCache(4); ca.refer(1); ca.refer(2); ca.refer(3); ca.refer(1); ca.refer(4); ca.refer(5); ca.display(); } }
[ "noreply@github.com" ]
noreply@github.com
57eacc3be02c73a798f3fb99657ea469b86a74b0
30ba7d04fcf0bbbb31887f47f05d5523d9365575
/app/src/androidTest/java/zapper/macronesiaorigins/ApplicationTest.java
7e706cd984cd44f11b6a2ba3cc884411e271f498
[]
no_license
vietkay94/MacronesiaOrigins
7a847d17696ca3ed5728015146757b357a8c3db9
e4ae08d3e3691fbdfd10e7ee44eecea7b5e983ed
refs/heads/master
2021-01-10T02:13:46.393726
2015-10-07T06:40:48
2015-10-07T06:40:48
43,799,184
0
0
null
null
null
null
UTF-8
Java
false
false
355
java
package zapper.macronesiaorigins; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
[ "vietkay94@yahoo.com" ]
vietkay94@yahoo.com
41d41a4794a8b1fe6398a11706bc2746bfef1916
0d49f373d6ec46f068e763bee98a0d9f82aa8550
/src/main/java/com/cywinsky/blog/repository/AuthorityRepository.java
fd87f12ffe7230642400674de4f6a23c9357ed76
[]
no_license
BulkSecurityGeneratorProject/weirdolog
3418d63f5f95b704aa751d4e4df120d99db42386
00ea2e9c8d155caee049d5e548ff5e76ff97db11
refs/heads/master
2022-12-15T17:30:26.725580
2017-12-27T14:40:35
2017-12-27T14:40:35
296,648,930
0
0
null
2020-09-18T14:45:41
2020-09-18T14:45:40
null
UTF-8
Java
false
false
292
java
package com.cywinsky.blog.repository; import com.cywinsky.blog.domain.Authority; import org.springframework.data.jpa.repository.JpaRepository; /** * Spring Data JPA repository for the Authority entity. */ public interface AuthorityRepository extends JpaRepository<Authority, String> { }
[ "jhipster-bot@users.noreply.github.com" ]
jhipster-bot@users.noreply.github.com
3ebbea76d5fb82798a0d52bcfec2243103c64e00
8bbb8cccb775d19ca81501c4e1028630a2d220be
/PI-UT-Automation-App/src/com/pi/ut/automation/view/StatusUpdateView.java
c0dfee048d67851eba52d9996a20b30e20d98dce
[ "Apache-2.0" ]
permissive
jithinrb/sap-po-unit-test-app
b3be8233e934743eccd7f3dc02ebf86c9a5345fe
01213acd31435acace40e706ee1011fb80dc9dad
refs/heads/master
2022-05-16T19:31:17.523026
2022-04-03T20:51:30
2022-04-03T20:51:30
162,493,259
2
0
null
null
null
null
UTF-8
Java
false
false
364
java
package com.pi.ut.automation.view; import java.util.Observable; import java.util.Observer; import com.pi.ut.automation.model.UnitTestAuditLogModel; public class StatusUpdateView implements Observer{ @Override public void update(Observable o, Object oText) { if(o instanceof UnitTestAuditLogModel){ System.out.println(oText); } } }
[ "noreply@github.com" ]
noreply@github.com
5fbf5a7493b1216c24f60087fad830bc5533f227
8896cd55fd82cc4d5e3aa7b925180542bba97bb6
/common/src/main/java/com/wyc/common/interceptor/AuthInterceptor.java
377d094098071975e98042c235e902f269d3441d
[]
no_license
wangyuchuan12/wordbank
91e28008ea96ff45146c17d4619abf55973c8810
57a323fc8fd40e3c2e71903e4f4a1857acf76395
refs/heads/master
2020-12-01T16:19:12.251378
2019-12-29T03:32:28
2019-12-29T03:32:28
230,696,286
0
0
null
null
null
null
UTF-8
Java
false
false
1,835
java
package com.wyc.common.interceptor; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import com.wyc.common.annotation.Auth; import com.wyc.common.context.UserContext; import com.wyc.common.util.CommonUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; public class AuthInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { return true; } /** * 处理401. */ private void unauthorized(HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED);// 401 response.getWriter() .write("{\"success\":false,\"code\":401,\"message\":\"没有登录.\"}"); response.getWriter().close(); } /** * 处理403. */ private void forbidden(HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_FORBIDDEN);// 403 response.getWriter() .write("{\"success\":false,\"code\":403,\"message\":\"没有权限.\"}"); response.getWriter().close(); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { UserContext.clear(); } }
[ "954229599@qq.com" ]
954229599@qq.com
57cd2fb07a021d0e6e46422156060c69fffb9f12
d1a6d1e511df6db8d8dd0912526e3875c7e1797d
/genny_JavaWithoutLambdas/applicationModule/src/test/java/applicationModulepackageJava17/Foo679Test.java
d0e7061d4cc182c6da382146df1536d44d113b6b
[]
no_license
NikitaKozlov/generated-project-for-desugaring
0bc1443ab3ddc84cd289331c726761585766aea7
81506b3711004185070ca4bb9a93482b70011d36
refs/heads/master
2020-03-20T00:35:06.996525
2018-06-12T09:30:37
2018-06-12T09:30:37
137,049,317
0
0
null
null
null
null
UTF-8
Java
false
false
482
java
package applicationModulepackageJava17; import org.junit.Test; public class Foo679Test { @Test public void testFoo0() { new Foo679().foo0(); } @Test public void testFoo1() { new Foo679().foo1(); } @Test public void testFoo2() { new Foo679().foo2(); } @Test public void testFoo3() { new Foo679().foo3(); } @Test public void testFoo4() { new Foo679().foo4(); } @Test public void testFoo5() { new Foo679().foo5(); } }
[ "nikita.e.kozlov@gmail.com" ]
nikita.e.kozlov@gmail.com
14291f2dc762fa5e5a8f5cab390f32045860b7f7
747f66bb162d5c7a5d51d2947d8e2e0c11bfae9e
/pattern-proxy/src/main/java/com/ml/proxy/dynamicproxy/IUserService.java
47cf4b00b9ae856ed14e61d718c7896a8e5ee0d3
[]
no_license
ml-dong-fang-yue-chu/pattern-demo
e6bdb5182007bdf715b8c733743ec87c38bce611
7b18898b1ca404af126b383b98b4638ec206e0a9
refs/heads/master
2020-05-15T14:40:58.910091
2019-04-27T14:41:11
2019-04-27T14:41:11
182,345,616
0
0
null
null
null
null
UTF-8
Java
false
false
213
java
package com.ml.proxy.dynamicproxy; /** * @ClassName IUserService * @DESC TODO * @Author ML * @Date 2019/4/18 22:25 * @Version 1.0 */ public interface IUserService { void login(String tel,int state); }
[ "863376328@qq.com" ]
863376328@qq.com
a96220e191377cfdc7becf91d9a3b51d65e27825
4bed862279be12e4959fa4b7df0c6a124d05c71e
/INT-bignum/src/main/java/big/num/operation/CommonOperation.java
690f749ab01cad817febc9d9ed45ea4a3eff53fd
[ "MIT", "BSD-3-Clause", "CC-BY-4.0" ]
permissive
gynvael/zrozumiec-programowanie-cwiczenia
2dcb173b5f05ff652993e44c2031f79200fb0697
12fbe6d21d792e6dd247dea051f03fe54408b095
refs/heads/master
2023-04-07T02:46:54.788551
2023-02-18T11:02:13
2023-02-18T11:02:13
48,878,550
31
22
MIT
2023-09-05T09:44:04
2016-01-01T13:19:14
Python
UTF-8
Java
false
false
495
java
package big.num.operation; import java.util.List; import java.util.stream.IntStream; public class CommonOperation { static void fillWithZeros(List<Integer> reverseCurrentNumber, int numberOfZeros) { IntStream.range(0, numberOfZeros).forEach(i -> reverseCurrentNumber.add(0)); } static int getOperationResult(int operationValue) { return operationValue % 10; } static int getValueToCarry(int operationValue) { return operationValue / 10; } }
[ "kinga.makowiecka02@gmail.com" ]
kinga.makowiecka02@gmail.com
63a45385972ebeadc3aca0df283a7fb6fd47be82
cf29ccb4411a2652e95f1b2496c435a0850f3540
/main/java/marlon/minecraftai/build/block/LogItemFilter.java
00e2e0abb3dfc9b9628bf5251bcdd2688959097a
[]
no_license
marloncalleja/MC-Experiment-AI
0799cbad4f7f75f5d7c010fb3debd4cf63302048
95d5019dac85353b11d176a838fc265ddcb83eab
refs/heads/master
2022-07-21T04:10:44.333081
2022-07-10T10:13:24
2022-07-10T10:13:24
93,537,809
4
1
null
2018-10-01T09:44:24
2017-06-06T16:05:36
Java
UTF-8
Java
false
false
1,987
java
/******************************************************************************* * This file is part of Minebot. * * Minebot is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Minebot is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Minebot. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package marlon.minecraftai.build.block; import marlon.minecraftai.ai.BlockItemFilter; import net.minecraft.item.ItemStack; /** * An item filter that filters for a given {@link WoodType} * * * */ public class LogItemFilter extends BlockItemFilter { private final WoodType logType; public LogItemFilter(WoodType logType) { super(logType.block); this.logType = logType; } @Override public boolean matches(ItemStack itemStack) { return super.matches(itemStack) && (itemStack.getItemDamage() & 3) == logType.lowerBits; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (logType == null ? 0 : logType.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } final LogItemFilter other = (LogItemFilter) obj; if (logType != other.logType) { return false; } return true; } @Override public String getDescription() { return logType.toString().toLowerCase() + " logs"; } }
[ "marlon.calleja1994@gmail.com" ]
marlon.calleja1994@gmail.com
be7cc281c331754b5baf509ef11dd2292e7d2f86
bad58763a9efc3a0910e3bb42713a4cba2182501
/heroes/Pyromancer.java
27abb7a79273fd650a8ed586d9a6ed8fcaa41887
[]
no_license
radupatrascoiu/League-of-OOP
f2ee4e57354941fbe36510eab0f1bb600aba9bb0
5b588a8f2d49024d60d01d1b479393b84e9b7097
refs/heads/master
2022-03-28T01:15:22.748617
2020-01-05T10:59:19
2020-01-05T10:59:19
223,650,508
0
0
null
null
null
null
UTF-8
Java
false
false
2,914
java
package heroes; import angels.Angel; import common.Constants; import common.StrategyConstans; import main.LocationHistory; import map.MapSingleton; import skills.PyromancerSkills.Fireblast; import skills.PyromancerSkills.Ignite; import skills.Skill; import strategies.DefensiveStrategy; import strategies.OffensiveStrategy; import java.io.IOException; public class Pyromancer extends Hero { private Fireblast fireblastAttack; private Ignite igniteAttack; public Pyromancer(final LocationHistory locationHistory) { super(locationHistory); this.hp = Constants.PYROMANCER_HP; this.damageReceived = 0; this.priority = Constants.PYROMANCER_PRIORITY; } /** * @return */ @Override public int getMaxHp() { return Constants.PYROMANCER_HP + Constants.PYROMANCER_HP_INCREASE_PER_LEVEL * super.getLevel(); } /** * @param hero */ @Override public void play(final Hero hero) { if (this.getHp() <= 0 || hero.getHp() <= 0) { return; } this.fireblastAttack = new Fireblast(this); this.igniteAttack = new Ignite(this); hero.accept(this.fireblastAttack); hero.accept(this.igniteAttack); } /** * @return */ @Override public float getLandModifier() { if (MapSingleton.getInstance().getMap()[getLocationHistory().getX()] [getLocationHistory().getY()] == 'V') { return Constants.VOLCANIC_MODIFIER; } return 1f; } /** * */ @Override public void applyStrategy() { // se alege strategia in functie de confitii if (this.hp > this.getMaxHp() / StrategyConstans.PYROMANCER_FORMULA_1 && this.hp < this.getMaxHp() / StrategyConstans.PYROMANCER_FORMULA_2) { this.setStrategy(new OffensiveStrategy()); this.strategy.execute(this, StrategyConstans.PYROMANCER_OFFENSIVE_HP, StrategyConstans.PYROMANCER_OFFENSIVE_COEFFICIENTS); } else if (this.hp < this.getMaxHp() / StrategyConstans.PYROMANCER_FORMULA_1) { this.setStrategy(new DefensiveStrategy()); this.strategy.execute(this, StrategyConstans.PYROMANCER_DEFENSIVE_HP, StrategyConstans.PYROMANCER_DEFENSIVE_COEFFICIENTS); } } /** * @param skill */ @Override public void accept(final Skill skill) { skill.visit(this); } /** * @param angel * @throws IOException */ @Override public void acceptAngel(final Angel angel) throws IOException { angel.visit(this); } /** * @return */ @Override public String toString() { return "Pyromancer " + this.position; } /** * @return */ @Override public String displayRace() { return "P"; } }
[ "patrascoiu.ion.radu@gmail.com" ]
patrascoiu.ion.radu@gmail.com
5e5f3457496e39bcafecf186a2f6a16db0b78f42
a7cdf058026f150dc40986b28df1bc1e1bd5e659
/EJERCICIO8/TableroPropio/tableroj.java
7482579de95d744a3a50f5444c1e6ec8ea8a8e15
[]
no_license
sorozcov/JAVA-POO-2018
9d0cac9150deba0bd5ba767ecc4dc8bd53835e7e
0269ba7c397586bd626444e4b3f446736a9c394e
refs/heads/master
2021-05-21T10:19:59.217556
2020-04-03T06:37:52
2020-04-03T06:37:52
252,652,097
0
0
null
null
null
null
UTF-8
Java
false
false
13,619
java
/*Silvio Orozco Vizquerra Carne 18282 Fecha 090918 Laboratorio 2 Archivo tablero.java*/ /*Importamos el scanner y las librerias necesarias.*/ import java.util.Scanner; import java.util.*; import java.text.*; import java.util.Random; import java.util.ArrayList; /*Clase tablero*/ public class tableroj{ /*Propiedades Una de ellas es el string tablero que muestra el estado del tablero.*/ protected String[][] tablero = new String [17][17]; /*Metodos*/ /*Instancia un nuevo tablero para el juego.*/ public tableroj(){ for (int x=0;x<tablero.length;x++){ for(int y=0;y<tablero[x].length;y++){ if(x==0 || x==16){ /*Bordes*/ tablero[x][y]=("- "); }else if(y==0 || y==16){ /*Bordes*/ tablero[x][y]=("- "); }else if(x==1 || x==15){ /*Tablero general*/ tablero[x][y]=("0 "); }else if(y==1 || y==15){ /*Tablero general*/ tablero[x][y]=("0 "); }else if(x==13 && (y==2 || y==3 || y==4 || y==5 || y==6)){ /*Safe Azul*/ if (y==6){ tablero[x][y]=("AH "); }else{ tablero[x][y]=("S "); } }else if(x==12 && (y==2 || y==3 || y==4 || y==5)){ /*Color Azul*/ tablero[x][2]=("A1 "); tablero[x][3]=("A2 "); tablero[x][4]=("A3 "); tablero[x][5]=("A4 "); }else if(x==3 && (y==10||y==11 || y==12 || y==13 || y==14)){ /*Safe Rojo*/ if (y==10){ tablero[x][y]=("RH "); }else{ tablero[x][y]=("S "); } }else if(x==4 && (y==11 || y==12 || y==13 || y==14)){ /*Color Rojo*/ tablero[x][14]=("R1 "); tablero[x][13]=("R2 "); tablero[x][12]=("R3 "); tablero[x][11]=("R4 "); }else if(y==13 && (x==10||x==11 || x==12 || x==13 || x==14)){ /*Safe Verde*/ if (x==10){ tablero[x][y]=("VH "); }else{ tablero[x][y]=("S "); } }else if(y==12 && (x==11 || x==12 || x==13 || x==14)){ /*Color Verde*/ tablero[14][y]=("V1 "); tablero[13][y]=("V2 "); tablero[12][y]=("V3 "); tablero[11][y]=("V4 "); }else if(y==3 && (x==2 || x==3 || x==4 || x==5 || x==6)){ /*Safe Negro*/ if (x==6){ tablero[x][y]=("NH "); }else{ tablero[x][y]=("S "); } }else if(y==4 && (x==2 || x==3 || x==4 || x==5)){ /*Color Negro*/ tablero[2][y]=("N1 "); tablero[3][y]=("N2 "); tablero[4][y]=("N3 "); tablero[5][y]=("N4 "); }else if(x==8 && y==6){ /*Juego SORRY S*/ tablero[x][y]=("S "); }else if(x==8 && y==7){ /*Juego SORRY O*/ tablero[x][y]=("O "); }else if(x==8 && y==8){ /*Juego SORRY R*/ tablero[x][y]=("R "); }else if(x==8 && y==9){ /*Juego SORRY R*/ tablero[x][y]=("R "); }else if(x==8 && y==10){ /*Juego SORRY S*/ tablero[x][y]=("Y "); }else{ tablero[x][y]=(" "); } } /*Slide 1/8 */ tablero[0][2]="S "; tablero[0][3]="L "; tablero[0][4]="I "; tablero[0][5]="D "; tablero[0][6]="E "; /*Slide 2/8 */ tablero[0][10]="S "; tablero[0][11]="L "; tablero[0][12]="I "; tablero[0][13]="D "; tablero[0][14]="E "; /*Slide 3/8 */ tablero[2][16]="S "; tablero[3][16]="L "; tablero[4][16]="I "; tablero[5][16]="D "; tablero[6][16]="E "; /*Slide 4/8 */ tablero[10][16]="S "; tablero[11][16]="L "; tablero[12][16]="I "; tablero[13][16]="D "; tablero[14][16]="E "; /*Slide 5/8 */ tablero[16][2]="S "; tablero[16][3]="L "; tablero[16][4]="I "; tablero[16][5]="D "; tablero[16][6]="E "; /*Slide 6/8 */ tablero[16][10]="S "; tablero[16][11]="L "; tablero[16][12]="I "; tablero[16][13]="D "; tablero[16][14]="E "; /*Slide 7/8 */ tablero[10][0]="S "; tablero[11][0]="L "; tablero[12][0]="I "; tablero[13][0]="D "; tablero[14][0]="E "; /*Slide 8/8 */ tablero[2][0]="S "; tablero[3][0]="L "; tablero[4][0]="I "; tablero[5][0]="D "; tablero[6][0]="E "; } } /*Retorna el estado del tablero para ser impreso en el driver.*/ public String vertablero(){ String tab="Tablero: \n"; for (int x=0;x<tablero.length;x++){ for(int y=0;y<tablero[x].length;y++){ tab=(tab+tablero[x][y]) ; } tab=(tab+" \n"); } return tab; } /*Sirve para mover un jugador, segun el peon ingresado y los movimientos.*/ public void mover(String peon, int movs){ int corx=0; int cory=0; int mov=movs; /*Primero se encuentra la posicion.*/ for (int x=0;x<tablero.length;x++){ for(int y=0;y<tablero[x].length;y++){ if (tablero[x][y].equals(peon)){ if ((x==2||x==3 ||x==4||x==5 )&&(y==4)){ corx=1; cory=4; }else if((y==11||y==12 ||y==13||y==14 )&&(x==4)){ corx=4; cory=15; }else if ((x==11||x==12 ||x==13||x==14 )&&(y==12)){ corx=15; cory=12; }else if((y==2||y==3 ||y==4||y==5 )&&(x==12)){ corx=12; cory=1; }else{ corx=x; cory=y; } tablero[x][y]="0 "; break; } } } /*Se crea un bool entra para ver si ya dio la vuelta completa.*/ boolean entra=false; while(movs>0){ /*Para moverse hacia la derecha*/ while (movs>0 && corx==1 &&cory!=15){ if(cory+movs>15){ movs=movs+cory-15; cory=15; }else{ corx=corx; if ((peon.equals("N1 ") || peon.equals("N2 ")|| peon.equals("N3 ")|| peon.equals("N4 "))&& (cory+movs>3)&&(cory<3)&&(mov!=4)){ if(peon.equals("N1 ")){ tablero[2][3]=peon; }else if(peon.equals("N2 ")){ tablero[3][3]=peon; }else if(peon.equals("N3 ")){ tablero[4][3]=peon; }else if(peon.equals("N4 ")){ tablero[5][3]=peon; } entra=true; movs=0; }else{ cory=cory+movs; movs=0; } } } /*Para moverse hacia abajo*/ while (movs>0&& corx!=15 &&cory==15){ if(corx+movs>15){ movs=movs+corx-15; corx=15; }else{ cory=cory; if ((peon.equals("R1 ") || peon.equals("R2 ")|| peon.equals("R3 ")|| peon.equals("R4 "))&& (corx+movs>3)&&(corx<3)&&(mov!=4)){ if(peon.equals("R1 ")){ tablero[3][14]=peon; }else if(peon.equals("R2 ")){ tablero[3][13]=peon; }else if(peon.equals("R3 ")){ tablero[3][12]=peon; }else if(peon.equals("R4 ")){ tablero[3][11]=peon; } entra=true; movs=0; }else{ corx=corx+movs; movs=0; } } } /*Para moverse hacia la izquierda*/ while (movs>0 && corx==15 &&cory!=1){ if(cory-movs<1){ movs=movs-cory+1; cory=1; }else{ corx=corx; if ((peon.equals("V1 ") || peon.equals("V2 ")|| peon.equals("V3 ")|| peon.equals("V4 "))&& (cory-movs<13)&&(cory>13)&&(mov!=4)){ if(peon.equals("V1 ")){ tablero[14][13]=peon; }else if(peon.equals("V2 ")){ tablero[13][13]=peon; }else if(peon.equals("V3 ")){ tablero[12][13]=peon; }else if(peon.equals("V4 ")){ tablero[11][13]=peon; } entra=true; movs=0; }else{ cory=cory-movs; movs=0; } } } /*Para moverse hacia arriba.*/ while (movs>0 && corx!=1 &&cory==1){ if(corx-movs<1){ movs=movs-corx+1; corx=1; }else{ cory=cory; if ((peon.equals("A1 ") || peon.equals("A2 ")|| peon.equals("A3 ")|| peon.equals("A4 "))&& (corx-movs<13)&&(corx>13)&&(mov!=4)){ if(peon.equals("A1 ")){ tablero[13][2]=peon; }else if(peon.equals("A2 ")){ tablero[13][3]=peon; }else if(peon.equals("A3 ")){ tablero[13][4]=peon; }else if(peon.equals("A4 ")){ tablero[13][5]=peon; } entra=true; movs=0; }else{ corx=corx-movs; movs=0; } } } } /*Slide*/ if(tablero[1][2]==peon || tablero[1][10]==peon || tablero[2][15]==peon || tablero[10][15]==peon || tablero[15][14]==peon || tablero[15][6]==peon || tablero[14][1]==peon || tablero[6][1]==peon){ slide(peon); } /*Si no entra, se actualiza el tablero.*/ if (entra==false){ String ant=tablero[corx][cory]; if((peon.substring(0,1)).equals(ant.substring(0,1))){ tablero[corx][cory]=peon; moveruno(corx,cory,ant,peon); }else if (ant.equals("0 ")){ tablero[corx][cory]=peon; }else{ enviarc(ant); tablero[corx][cory]=peon; } } } /*Sirve para hacer un slide.*/ public void slide(String peon){ mover(peon,4); System.out.println("SLIDE WOOO"); } /*Sirve para realizar un unico movimiento.*/ public void moveruno(int corx, int cory,String ant, String peon){ mover(peon,1); tablero[corx][cory]=ant; } /*Sirve para enviar un peon a su casa con carta sorry.*/ public void enviarcasa(String peon){ System.out.println(peon.length()); int corx=0; int cory=0; for (int x=0;x<tablero.length;x++){ for(int y=0;y<tablero[x].length;y++){ if (tablero[x][y].equals(peon)){ if ((x==2||x==3 ||x==4||x==5 )&&(y==4)){ corx=1; cory=4; }else if((y==11||y==12 ||y==13||y==14 )&&(x==4)){ corx=4; cory=15; }else if ((x==11||x==12 ||x==13||x==14 )&&(y==12)){ corx=15; cory=12; }else if((y==2||y==3 ||y==4||y==5 )&&(x==12)){ corx=12; cory=1; }else{ corx=x; cory=y; } tablero[x][y]="0 "; break; } } } if(peon.equals("N1 ")){ tablero[2][4]=peon; }else if(peon.equals("N2 ")){ tablero[3][4]=peon; }else if(peon.equals("N3 ")){ tablero[4][4]=peon; }else if(peon.equals("N4 ")){ tablero[5][4]=peon; }else if(peon.equals("R1 ")){ tablero[4][14]=peon; }else if(peon.equals("R2 ")){ tablero[4][13]=peon; }else if(peon.equals("R3 ")){ tablero[4][12]=peon; }else if(peon.equals("R4 ")){ tablero[4][11]=peon; }else if(peon.equals("V1 ")){ tablero[14][12]=peon; }else if(peon.equals("V2 ")){ tablero[13][12]=peon; }else if(peon.equals("V3 ")){ tablero[12][12]=peon; }else if(peon.equals("V4 ")){ tablero[11][12]=peon; }else if(peon.equals("A1 ")){ tablero[12][2]=peon; }else if(peon.equals("A2 ")){ tablero[12][3]=peon; }else if(peon.equals("A3 ")){ tablero[12][4]=peon; }else if(peon.equals("A4 ")){ tablero[12][5]=peon; } } /*Sirve para enviar un peon a su casa si topan en el mismo lugar.*/ public void enviarc(String peon){ if(peon.equals("N1 ")){ tablero[2][4]=peon; }else if(peon.equals("N2 ")){ tablero[3][4]=peon; }else if(peon.equals("N3 ")){ tablero[4][4]=peon; }else if(peon.equals("N4 ")){ tablero[5][4]=peon; }else if(peon.equals("R1 ")){ tablero[4][14]=peon; }else if(peon.equals("R2 ")){ tablero[4][13]=peon; }else if(peon.equals("R3 ")){ tablero[4][12]=peon; }else if(peon.equals("R4 ")){ tablero[4][11]=peon; }else if(peon.equals("V1 ")){ tablero[14][12]=peon; }else if(peon.equals("V2 ")){ tablero[13][12]=peon; }else if(peon.equals("V3 ")){ tablero[12][12]=peon; }else if(peon.equals("V4 ")){ tablero[11][12]=peon; }else if(peon.equals("A1 ")){ tablero[12][2]=peon; }else if(peon.equals("A2 ")){ tablero[12][3]=peon; }else if(peon.equals("A3 ")){ tablero[12][4]=peon; }else if(peon.equals("A4 ")){ tablero[12][5]=peon; } } public boolean verificaradentro(String peon){ boolean ver=false; if(tablero[2][3].equals(peon)){ ver=true; }else if(tablero[3][3].equals(peon)){ ver=true; }else if(tablero[4][3].equals(peon)){ ver=true; }else if(tablero[5][3].equals(peon)){ ver=true; }else if(tablero[3][11].equals(peon)){ ver=true; }else if(tablero[3][12].equals(peon)){ ver=true; }else if(tablero[3][13].equals(peon)){ ver=true; }else if(tablero[3][14].equals(peon)){ ver=true; }else if(tablero[11][13].equals(peon)){ ver=true; }else if(tablero[12][13].equals(peon)){ ver=true; }else if(tablero[13][13].equals(peon)){ ver=true; }else if(tablero[14][13].equals(peon)){ ver=true; }else if(tablero[13][2].equals(peon)){ ver=true; }else if(tablero[13][3].equals(peon)){ ver=true; }else if(tablero[13][4].equals(peon)){ ver=true; }else if(tablero[13][5].equals(peon)){ ver=true; } return ver; } /*Retorna un boolean si alguien ha ganado, cuando esto es verdadero se acaba el juego.*/ public int terminoj(){ int termino; int x=0; if(tablero[2][3].equals("S ")==false &&tablero[3][3].equals("S ")==false&&tablero[4][3].equals("S ")==false&&tablero[5][3].equals("S ")==false){ termino=1; }else if(tablero[13][2].equals("S ")==false &&tablero[13][3].equals("S ")==false&&tablero[13][4].equals("S ")==false&&tablero[13][5].equals("S ")==false){ termino=4; }else if(tablero[3][11].equals("S ")==false &&tablero[3][12].equals("S ")==false&&tablero[3][13].equals("S ")==false&&tablero[3][14].equals("S ")==false){ termino=2; }else if(tablero[11][13].equals("S ")==false && tablero[12][13].equals("S ")==false && tablero[13][13].equals("S ")==false &&tablero[14][13].equals("S ")==false){ termino=3; }else{ termino=0; } return termino; } }
[ "42949349+sorozcov@users.noreply.github.com" ]
42949349+sorozcov@users.noreply.github.com
0dc44d9858ed90103e3df515e4cbad9be990bb32
98873da3d12e83c24579ad40018651099972e963
/app/src/main/java/com/microsoft/util/ImageUploadUtil.java
83b92b5752bd05157b3beefbabf3a33ec198d7f9
[]
no_license
miniPinocchio/MicrosoftClient
ae78ae944c7d9c19bcc2b71347f73d6074db6fbc
787c0cb4bbd37a76d72ae9aa663ad2bcab95b322
refs/heads/master
2020-04-03T08:32:28.003905
2018-12-21T01:30:38
2018-12-21T01:30:38
155,136,668
0
0
null
null
null
null
UTF-8
Java
false
false
160
java
package com.microsoft.util; /** * @author Created by huiliu on 2018/12/2. * @email liu594545591@126.com * @introduce */ public class ImageUploadUtil { }
[ "liu594545591@126.com" ]
liu594545591@126.com
eddd3e40f5b457511e490db17452e06e3e563503
995f73d30450a6dce6bc7145d89344b4ad6e0622
/MATE-20_EMUI_11.0.0/src/main/java/com/android/server/hidata/histream/HwHistreamCHRQoeInfo.java
2ebbb42ee5c08604780867e996d204367bf664cb
[]
no_license
morningblu/HWFramework
0ceb02cbe42585d0169d9b6c4964a41b436039f5
672bb34094b8780806a10ba9b1d21036fd808b8e
refs/heads/master
2023-07-29T05:26:14.603817
2021-09-03T05:23:34
2021-09-03T05:23:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
496
java
package com.android.server.hidata.histream; public class HwHistreamCHRQoeInfo { public int mDlTup = -1; public int mNetDlTup = -1; public int mSceneId = -1; public int mUlTup = -1; public int mVideoQoe = -1; public HwHistreamCHRQoeInfo(int sceneId, int videoQoe, int ulTup, int dlTup, int netDlTup) { this.mSceneId = sceneId; this.mVideoQoe = videoQoe; this.mUlTup = ulTup; this.mDlTup = dlTup; this.mNetDlTup = netDlTup; } }
[ "dstmath@163.com" ]
dstmath@163.com
a067bb62700a4b0187dfd8d09b17ac5801c67601
2d45824443a6f97529cc939102c88e496b33b3f5
/coding-interview/src/main/java/com/shra012/cracking/coding/interview/heap/Heap.java
6133fd93c418f95f523870e88fc45237410c914e
[]
no_license
shra012/Java-Problems
28d1a919b57b137d35a438643afd6749e576781f
f0fb92d70bb7778208bb333b6de26b91e1a71790
refs/heads/master
2022-01-12T20:28:57.447055
2021-12-26T15:32:41
2021-12-26T15:32:41
67,307,230
0
0
null
null
null
null
UTF-8
Java
false
false
5,935
java
package com.shra012.cracking.coding.interview.heap; import java.lang.reflect.Array; /** * Abstract Heap Class which can be extended further to create * maxheap and minheap. * * @param <T> - Generic Type. */ public abstract class Heap<T extends Comparable<T>> { private static final int MAX_SIZE = 10; private final T[] array; private int count = 0; protected Heap(Class<T> clazz) { this(clazz, MAX_SIZE); } @SuppressWarnings("unchecked") protected Heap(Class<T> clazz, int size) { this.array = (T[]) Array.newInstance(clazz, size); } /** * Current Size of the heap. * * @return - int size. */ public int getSize() { return count; } /** * To check if the heap is full. * * @return true when heap is full. */ public boolean isFull() { return count == array.length; } /** * Finds the value at the index * * @param index - index of the element to be returned. * @return - Element at the given index. */ public T get(int index) { return array[index]; } /** * Given a parent index computes its left child index. * * @param parentIndex - parent index. * @return left child index. */ public int getLeftChildIndex(int parentIndex) { if (parentIndex < 0) { return -1; } int leftChildIndex = 2 * parentIndex + 1; if (leftChildIndex >= count) { return -1; } return leftChildIndex; } /** * Given a parent index computes its right child index. * * @param parentIndex - parent index. * @return right child index. */ public int getRightChildIndex(int parentIndex) { if (parentIndex < 0) { return -1; } int rightChildIndex = 2 * parentIndex + 2; if (rightChildIndex >= count) { return -1; } return rightChildIndex; } /** * Given a child index computes its parent index. * * @param childIndex - child index. * @return parent index. */ public int getParentIndex(int childIndex) { if (childIndex <= 0 || childIndex >= count) { return -1; } return (childIndex - 1) / 2; } /** * Swap the elements at the given indices. * * @param first - first index * @param second - second index */ protected void swap(int first, int second) { T temp = array[first]; array[first] = array[second]; array[second] = temp; } /** * shifts the misplaced node from top to its correct position * in the bottom of the heap. * * @param index - misplaced nodes index. */ protected abstract void siftDown(int index); /** * shifts the misplaced node from bottom to its correct position * in the top of the heap. * * @param index - misplaced nodes index. */ protected abstract void siftUp(int index); /** * Gets the root element of the heap. * * @return the priority element * @throws HeapEmptyException - if the heap is empty exception is thrown. */ public T getHighestPriority() throws HeapEmptyException { if (count == 0) { throw new HeapEmptyException("There are no elements in the heap..."); } return array[0]; } /** * inserts the given value in its correct position * inside the binary heap. * * @param value - value to be inserted. * @throws HeapFullException - exception is thrown when the heap is full. */ public void add(T value) throws HeapFullException { if (count >= array.length) { throw new HeapFullException("No more space to add in the heap"); } array[count] = value; count++; siftUp(count - 1); } /** * removes and returns the highest priority element. * * @return the value of the highest priority element * @throws HeapEmptyException exception is thrown when heap is empty. */ public T removeHighestPriority() throws HeapEmptyException { T first = getHighestPriority(); array[0] = array[count - 1]; array[count - 1] = null; count--; siftDown(0); return first; } /** * The string representation of a heap. * * @return a string which draws a heap in a tree structure. */ @Override public String toString() { return this.toString(0, new StringBuilder(), true, new StringBuilder()).toString(); } /** * recursively builds a binary tree representation of a heap. * * @param index - current index. * @param prefix - prefix string builder * @param isTail - indicates if it is tail node. * @param sb - string builder which collects all the node values. * @return - a binary tree representation of the heap. */ @SuppressWarnings("java:S3776") private StringBuilder toString(int index, StringBuilder prefix, boolean isTail, StringBuilder sb) { if (index != -1 && index < count) { int rightIndex = getRightChildIndex(index); int leftIndex = getLeftChildIndex(index); if (rightIndex != -1 && rightIndex < count) { String joining = isTail ? "│ " : " "; toString(rightIndex, new StringBuilder().append(prefix).append(joining), false, sb); } sb.append(prefix).append(isTail ? "└── " : "┌── ").append(array[index]).append("\n"); if (leftIndex != -1 && leftIndex < count) { String joining = isTail ? " " : "│ "; toString(leftIndex, new StringBuilder().append(prefix).append(joining), true, sb); } } return sb; } }
[ "shravan_fisher@yahoo.ca" ]
shravan_fisher@yahoo.ca
583eb1a88d9d0ffbe610bfa7b55c9cc4f2dc7d99
fddab07ad39c57b6aa1ffb9ee1f68a6192b958f6
/ElevatorCaseStudy.java
94c4ca1d45ebf2143be36ea8ce509b7ead5598c7
[]
no_license
smrdhkh/elevatorJava
86f3969a9f3f3946674e9ef736f8368ba197cfc8
6c58ba3b9b1050ad539df4e4c47f562236197aec
refs/heads/master
2021-01-10T03:33:15.425243
2016-03-22T07:51:21
2016-03-22T07:51:21
54,455,475
0
0
null
null
null
null
UTF-8
Java
false
false
860
java
import java.awt.*; import javax.swing.*; public class ElevatorCaseStudy extends JFrame { private ElevatorSimulation model; private ElevatorView view; private ElevatorController controller; public ElevatorCaseStudy() { super( "Elevator Simulation" ); model = new ElevatorSimulation(); view = new ElevatorView(); controller = new ElevatorController( model ); model.setElevatorSimulationListener( view ); getContentPane().add( view, BorderLayout.CENTER ); getContentPane().add( controller, BorderLayout.SOUTH ); } public static void main( String args[] ) { ElevatorCaseStudy simulation = new ElevatorCaseStudy(); simulation.setDefaultCloseOperation( EXIT_ON_CLOSE ); // pack no idea what it is simulation.pack(); simulation.setVisible( true ); } }
[ "samridhikh26@gmail.com" ]
samridhikh26@gmail.com
a8101470031a551004cc3e9772d065183de7dce0
cfe71d800f6585a2f54a1d932c961c1e43e9e08a
/src/main/java/leetcode/easy/P557ReverseWordsInAString.java
6b20fe52930471ed084e8a7ff078bb716f0d5dec
[]
no_license
sharubhat/piij-cci
4eebe6d575a4e09ae2b93b1af41b46223d31836c
4705d0a654596431470b7d0bd9dba7f57eccdb3a
refs/heads/master
2022-06-04T21:48:39.260642
2021-02-21T07:06:29
2021-02-21T07:06:29
70,663,296
1
0
null
2021-02-21T06:24:43
2016-10-12T04:39:18
Java
UTF-8
Java
false
false
600
java
package leetcode.easy; public class P557ReverseWordsInAString { /** * A quick readable solution. Can be solved without using StringBuffers at the cost * of increased code complexity and reduced readability. * @param s input * @return String */ public String reverseWords(String s) { if (s == null || s.isEmpty()) { return s; } String[] words = s.split(" "); StringBuffer sb = new StringBuffer(); for (String word : words) { sb.append(new StringBuffer(word).reverse()).append(" "); } String res = sb.toString(); return res.trim(); } }
[ "sharubhat@gmail.com" ]
sharubhat@gmail.com
abe3185f582c4eafb0f6e8dfe4abc9b993c64a85
33d6261fb8d118a965434deb9f588d601ccfe61e
/SpagoBIJPXMLAEngine/src/it/eng/spagobi/jpivotaddins/engines/jpivot/security/SecurityUtilities.java
c9928233849e406565b402d5302cde182ab17945
[]
no_license
svn2github/SpagoBI-V4x
8980656ec888782ea2ffb5a06ffa60b5c91849ee
b6cb536106644e446de2d974837ff909bfa73b58
refs/heads/master
2020-05-28T02:52:31.002963
2015-01-16T11:17:54
2015-01-16T11:17:54
10,394,712
3
6
null
null
null
null
UTF-8
Java
false
false
6,238
java
/* SpagoBI, the Open Source Business Intelligence suite * Copyright (C) 2012 Engineering Ingegneria Informatica S.p.A. - SpagoBI Competency Center * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0, without the "Incompatible With Secondary Licenses" notice. * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package it.eng.spagobi.jpivotaddins.engines.jpivot.security; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.spec.EncodedKeySpec; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Node; import org.dom4j.io.SAXReader; import sun.misc.BASE64Decoder; public class SecurityUtilities { private transient Logger logger = null; public SecurityUtilities(Logger log) { logger = log; } /** * Get the SpagoBI Public Key for a DSA alghoritm * @return Public Key for SpagoBI (DSA alghoritm) */ public PublicKey getPublicKey() { PublicKey pubKey = null; SAXReader reader = new SAXReader(); Document document = null; try{ document = reader.read(getClass().getResourceAsStream("/security-config.xml")); Node publicKeyNode = document.selectSingleNode( "//SECURITY-CONFIGURATION/KEYS/SPAGOBI_PUBLIC_KEY_DSA"); String namePubKey = publicKeyNode.valueOf("@keyname"); InputStream publicKeyIs = this.getClass().getClassLoader().getResourceAsStream(namePubKey); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = publicKeyIs.read(buffer)) >= 0) baos.write(buffer, 0, len); publicKeyIs.close(); baos.close(); byte[] pubKeyByte = baos.toByteArray(); // get the public key from bytes KeyFactory keyFactory = KeyFactory.getInstance("DSA"); EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(pubKeyByte); pubKey = keyFactory.generatePublic(publicKeySpec); }catch(DocumentException de){ logger.error("Engines"+ this.getClass().getName()+ "getPublicKey:"+ "Error during parsing of the security configuration file", de); } catch (IOException e) { logger.error("Engines"+ this.getClass().getName()+ "getPublicKey:"+ "Error retriving the key file", e); } catch (NoSuchAlgorithmException e) { logger.error("Engines"+ this.getClass().getName()+ "getPublicKey:"+ "DSA Alghoritm not avaiable", e); } catch (InvalidKeySpecException e) { logger.error("Engines"+ this.getClass().getName()+ "getPublicKey:"+ "Invalid Key", e); } return pubKey; } /** * Decode a Base64 String into a byte array * @param encoded String encoded with Base64 algorithm * @return byte array decoded */ public byte[] decodeBase64(String encoded) { byte[] clear = null; try{ BASE64Decoder decoder = new BASE64Decoder(); clear = decoder.decodeBuffer(encoded); return clear; } catch (IOException ioe) { logger.error("Engines"+ this.getClass().getName()+ "getPublicKey:"+ "Error during base64 decoding", ioe); } return clear; } /** * Verify the signature * @param tokenclear Clear data * @param tokensign Signed data * @return */ public boolean verifySignature(byte[] tokenclear, byte[] tokensign, PublicKey publicKeyDSASbi) { try { Signature sign = Signature.getInstance("DSA"); sign.initVerify(publicKeyDSASbi); sign.update(tokenclear); return sign.verify(tokensign); } catch (NoSuchAlgorithmException e) { logger.error("Engines"+ this.getClass().getName()+ "verifySignature:"+ "DSA Algorithm not avaiable", e); return false; } catch (InvalidKeyException e) { logger.error("Engines"+ this.getClass().getName()+ "verifySignature:"+ "Invalid Key", e); return false; } catch (SignatureException e) { logger.error("Engines"+ this.getClass().getName()+ "verifySignature:"+ "Error while verifing the exception", e); return false; } } /** * Authenticate the caller (must be SpagoBI) * @param request HttpRequest * @param response HttpResponse * @return boolean, true if autheticated false otherwise */ public boolean authenticate(String token, String tokenclear, PublicKey publicKey) { if(token==null) { logger.error("Engines"+ this.getClass().getName()+ "authenticate:"+ "Token null"); return false; } if(tokenclear==null) { logger.error("Engines"+ this.getClass().getName()+ "authenticate:"+ "Token clear null"); return false; } byte[] tokenClear = tokenclear.getBytes(); String tokenSign64 = token; byte[] tokenSign = decodeBase64(tokenSign64); if(tokenSign==null) { logger.error("Engines"+ this.getClass().getName()+ "authenticate:"+ "Token null after base 64 decoding"); return false; } // verify the signature boolean sign = verifySignature(tokenClear, tokenSign, publicKey); return sign; } /** * Decodes (using byte64 decoding function) all the value contained into the input map * @param parMap Map containing value to be decoded * @return Map with value decoded */ public Map decodeParameterMap(Map parMap){ Map decMap = new HashMap(); Set keys = parMap.keySet(); Iterator iterKeys = keys.iterator(); while(iterKeys.hasNext()) { String key = (String)iterKeys.next(); Object[] valueEncArr = (Object[])parMap.get(key); String valueEnc = valueEncArr[0].toString(); byte[] valueDecBytes = decodeBase64(valueEnc); String valueDec = new String(valueDecBytes); decMap.put(key, valueDec); } return decMap; } }
[ "zerbetto@99afaf0d-6903-0410-885a-c66a8bbb5f81" ]
zerbetto@99afaf0d-6903-0410-885a-c66a8bbb5f81
8bdf010753adf97ebaf478b8db6a67d303b718c8
f25c6cfca210cfb54c90332e194854267b4f6343
/base/src/main/java/com/ittianyu/relight/widget/native_/WidgetPagerAdapter.java
a80f786f0ed753c982e16111ccb6fe6a7737f4cc
[]
no_license
bingoloves/mvvc_relight
9f8e7c13a438335bd0a5a14295bd609ba435d293
386c0e229d289dbf8a1bb502cc2a21f584117cf4
refs/heads/master
2022-11-11T13:19:20.799084
2020-06-18T07:01:04
2020-06-18T07:01:04
272,913,639
1
0
null
null
null
null
UTF-8
Java
false
false
1,194
java
package com.ittianyu.relight.widget.native_; import android.arch.lifecycle.Lifecycle; import android.content.Context; import android.support.annotation.NonNull; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import com.ittianyu.relight.widget.Widget; public abstract class WidgetPagerAdapter<T extends Widget> extends PagerAdapter { protected Context context; protected Lifecycle lifecycle; public WidgetPagerAdapter(Context context, Lifecycle lifecycle) { this.context = context; this.lifecycle = lifecycle; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { T widget = getItem(position); container.addView(widget.render()); return widget; } protected abstract T getItem(int position); @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView(((T) object).render()); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return ((T) object).render() == view; } }
[ "657952166@qq.com" ]
657952166@qq.com
9d20fea20fac9d9d8201cdf760bc3986e922ad34
a5b9aafdeb3db898a09ed3cf23135cf047dbe6c7
/ieka-sso/src/main/java/com/ieka/sso/controller/PageController.java
7afcfc3c8b9398f9e443a34a77333a9f22dfc1b3
[]
no_license
lunza/IEKA
8717ac108557faa2a1aab0ec961e8d54d3b6d614
790fafd33fcfa41cdbed15bbdaba9d4fefd7e718
refs/heads/master
2021-01-01T06:34:39.981433
2017-07-17T09:07:34
2017-07-17T09:07:34
97,450,839
0
0
null
null
null
null
UTF-8
Java
false
false
539
java
package com.ieka.sso.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * 页面跳转controller * @author fx50j * */ @Controller @RequestMapping("/page") public class PageController { @RequestMapping("/register") public String showRegister(){ return "register"; } @RequestMapping("/login") public String showLogin(String redirect,Model model){ model.addAttribute("redirect",redirect); return "login"; } }
[ "a1299021@163.com" ]
a1299021@163.com
0a8197b68ad25ab4d15d75fc1100348445fa2c5d
0c7e5c400b636b060ddbc6bafe63526cd2b48a19
/src/main/java/com/example/placebo/exceptions/ObjectNotFoundException.java
c400b8e881d846f93cc58cbe1e297617eaa246e4
[]
no_license
mparszewski/placebo-app
981a6013fdb841d973e9cee336ca00c08d2bbeec
d3f6fac4aa2a297dabf69d0b27665815305da8ef
refs/heads/master
2020-03-19T04:13:36.164406
2018-06-10T21:06:45
2018-06-10T21:06:45
135,807,603
0
0
null
null
null
null
UTF-8
Java
false
false
99
java
package com.example.placebo.exceptions; public class ObjectNotFoundException extends Exception {}
[ "33162624+mparszewski@users.noreply.github.com" ]
33162624+mparszewski@users.noreply.github.com
2e8de808181aee4d0183e5076a3f6e8d05c44241
8155b3907cd529e29a1c71f95133b129d09037de
/src/com/caihong/bbs/dao/BbsCategoryDao.java
700cd50aad7541725122556967fd5de41ec321c7
[]
no_license
xrogzu/caihongbbs
4410a4b541a4bac846bf875887958f92cc617903
94682bebbdb15b500f7b30ceb4af5b57d3b62d8a
refs/heads/master
2020-04-06T04:13:52.247974
2017-02-23T06:06:57
2017-02-23T06:06:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
787
java
package com.caihong.bbs.dao; import java.util.List; import com.caihong.bbs.entity.BbsCategory; import com.caihong.common.hibernate3.Updater; public interface BbsCategoryDao { /** * 获得分区列表 * * @param webId * @return */ public List<BbsCategory> getList(Integer siteId); /** * 分区路径 * * @param webId * @param path * @return */ public int countPath(Integer siteId, String path); /** * 通过路径获得栏目分区 * * @param webId * @param path * @return */ public BbsCategory getByPath(Integer siteId, String path); public BbsCategory findById(Integer id); public BbsCategory save(BbsCategory bean); public BbsCategory updateByUpdater(Updater<BbsCategory> updater); public BbsCategory deleteById(Integer id); }
[ "qianfo_713@163.com" ]
qianfo_713@163.com
352b4b9b595171811aabbb75bc66c52b27157e51
1feddcf79108ddb3ef4218587d2f6e41cca1b9e5
/src/srinjoy_dbs/login.java
53296d4304a2c5f5e260719959f719c82fb7dc53
[]
no_license
srinchow/dbs
f2f2f9e87f9747e252af55dbcf5f961f254c7a36
23ec3161ee9c443b829dac32f715b7a2831d31bc
refs/heads/master
2020-05-09T11:19:21.309941
2019-04-13T04:32:46
2019-04-13T04:32:46
181,075,265
0
0
null
null
null
null
UTF-8
Java
false
false
4,077
java
package srinjoy_dbs; import java.awt.BorderLayout; import java.sql.*; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class login extends JFrame { private JPanel contentPane; private JTextField username; private JTextField password; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { login frame = new login(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public login() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); setVisible(true); JLabel lblUsername = new JLabel("username"); lblUsername.setBounds(49, 41, 82, 23); contentPane.add(lblUsername); JLabel lblPassword = new JLabel("password"); lblPassword.setBounds(49, 145, 61, 16); contentPane.add(lblPassword); JRadioButton r1 = new JRadioButton("student"); r1.setBounds(236, 40, 141, 23); contentPane.add(r1); JRadioButton r2 = new JRadioButton("teacher"); r2.setBounds(236, 92, 141, 23); contentPane.add(r2); JLabel reply_show = new JLabel("check"); reply_show.setBounds(83, 239, 226, 16); contentPane.add(reply_show); ButtonGroup bgroup = new ButtonGroup(); bgroup.add(r1); bgroup.add(r2); JButton btnLogin = new JButton("login"); btnLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //submit String reply = ""; try { //connection code String uname = username.getText(); String pass = password.getText(); if(uname.isEmpty() || pass.isEmpty()) { reply = "Please enter both the details"; reply_show.setText(reply); return; } if(r2.isSelected()) { String qry = "select count(*) as cnt from teacher_login where username = ? and password = ?"; PreparedStatement stmt = con.prepareStatement(qry); stmt.setString(1, uname); stmt.setString(2, pass); ResultSet rs = stmt.executeQuery(); int count = rs.getInt(1); if(count == 0) { reply = "wrong password or username"; reply_show.setText(reply); return; } else { dispose(); new teacher_page(uname); return; } } if(r1.isSelected()) { String qry = "select count(*) as cnt from student_login where username = ? and password = ?"; PreparedStatement stmt = con.prepareStatement(qry); stmt.setString(1, uname); stmt.setString(2, pass); ResultSet rs = stmt.executeQuery(); int count = rs.getInt(1); if(count == 0) { reply = "wrong password or username"; reply_show.setText(reply); return; } else { dispose(); new student_page(uname); return; } } if(!r1.isSelected() && !r2.isSelected()) { reply = "Choose one of them"; reply_show.setText(reply); return; } // need to create a table set the value of it before return } catch(Exception err) { reply = "database error"; reply_show.setText(reply); return; } } }); btnLogin.setBounds(236, 179, 117, 29); contentPane.add(btnLogin); username = new JTextField(); username.setBounds(29, 76, 130, 26); contentPane.add(username); username.setColumns(10); password = new JTextField(); password.setBounds(29, 182, 130, 26); contentPane.add(password); password.setColumns(10); } }
[ "arsh.167.agrawal@gmail.com" ]
arsh.167.agrawal@gmail.com
ceb21e91f2f49fe1dee0e534a23d8e0607d687c9
edd3a82bcc581bde4bb46a2e37e06e4f6c65aeec
/Accounts/src/main/java/com/frknuzn/accounts/controller/AccountsControllerAdvice.java
29d7b36e09297c591be65c868893b291a2f44d8b
[]
no_license
faikturan/microservice-infrastructure
62b3728813a0bd2af812c1427cd2ed17fe830ff0
e92284203729b75ecd63832a3adff59ff36836dc
refs/heads/main
2023-07-16T02:05:47.107140
2021-08-20T08:49:11
2021-08-20T08:49:11
398,349,173
1
0
null
2021-08-20T17:11:27
2021-08-20T17:11:26
null
UTF-8
Java
false
false
1,131
java
package com.frknuzn.accounts.controller; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import java.util.List; import java.util.stream.Collectors; @ControllerAdvice @Slf4j public class AccountsControllerAdvice { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<?> handleRequestBody(MethodArgumentNotValidException ex) { List<FieldError> errorList = ex.getBindingResult().getFieldErrors(); String errorMessage = errorList.stream() .map(fieldError -> fieldError.getField() + " - " + fieldError.getDefaultMessage()) .sorted() .collect(Collectors.joining(", ")); log.info("errorMessage : {} ", errorMessage); return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST); } }
[ "frknuzn34@hotmail.com" ]
frknuzn34@hotmail.com
f9a7789969dfa9c8fa046c2d398b0259d89a133f
0207203c7c4790c35bcb7b5c21d3d66757f658d8
/docroot/WEB-INF/src/vn/dtt/duongbien/dao/vrcb/service/persistence/IssueShiftingOrderPersistenceImpl.java
1c39ecd9546285223086510fefaaa65548667681
[]
no_license
longdm10/DuongBoDoanhNghiepApp-portlet
930a0628a34a76dbd9e7e96febcd13206366b954
512b03be6cd6d7e2aa9043ab0a9480de5518ce84
refs/heads/master
2021-01-21T13:44:15.439969
2016-04-28T17:39:15
2016-04-28T17:39:15
54,985,320
0
0
null
null
null
null
UTF-8
Java
false
false
115,454
java
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package vn.dtt.duongbien.dao.vrcb.service.persistence; import com.liferay.portal.kernel.cache.CacheRegistryUtil; import com.liferay.portal.kernel.dao.orm.EntityCacheUtil; import com.liferay.portal.kernel.dao.orm.FinderCacheUtil; import com.liferay.portal.kernel.dao.orm.FinderPath; import com.liferay.portal.kernel.dao.orm.Query; import com.liferay.portal.kernel.dao.orm.QueryPos; import com.liferay.portal.kernel.dao.orm.QueryUtil; import com.liferay.portal.kernel.dao.orm.Session; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.InstanceFactory; import com.liferay.portal.kernel.util.OrderByComparator; import com.liferay.portal.kernel.util.PropsKeys; import com.liferay.portal.kernel.util.PropsUtil; import com.liferay.portal.kernel.util.SetUtil; import com.liferay.portal.kernel.util.StringBundler; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.StringUtil; import com.liferay.portal.kernel.util.UnmodifiableList; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.model.CacheModel; import com.liferay.portal.model.ModelListener; import com.liferay.portal.service.persistence.impl.BasePersistenceImpl; import vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException; import vn.dtt.duongbien.dao.vrcb.model.IssueShiftingOrder; import vn.dtt.duongbien.dao.vrcb.model.impl.IssueShiftingOrderImpl; import vn.dtt.duongbien.dao.vrcb.model.impl.IssueShiftingOrderModelImpl; import java.io.Serializable; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; /** * The persistence implementation for the issue shifting order service. * * <p> * Caching information and settings can be found in <code>portal.properties</code> * </p> * * @author longdm * @see IssueShiftingOrderPersistence * @see IssueShiftingOrderUtil * @generated */ public class IssueShiftingOrderPersistenceImpl extends BasePersistenceImpl<IssueShiftingOrder> implements IssueShiftingOrderPersistence { /* * NOTE FOR DEVELOPERS: * * Never modify or reference this class directly. Always use {@link IssueShiftingOrderUtil} to access the issue shifting order persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class. */ public static final String FINDER_CLASS_NAME_ENTITY = IssueShiftingOrderImpl.class.getName(); public static final String FINDER_CLASS_NAME_LIST_WITH_PAGINATION = FINDER_CLASS_NAME_ENTITY + ".List1"; public static final String FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION = FINDER_CLASS_NAME_ENTITY + ".List2"; public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_ALL = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, IssueShiftingOrderImpl.class, FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findAll", new String[0]); public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, IssueShiftingOrderImpl.class, FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findAll", new String[0]); public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, Long.class, FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countAll", new String[0]); public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, IssueShiftingOrderImpl.class, FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByfindIssueShiftingOrderByDocumentYearAndDocumentYear", new String[] { Long.class.getName(), Integer.class.getName(), Integer.class.getName(), Integer.class.getName(), OrderByComparator.class.getName() }); public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, IssueShiftingOrderImpl.class, FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByfindIssueShiftingOrderByDocumentYearAndDocumentYear", new String[] { Long.class.getName(), Integer.class.getName() }, IssueShiftingOrderModelImpl.DOCUMENTNAME_COLUMN_BITMASK | IssueShiftingOrderModelImpl.DOCUMENTYEAR_COLUMN_BITMASK); public static final FinderPath FINDER_PATH_COUNT_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, Long.class, FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByfindIssueShiftingOrderByDocumentYearAndDocumentYear", new String[] { Long.class.getName(), Integer.class.getName() }); /** * Returns all the issue shifting orders where documentName = &#63; and documentYear = &#63;. * * @param documentName the document name * @param documentYear the document year * @return the matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findByfindIssueShiftingOrderByDocumentYearAndDocumentYear( long documentName, int documentYear) throws SystemException { return findByfindIssueShiftingOrderByDocumentYearAndDocumentYear(documentName, documentYear, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); } /** * Returns a range of all the issue shifting orders where documentName = &#63; and documentYear = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link vn.dtt.duongbien.dao.vrcb.model.impl.IssueShiftingOrderModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param documentName the document name * @param documentYear the document year * @param start the lower bound of the range of issue shifting orders * @param end the upper bound of the range of issue shifting orders (not inclusive) * @return the range of matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findByfindIssueShiftingOrderByDocumentYearAndDocumentYear( long documentName, int documentYear, int start, int end) throws SystemException { return findByfindIssueShiftingOrderByDocumentYearAndDocumentYear(documentName, documentYear, start, end, null); } /** * Returns an ordered range of all the issue shifting orders where documentName = &#63; and documentYear = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link vn.dtt.duongbien.dao.vrcb.model.impl.IssueShiftingOrderModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param documentName the document name * @param documentYear the document year * @param start the lower bound of the range of issue shifting orders * @param end the upper bound of the range of issue shifting orders (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findByfindIssueShiftingOrderByDocumentYearAndDocumentYear( long documentName, int documentYear, int start, int end, OrderByComparator orderByComparator) throws SystemException { boolean pagination = true; FinderPath finderPath = null; Object[] finderArgs = null; if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) && (orderByComparator == null)) { pagination = false; finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR; finderArgs = new Object[] { documentName, documentYear }; } else { finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR; finderArgs = new Object[] { documentName, documentYear, start, end, orderByComparator }; } List<IssueShiftingOrder> list = (List<IssueShiftingOrder>)FinderCacheUtil.getResult(finderPath, finderArgs, this); if ((list != null) && !list.isEmpty()) { for (IssueShiftingOrder issueShiftingOrder : list) { if ((documentName != issueShiftingOrder.getDocumentName()) || (documentYear != issueShiftingOrder.getDocumentYear())) { list = null; break; } } } if (list == null) { StringBundler query = null; if (orderByComparator != null) { query = new StringBundler(4 + (orderByComparator.getOrderByFields().length * 3)); } else { query = new StringBundler(4); } query.append(_SQL_SELECT_ISSUESHIFTINGORDER_WHERE); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR_DOCUMENTNAME_2); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR_DOCUMENTYEAR_2); if (orderByComparator != null) { appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS, orderByComparator); } else if (pagination) { query.append(IssueShiftingOrderModelImpl.ORDER_BY_JPQL); } String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(documentName); qPos.add(documentYear); if (!pagination) { list = (List<IssueShiftingOrder>)QueryUtil.list(q, getDialect(), start, end, false); Collections.sort(list); list = new UnmodifiableList<IssueShiftingOrder>(list); } else { list = (List<IssueShiftingOrder>)QueryUtil.list(q, getDialect(), start, end); } cacheResult(list); FinderCacheUtil.putResult(finderPath, finderArgs, list); } catch (Exception e) { FinderCacheUtil.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return list; } /** * Returns the first issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63;. * * @param documentName the document name * @param documentYear the document year * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder findByfindIssueShiftingOrderByDocumentYearAndDocumentYear_First( long documentName, int documentYear, OrderByComparator orderByComparator) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = fetchByfindIssueShiftingOrderByDocumentYearAndDocumentYear_First(documentName, documentYear, orderByComparator); if (issueShiftingOrder != null) { return issueShiftingOrder; } StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("documentName="); msg.append(documentName); msg.append(", documentYear="); msg.append(documentYear); msg.append(StringPool.CLOSE_CURLY_BRACE); throw new NoSuchIssueShiftingOrderException(msg.toString()); } /** * Returns the first issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63;. * * @param documentName the document name * @param documentYear the document year * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching issue shifting order, or <code>null</code> if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder fetchByfindIssueShiftingOrderByDocumentYearAndDocumentYear_First( long documentName, int documentYear, OrderByComparator orderByComparator) throws SystemException { List<IssueShiftingOrder> list = findByfindIssueShiftingOrderByDocumentYearAndDocumentYear(documentName, documentYear, 0, 1, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; } /** * Returns the last issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63;. * * @param documentName the document name * @param documentYear the document year * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder findByfindIssueShiftingOrderByDocumentYearAndDocumentYear_Last( long documentName, int documentYear, OrderByComparator orderByComparator) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = fetchByfindIssueShiftingOrderByDocumentYearAndDocumentYear_Last(documentName, documentYear, orderByComparator); if (issueShiftingOrder != null) { return issueShiftingOrder; } StringBundler msg = new StringBundler(6); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("documentName="); msg.append(documentName); msg.append(", documentYear="); msg.append(documentYear); msg.append(StringPool.CLOSE_CURLY_BRACE); throw new NoSuchIssueShiftingOrderException(msg.toString()); } /** * Returns the last issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63;. * * @param documentName the document name * @param documentYear the document year * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching issue shifting order, or <code>null</code> if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder fetchByfindIssueShiftingOrderByDocumentYearAndDocumentYear_Last( long documentName, int documentYear, OrderByComparator orderByComparator) throws SystemException { int count = countByfindIssueShiftingOrderByDocumentYearAndDocumentYear(documentName, documentYear); if (count == 0) { return null; } List<IssueShiftingOrder> list = findByfindIssueShiftingOrderByDocumentYearAndDocumentYear(documentName, documentYear, count - 1, count, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; } /** * Returns the issue shifting orders before and after the current issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63;. * * @param id the primary key of the current issue shifting order * @param documentName the document name * @param documentYear the document year * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the previous, current, and next issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a issue shifting order with the primary key could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder[] findByfindIssueShiftingOrderByDocumentYearAndDocumentYear_PrevAndNext( long id, long documentName, int documentYear, OrderByComparator orderByComparator) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = findByPrimaryKey(id); Session session = null; try { session = openSession(); IssueShiftingOrder[] array = new IssueShiftingOrderImpl[3]; array[0] = getByfindIssueShiftingOrderByDocumentYearAndDocumentYear_PrevAndNext(session, issueShiftingOrder, documentName, documentYear, orderByComparator, true); array[1] = issueShiftingOrder; array[2] = getByfindIssueShiftingOrderByDocumentYearAndDocumentYear_PrevAndNext(session, issueShiftingOrder, documentName, documentYear, orderByComparator, false); return array; } catch (Exception e) { throw processException(e); } finally { closeSession(session); } } protected IssueShiftingOrder getByfindIssueShiftingOrderByDocumentYearAndDocumentYear_PrevAndNext( Session session, IssueShiftingOrder issueShiftingOrder, long documentName, int documentYear, OrderByComparator orderByComparator, boolean previous) { StringBundler query = null; if (orderByComparator != null) { query = new StringBundler(6 + (orderByComparator.getOrderByFields().length * 6)); } else { query = new StringBundler(3); } query.append(_SQL_SELECT_ISSUESHIFTINGORDER_WHERE); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR_DOCUMENTNAME_2); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR_DOCUMENTYEAR_2); if (orderByComparator != null) { String[] orderByConditionFields = orderByComparator.getOrderByConditionFields(); if (orderByConditionFields.length > 0) { query.append(WHERE_AND); } for (int i = 0; i < orderByConditionFields.length; i++) { query.append(_ORDER_BY_ENTITY_ALIAS); query.append(orderByConditionFields[i]); if ((i + 1) < orderByConditionFields.length) { if (orderByComparator.isAscending() ^ previous) { query.append(WHERE_GREATER_THAN_HAS_NEXT); } else { query.append(WHERE_LESSER_THAN_HAS_NEXT); } } else { if (orderByComparator.isAscending() ^ previous) { query.append(WHERE_GREATER_THAN); } else { query.append(WHERE_LESSER_THAN); } } } query.append(ORDER_BY_CLAUSE); String[] orderByFields = orderByComparator.getOrderByFields(); for (int i = 0; i < orderByFields.length; i++) { query.append(_ORDER_BY_ENTITY_ALIAS); query.append(orderByFields[i]); if ((i + 1) < orderByFields.length) { if (orderByComparator.isAscending() ^ previous) { query.append(ORDER_BY_ASC_HAS_NEXT); } else { query.append(ORDER_BY_DESC_HAS_NEXT); } } else { if (orderByComparator.isAscending() ^ previous) { query.append(ORDER_BY_ASC); } else { query.append(ORDER_BY_DESC); } } } } else { query.append(IssueShiftingOrderModelImpl.ORDER_BY_JPQL); } String sql = query.toString(); Query q = session.createQuery(sql); q.setFirstResult(0); q.setMaxResults(2); QueryPos qPos = QueryPos.getInstance(q); qPos.add(documentName); qPos.add(documentYear); if (orderByComparator != null) { Object[] values = orderByComparator.getOrderByConditionValues(issueShiftingOrder); for (Object value : values) { qPos.add(value); } } List<IssueShiftingOrder> list = q.list(); if (list.size() == 2) { return list.get(1); } else { return null; } } /** * Removes all the issue shifting orders where documentName = &#63; and documentYear = &#63; from the database. * * @param documentName the document name * @param documentYear the document year * @throws SystemException if a system exception occurred */ @Override public void removeByfindIssueShiftingOrderByDocumentYearAndDocumentYear( long documentName, int documentYear) throws SystemException { for (IssueShiftingOrder issueShiftingOrder : findByfindIssueShiftingOrderByDocumentYearAndDocumentYear( documentName, documentYear, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(issueShiftingOrder); } } /** * Returns the number of issue shifting orders where documentName = &#63; and documentYear = &#63;. * * @param documentName the document name * @param documentYear the document year * @return the number of matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public int countByfindIssueShiftingOrderByDocumentYearAndDocumentYear( long documentName, int documentYear) throws SystemException { FinderPath finderPath = FINDER_PATH_COUNT_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR; Object[] finderArgs = new Object[] { documentName, documentYear }; Long count = (Long)FinderCacheUtil.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(3); query.append(_SQL_COUNT_ISSUESHIFTINGORDER_WHERE); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR_DOCUMENTNAME_2); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR_DOCUMENTYEAR_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(documentName); qPos.add(documentYear); count = (Long)q.uniqueResult(); FinderCacheUtil.putResult(finderPath, finderArgs, count); } catch (Exception e) { FinderCacheUtil.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); } private static final String _FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR_DOCUMENTNAME_2 = "issueShiftingOrder.documentName = ? AND "; private static final String _FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR_DOCUMENTYEAR_2 = "issueShiftingOrder.documentYear = ?"; public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, IssueShiftingOrderImpl.class, FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState", new String[] { Long.class.getName(), Integer.class.getName(), Integer.class.getName(), Integer.class.getName(), Integer.class.getName(), OrderByComparator.class.getName() }); public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, IssueShiftingOrderImpl.class, FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState", new String[] { Long.class.getName(), Integer.class.getName(), Integer.class.getName() }, IssueShiftingOrderModelImpl.DOCUMENTNAME_COLUMN_BITMASK | IssueShiftingOrderModelImpl.DOCUMENTYEAR_COLUMN_BITMASK | IssueShiftingOrderModelImpl.REQUESTSTATE_COLUMN_BITMASK); public static final FinderPath FINDER_PATH_COUNT_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, Long.class, FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState", new String[] { Long.class.getName(), Integer.class.getName(), Integer.class.getName() }); /** * Returns all the issue shifting orders where documentName = &#63; and documentYear = &#63; and requestState = &#63;. * * @param documentName the document name * @param documentYear the document year * @param requestState the request state * @return the matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState( long documentName, int documentYear, int requestState) throws SystemException { return findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState(documentName, documentYear, requestState, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); } /** * Returns a range of all the issue shifting orders where documentName = &#63; and documentYear = &#63; and requestState = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link vn.dtt.duongbien.dao.vrcb.model.impl.IssueShiftingOrderModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param documentName the document name * @param documentYear the document year * @param requestState the request state * @param start the lower bound of the range of issue shifting orders * @param end the upper bound of the range of issue shifting orders (not inclusive) * @return the range of matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState( long documentName, int documentYear, int requestState, int start, int end) throws SystemException { return findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState(documentName, documentYear, requestState, start, end, null); } /** * Returns an ordered range of all the issue shifting orders where documentName = &#63; and documentYear = &#63; and requestState = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link vn.dtt.duongbien.dao.vrcb.model.impl.IssueShiftingOrderModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param documentName the document name * @param documentYear the document year * @param requestState the request state * @param start the lower bound of the range of issue shifting orders * @param end the upper bound of the range of issue shifting orders (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState( long documentName, int documentYear, int requestState, int start, int end, OrderByComparator orderByComparator) throws SystemException { boolean pagination = true; FinderPath finderPath = null; Object[] finderArgs = null; if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) && (orderByComparator == null)) { pagination = false; finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE; finderArgs = new Object[] { documentName, documentYear, requestState }; } else { finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE; finderArgs = new Object[] { documentName, documentYear, requestState, start, end, orderByComparator }; } List<IssueShiftingOrder> list = (List<IssueShiftingOrder>)FinderCacheUtil.getResult(finderPath, finderArgs, this); if ((list != null) && !list.isEmpty()) { for (IssueShiftingOrder issueShiftingOrder : list) { if ((documentName != issueShiftingOrder.getDocumentName()) || (documentYear != issueShiftingOrder.getDocumentYear()) || (requestState != issueShiftingOrder.getRequestState())) { list = null; break; } } } if (list == null) { StringBundler query = null; if (orderByComparator != null) { query = new StringBundler(5 + (orderByComparator.getOrderByFields().length * 3)); } else { query = new StringBundler(5); } query.append(_SQL_SELECT_ISSUESHIFTINGORDER_WHERE); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE_DOCUMENTNAME_2); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE_DOCUMENTYEAR_2); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE_REQUESTSTATE_2); if (orderByComparator != null) { appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS, orderByComparator); } else if (pagination) { query.append(IssueShiftingOrderModelImpl.ORDER_BY_JPQL); } String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(documentName); qPos.add(documentYear); qPos.add(requestState); if (!pagination) { list = (List<IssueShiftingOrder>)QueryUtil.list(q, getDialect(), start, end, false); Collections.sort(list); list = new UnmodifiableList<IssueShiftingOrder>(list); } else { list = (List<IssueShiftingOrder>)QueryUtil.list(q, getDialect(), start, end); } cacheResult(list); FinderCacheUtil.putResult(finderPath, finderArgs, list); } catch (Exception e) { FinderCacheUtil.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return list; } /** * Returns the first issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63; and requestState = &#63;. * * @param documentName the document name * @param documentYear the document year * @param requestState the request state * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState_First( long documentName, int documentYear, int requestState, OrderByComparator orderByComparator) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = fetchByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState_First(documentName, documentYear, requestState, orderByComparator); if (issueShiftingOrder != null) { return issueShiftingOrder; } StringBundler msg = new StringBundler(8); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("documentName="); msg.append(documentName); msg.append(", documentYear="); msg.append(documentYear); msg.append(", requestState="); msg.append(requestState); msg.append(StringPool.CLOSE_CURLY_BRACE); throw new NoSuchIssueShiftingOrderException(msg.toString()); } /** * Returns the first issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63; and requestState = &#63;. * * @param documentName the document name * @param documentYear the document year * @param requestState the request state * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching issue shifting order, or <code>null</code> if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder fetchByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState_First( long documentName, int documentYear, int requestState, OrderByComparator orderByComparator) throws SystemException { List<IssueShiftingOrder> list = findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState(documentName, documentYear, requestState, 0, 1, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; } /** * Returns the last issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63; and requestState = &#63;. * * @param documentName the document name * @param documentYear the document year * @param requestState the request state * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState_Last( long documentName, int documentYear, int requestState, OrderByComparator orderByComparator) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = fetchByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState_Last(documentName, documentYear, requestState, orderByComparator); if (issueShiftingOrder != null) { return issueShiftingOrder; } StringBundler msg = new StringBundler(8); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("documentName="); msg.append(documentName); msg.append(", documentYear="); msg.append(documentYear); msg.append(", requestState="); msg.append(requestState); msg.append(StringPool.CLOSE_CURLY_BRACE); throw new NoSuchIssueShiftingOrderException(msg.toString()); } /** * Returns the last issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63; and requestState = &#63;. * * @param documentName the document name * @param documentYear the document year * @param requestState the request state * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching issue shifting order, or <code>null</code> if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder fetchByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState_Last( long documentName, int documentYear, int requestState, OrderByComparator orderByComparator) throws SystemException { int count = countByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState(documentName, documentYear, requestState); if (count == 0) { return null; } List<IssueShiftingOrder> list = findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState(documentName, documentYear, requestState, count - 1, count, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; } /** * Returns the issue shifting orders before and after the current issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63; and requestState = &#63;. * * @param id the primary key of the current issue shifting order * @param documentName the document name * @param documentYear the document year * @param requestState the request state * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the previous, current, and next issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a issue shifting order with the primary key could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder[] findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState_PrevAndNext( long id, long documentName, int documentYear, int requestState, OrderByComparator orderByComparator) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = findByPrimaryKey(id); Session session = null; try { session = openSession(); IssueShiftingOrder[] array = new IssueShiftingOrderImpl[3]; array[0] = getByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState_PrevAndNext(session, issueShiftingOrder, documentName, documentYear, requestState, orderByComparator, true); array[1] = issueShiftingOrder; array[2] = getByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState_PrevAndNext(session, issueShiftingOrder, documentName, documentYear, requestState, orderByComparator, false); return array; } catch (Exception e) { throw processException(e); } finally { closeSession(session); } } protected IssueShiftingOrder getByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState_PrevAndNext( Session session, IssueShiftingOrder issueShiftingOrder, long documentName, int documentYear, int requestState, OrderByComparator orderByComparator, boolean previous) { StringBundler query = null; if (orderByComparator != null) { query = new StringBundler(6 + (orderByComparator.getOrderByFields().length * 6)); } else { query = new StringBundler(3); } query.append(_SQL_SELECT_ISSUESHIFTINGORDER_WHERE); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE_DOCUMENTNAME_2); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE_DOCUMENTYEAR_2); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE_REQUESTSTATE_2); if (orderByComparator != null) { String[] orderByConditionFields = orderByComparator.getOrderByConditionFields(); if (orderByConditionFields.length > 0) { query.append(WHERE_AND); } for (int i = 0; i < orderByConditionFields.length; i++) { query.append(_ORDER_BY_ENTITY_ALIAS); query.append(orderByConditionFields[i]); if ((i + 1) < orderByConditionFields.length) { if (orderByComparator.isAscending() ^ previous) { query.append(WHERE_GREATER_THAN_HAS_NEXT); } else { query.append(WHERE_LESSER_THAN_HAS_NEXT); } } else { if (orderByComparator.isAscending() ^ previous) { query.append(WHERE_GREATER_THAN); } else { query.append(WHERE_LESSER_THAN); } } } query.append(ORDER_BY_CLAUSE); String[] orderByFields = orderByComparator.getOrderByFields(); for (int i = 0; i < orderByFields.length; i++) { query.append(_ORDER_BY_ENTITY_ALIAS); query.append(orderByFields[i]); if ((i + 1) < orderByFields.length) { if (orderByComparator.isAscending() ^ previous) { query.append(ORDER_BY_ASC_HAS_NEXT); } else { query.append(ORDER_BY_DESC_HAS_NEXT); } } else { if (orderByComparator.isAscending() ^ previous) { query.append(ORDER_BY_ASC); } else { query.append(ORDER_BY_DESC); } } } } else { query.append(IssueShiftingOrderModelImpl.ORDER_BY_JPQL); } String sql = query.toString(); Query q = session.createQuery(sql); q.setFirstResult(0); q.setMaxResults(2); QueryPos qPos = QueryPos.getInstance(q); qPos.add(documentName); qPos.add(documentYear); qPos.add(requestState); if (orderByComparator != null) { Object[] values = orderByComparator.getOrderByConditionValues(issueShiftingOrder); for (Object value : values) { qPos.add(value); } } List<IssueShiftingOrder> list = q.list(); if (list.size() == 2) { return list.get(1); } else { return null; } } /** * Removes all the issue shifting orders where documentName = &#63; and documentYear = &#63; and requestState = &#63; from the database. * * @param documentName the document name * @param documentYear the document year * @param requestState the request state * @throws SystemException if a system exception occurred */ @Override public void removeByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState( long documentName, int documentYear, int requestState) throws SystemException { for (IssueShiftingOrder issueShiftingOrder : findByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState( documentName, documentYear, requestState, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(issueShiftingOrder); } } /** * Returns the number of issue shifting orders where documentName = &#63; and documentYear = &#63; and requestState = &#63;. * * @param documentName the document name * @param documentYear the document year * @param requestState the request state * @return the number of matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public int countByfindIssueShiftingOrderByDocumentYearAndDocumentYearAndRequestState( long documentName, int documentYear, int requestState) throws SystemException { FinderPath finderPath = FINDER_PATH_COUNT_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE; Object[] finderArgs = new Object[] { documentName, documentYear, requestState }; Long count = (Long)FinderCacheUtil.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(4); query.append(_SQL_COUNT_ISSUESHIFTINGORDER_WHERE); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE_DOCUMENTNAME_2); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE_DOCUMENTYEAR_2); query.append(_FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE_REQUESTSTATE_2); String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(documentName); qPos.add(documentYear); qPos.add(requestState); count = (Long)q.uniqueResult(); FinderCacheUtil.putResult(finderPath, finderArgs, count); } catch (Exception e) { FinderCacheUtil.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); } private static final String _FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE_DOCUMENTNAME_2 = "issueShiftingOrder.documentName = ? AND "; private static final String _FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE_DOCUMENTYEAR_2 = "issueShiftingOrder.documentYear = ? AND "; private static final String _FINDER_COLUMN_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE_REQUESTSTATE_2 = "issueShiftingOrder.requestState = ?"; public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_REQUESTCODE = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, IssueShiftingOrderImpl.class, FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByRequestCode", new String[] { String.class.getName(), Integer.class.getName(), Integer.class.getName(), OrderByComparator.class.getName() }); public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_REQUESTCODE = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, IssueShiftingOrderImpl.class, FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByRequestCode", new String[] { String.class.getName() }, IssueShiftingOrderModelImpl.REQUESTCODE_COLUMN_BITMASK); public static final FinderPath FINDER_PATH_COUNT_BY_REQUESTCODE = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, Long.class, FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByRequestCode", new String[] { String.class.getName() }); /** * Returns all the issue shifting orders where requestCode = &#63;. * * @param requestCode the request code * @return the matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findByRequestCode(String requestCode) throws SystemException { return findByRequestCode(requestCode, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); } /** * Returns a range of all the issue shifting orders where requestCode = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link vn.dtt.duongbien.dao.vrcb.model.impl.IssueShiftingOrderModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param requestCode the request code * @param start the lower bound of the range of issue shifting orders * @param end the upper bound of the range of issue shifting orders (not inclusive) * @return the range of matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findByRequestCode(String requestCode, int start, int end) throws SystemException { return findByRequestCode(requestCode, start, end, null); } /** * Returns an ordered range of all the issue shifting orders where requestCode = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link vn.dtt.duongbien.dao.vrcb.model.impl.IssueShiftingOrderModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param requestCode the request code * @param start the lower bound of the range of issue shifting orders * @param end the upper bound of the range of issue shifting orders (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findByRequestCode(String requestCode, int start, int end, OrderByComparator orderByComparator) throws SystemException { boolean pagination = true; FinderPath finderPath = null; Object[] finderArgs = null; if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) && (orderByComparator == null)) { pagination = false; finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_REQUESTCODE; finderArgs = new Object[] { requestCode }; } else { finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_REQUESTCODE; finderArgs = new Object[] { requestCode, start, end, orderByComparator }; } List<IssueShiftingOrder> list = (List<IssueShiftingOrder>)FinderCacheUtil.getResult(finderPath, finderArgs, this); if ((list != null) && !list.isEmpty()) { for (IssueShiftingOrder issueShiftingOrder : list) { if (!Validator.equals(requestCode, issueShiftingOrder.getRequestCode())) { list = null; break; } } } if (list == null) { StringBundler query = null; if (orderByComparator != null) { query = new StringBundler(3 + (orderByComparator.getOrderByFields().length * 3)); } else { query = new StringBundler(3); } query.append(_SQL_SELECT_ISSUESHIFTINGORDER_WHERE); boolean bindRequestCode = false; if (requestCode == null) { query.append(_FINDER_COLUMN_REQUESTCODE_REQUESTCODE_1); } else if (requestCode.equals(StringPool.BLANK)) { query.append(_FINDER_COLUMN_REQUESTCODE_REQUESTCODE_3); } else { bindRequestCode = true; query.append(_FINDER_COLUMN_REQUESTCODE_REQUESTCODE_2); } if (orderByComparator != null) { appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS, orderByComparator); } else if (pagination) { query.append(IssueShiftingOrderModelImpl.ORDER_BY_JPQL); } String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); if (bindRequestCode) { qPos.add(requestCode); } if (!pagination) { list = (List<IssueShiftingOrder>)QueryUtil.list(q, getDialect(), start, end, false); Collections.sort(list); list = new UnmodifiableList<IssueShiftingOrder>(list); } else { list = (List<IssueShiftingOrder>)QueryUtil.list(q, getDialect(), start, end); } cacheResult(list); FinderCacheUtil.putResult(finderPath, finderArgs, list); } catch (Exception e) { FinderCacheUtil.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return list; } /** * Returns the first issue shifting order in the ordered set where requestCode = &#63;. * * @param requestCode the request code * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder findByRequestCode_First(String requestCode, OrderByComparator orderByComparator) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = fetchByRequestCode_First(requestCode, orderByComparator); if (issueShiftingOrder != null) { return issueShiftingOrder; } StringBundler msg = new StringBundler(4); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("requestCode="); msg.append(requestCode); msg.append(StringPool.CLOSE_CURLY_BRACE); throw new NoSuchIssueShiftingOrderException(msg.toString()); } /** * Returns the first issue shifting order in the ordered set where requestCode = &#63;. * * @param requestCode the request code * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching issue shifting order, or <code>null</code> if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder fetchByRequestCode_First(String requestCode, OrderByComparator orderByComparator) throws SystemException { List<IssueShiftingOrder> list = findByRequestCode(requestCode, 0, 1, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; } /** * Returns the last issue shifting order in the ordered set where requestCode = &#63;. * * @param requestCode the request code * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder findByRequestCode_Last(String requestCode, OrderByComparator orderByComparator) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = fetchByRequestCode_Last(requestCode, orderByComparator); if (issueShiftingOrder != null) { return issueShiftingOrder; } StringBundler msg = new StringBundler(4); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("requestCode="); msg.append(requestCode); msg.append(StringPool.CLOSE_CURLY_BRACE); throw new NoSuchIssueShiftingOrderException(msg.toString()); } /** * Returns the last issue shifting order in the ordered set where requestCode = &#63;. * * @param requestCode the request code * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching issue shifting order, or <code>null</code> if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder fetchByRequestCode_Last(String requestCode, OrderByComparator orderByComparator) throws SystemException { int count = countByRequestCode(requestCode); if (count == 0) { return null; } List<IssueShiftingOrder> list = findByRequestCode(requestCode, count - 1, count, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; } /** * Returns the issue shifting orders before and after the current issue shifting order in the ordered set where requestCode = &#63;. * * @param id the primary key of the current issue shifting order * @param requestCode the request code * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the previous, current, and next issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a issue shifting order with the primary key could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder[] findByRequestCode_PrevAndNext(long id, String requestCode, OrderByComparator orderByComparator) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = findByPrimaryKey(id); Session session = null; try { session = openSession(); IssueShiftingOrder[] array = new IssueShiftingOrderImpl[3]; array[0] = getByRequestCode_PrevAndNext(session, issueShiftingOrder, requestCode, orderByComparator, true); array[1] = issueShiftingOrder; array[2] = getByRequestCode_PrevAndNext(session, issueShiftingOrder, requestCode, orderByComparator, false); return array; } catch (Exception e) { throw processException(e); } finally { closeSession(session); } } protected IssueShiftingOrder getByRequestCode_PrevAndNext(Session session, IssueShiftingOrder issueShiftingOrder, String requestCode, OrderByComparator orderByComparator, boolean previous) { StringBundler query = null; if (orderByComparator != null) { query = new StringBundler(6 + (orderByComparator.getOrderByFields().length * 6)); } else { query = new StringBundler(3); } query.append(_SQL_SELECT_ISSUESHIFTINGORDER_WHERE); boolean bindRequestCode = false; if (requestCode == null) { query.append(_FINDER_COLUMN_REQUESTCODE_REQUESTCODE_1); } else if (requestCode.equals(StringPool.BLANK)) { query.append(_FINDER_COLUMN_REQUESTCODE_REQUESTCODE_3); } else { bindRequestCode = true; query.append(_FINDER_COLUMN_REQUESTCODE_REQUESTCODE_2); } if (orderByComparator != null) { String[] orderByConditionFields = orderByComparator.getOrderByConditionFields(); if (orderByConditionFields.length > 0) { query.append(WHERE_AND); } for (int i = 0; i < orderByConditionFields.length; i++) { query.append(_ORDER_BY_ENTITY_ALIAS); query.append(orderByConditionFields[i]); if ((i + 1) < orderByConditionFields.length) { if (orderByComparator.isAscending() ^ previous) { query.append(WHERE_GREATER_THAN_HAS_NEXT); } else { query.append(WHERE_LESSER_THAN_HAS_NEXT); } } else { if (orderByComparator.isAscending() ^ previous) { query.append(WHERE_GREATER_THAN); } else { query.append(WHERE_LESSER_THAN); } } } query.append(ORDER_BY_CLAUSE); String[] orderByFields = orderByComparator.getOrderByFields(); for (int i = 0; i < orderByFields.length; i++) { query.append(_ORDER_BY_ENTITY_ALIAS); query.append(orderByFields[i]); if ((i + 1) < orderByFields.length) { if (orderByComparator.isAscending() ^ previous) { query.append(ORDER_BY_ASC_HAS_NEXT); } else { query.append(ORDER_BY_DESC_HAS_NEXT); } } else { if (orderByComparator.isAscending() ^ previous) { query.append(ORDER_BY_ASC); } else { query.append(ORDER_BY_DESC); } } } } else { query.append(IssueShiftingOrderModelImpl.ORDER_BY_JPQL); } String sql = query.toString(); Query q = session.createQuery(sql); q.setFirstResult(0); q.setMaxResults(2); QueryPos qPos = QueryPos.getInstance(q); if (bindRequestCode) { qPos.add(requestCode); } if (orderByComparator != null) { Object[] values = orderByComparator.getOrderByConditionValues(issueShiftingOrder); for (Object value : values) { qPos.add(value); } } List<IssueShiftingOrder> list = q.list(); if (list.size() == 2) { return list.get(1); } else { return null; } } /** * Removes all the issue shifting orders where requestCode = &#63; from the database. * * @param requestCode the request code * @throws SystemException if a system exception occurred */ @Override public void removeByRequestCode(String requestCode) throws SystemException { for (IssueShiftingOrder issueShiftingOrder : findByRequestCode( requestCode, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(issueShiftingOrder); } } /** * Returns the number of issue shifting orders where requestCode = &#63;. * * @param requestCode the request code * @return the number of matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public int countByRequestCode(String requestCode) throws SystemException { FinderPath finderPath = FINDER_PATH_COUNT_BY_REQUESTCODE; Object[] finderArgs = new Object[] { requestCode }; Long count = (Long)FinderCacheUtil.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(2); query.append(_SQL_COUNT_ISSUESHIFTINGORDER_WHERE); boolean bindRequestCode = false; if (requestCode == null) { query.append(_FINDER_COLUMN_REQUESTCODE_REQUESTCODE_1); } else if (requestCode.equals(StringPool.BLANK)) { query.append(_FINDER_COLUMN_REQUESTCODE_REQUESTCODE_3); } else { bindRequestCode = true; query.append(_FINDER_COLUMN_REQUESTCODE_REQUESTCODE_2); } String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); if (bindRequestCode) { qPos.add(requestCode); } count = (Long)q.uniqueResult(); FinderCacheUtil.putResult(finderPath, finderArgs, count); } catch (Exception e) { FinderCacheUtil.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); } private static final String _FINDER_COLUMN_REQUESTCODE_REQUESTCODE_1 = "issueShiftingOrder.requestCode IS NULL"; private static final String _FINDER_COLUMN_REQUESTCODE_REQUESTCODE_2 = "issueShiftingOrder.requestCode = ?"; private static final String _FINDER_COLUMN_REQUESTCODE_REQUESTCODE_3 = "(issueShiftingOrder.requestCode IS NULL OR issueShiftingOrder.requestCode = '')"; public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, IssueShiftingOrderImpl.class, FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByDocumentNameAndDocumentYearAndVersionNo", new String[] { Long.class.getName(), Integer.class.getName(), String.class.getName(), Integer.class.getName(), Integer.class.getName(), OrderByComparator.class.getName() }); public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, IssueShiftingOrderImpl.class, FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByDocumentNameAndDocumentYearAndVersionNo", new String[] { Long.class.getName(), Integer.class.getName(), String.class.getName() }, IssueShiftingOrderModelImpl.DOCUMENTNAME_COLUMN_BITMASK | IssueShiftingOrderModelImpl.DOCUMENTYEAR_COLUMN_BITMASK | IssueShiftingOrderModelImpl.VERSIONNO_COLUMN_BITMASK); public static final FinderPath FINDER_PATH_COUNT_BY_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO = new FinderPath(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderModelImpl.FINDER_CACHE_ENABLED, Long.class, FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByDocumentNameAndDocumentYearAndVersionNo", new String[] { Long.class.getName(), Integer.class.getName(), String.class.getName() }); /** * Returns all the issue shifting orders where documentName = &#63; and documentYear = &#63; and versionNo = &#63;. * * @param documentName the document name * @param documentYear the document year * @param versionNo the version no * @return the matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findByDocumentNameAndDocumentYearAndVersionNo( long documentName, int documentYear, String versionNo) throws SystemException { return findByDocumentNameAndDocumentYearAndVersionNo(documentName, documentYear, versionNo, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); } /** * Returns a range of all the issue shifting orders where documentName = &#63; and documentYear = &#63; and versionNo = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link vn.dtt.duongbien.dao.vrcb.model.impl.IssueShiftingOrderModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param documentName the document name * @param documentYear the document year * @param versionNo the version no * @param start the lower bound of the range of issue shifting orders * @param end the upper bound of the range of issue shifting orders (not inclusive) * @return the range of matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findByDocumentNameAndDocumentYearAndVersionNo( long documentName, int documentYear, String versionNo, int start, int end) throws SystemException { return findByDocumentNameAndDocumentYearAndVersionNo(documentName, documentYear, versionNo, start, end, null); } /** * Returns an ordered range of all the issue shifting orders where documentName = &#63; and documentYear = &#63; and versionNo = &#63;. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link vn.dtt.duongbien.dao.vrcb.model.impl.IssueShiftingOrderModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param documentName the document name * @param documentYear the document year * @param versionNo the version no * @param start the lower bound of the range of issue shifting orders * @param end the upper bound of the range of issue shifting orders (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findByDocumentNameAndDocumentYearAndVersionNo( long documentName, int documentYear, String versionNo, int start, int end, OrderByComparator orderByComparator) throws SystemException { boolean pagination = true; FinderPath finderPath = null; Object[] finderArgs = null; if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) && (orderByComparator == null)) { pagination = false; finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO; finderArgs = new Object[] { documentName, documentYear, versionNo }; } else { finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO; finderArgs = new Object[] { documentName, documentYear, versionNo, start, end, orderByComparator }; } List<IssueShiftingOrder> list = (List<IssueShiftingOrder>)FinderCacheUtil.getResult(finderPath, finderArgs, this); if ((list != null) && !list.isEmpty()) { for (IssueShiftingOrder issueShiftingOrder : list) { if ((documentName != issueShiftingOrder.getDocumentName()) || (documentYear != issueShiftingOrder.getDocumentYear()) || !Validator.equals(versionNo, issueShiftingOrder.getVersionNo())) { list = null; break; } } } if (list == null) { StringBundler query = null; if (orderByComparator != null) { query = new StringBundler(5 + (orderByComparator.getOrderByFields().length * 3)); } else { query = new StringBundler(5); } query.append(_SQL_SELECT_ISSUESHIFTINGORDER_WHERE); query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_DOCUMENTNAME_2); query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_DOCUMENTYEAR_2); boolean bindVersionNo = false; if (versionNo == null) { query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_VERSIONNO_1); } else if (versionNo.equals(StringPool.BLANK)) { query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_VERSIONNO_3); } else { bindVersionNo = true; query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_VERSIONNO_2); } if (orderByComparator != null) { appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS, orderByComparator); } else if (pagination) { query.append(IssueShiftingOrderModelImpl.ORDER_BY_JPQL); } String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(documentName); qPos.add(documentYear); if (bindVersionNo) { qPos.add(versionNo); } if (!pagination) { list = (List<IssueShiftingOrder>)QueryUtil.list(q, getDialect(), start, end, false); Collections.sort(list); list = new UnmodifiableList<IssueShiftingOrder>(list); } else { list = (List<IssueShiftingOrder>)QueryUtil.list(q, getDialect(), start, end); } cacheResult(list); FinderCacheUtil.putResult(finderPath, finderArgs, list); } catch (Exception e) { FinderCacheUtil.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return list; } /** * Returns the first issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63; and versionNo = &#63;. * * @param documentName the document name * @param documentYear the document year * @param versionNo the version no * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder findByDocumentNameAndDocumentYearAndVersionNo_First( long documentName, int documentYear, String versionNo, OrderByComparator orderByComparator) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = fetchByDocumentNameAndDocumentYearAndVersionNo_First(documentName, documentYear, versionNo, orderByComparator); if (issueShiftingOrder != null) { return issueShiftingOrder; } StringBundler msg = new StringBundler(8); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("documentName="); msg.append(documentName); msg.append(", documentYear="); msg.append(documentYear); msg.append(", versionNo="); msg.append(versionNo); msg.append(StringPool.CLOSE_CURLY_BRACE); throw new NoSuchIssueShiftingOrderException(msg.toString()); } /** * Returns the first issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63; and versionNo = &#63;. * * @param documentName the document name * @param documentYear the document year * @param versionNo the version no * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the first matching issue shifting order, or <code>null</code> if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder fetchByDocumentNameAndDocumentYearAndVersionNo_First( long documentName, int documentYear, String versionNo, OrderByComparator orderByComparator) throws SystemException { List<IssueShiftingOrder> list = findByDocumentNameAndDocumentYearAndVersionNo(documentName, documentYear, versionNo, 0, 1, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; } /** * Returns the last issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63; and versionNo = &#63;. * * @param documentName the document name * @param documentYear the document year * @param versionNo the version no * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder findByDocumentNameAndDocumentYearAndVersionNo_Last( long documentName, int documentYear, String versionNo, OrderByComparator orderByComparator) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = fetchByDocumentNameAndDocumentYearAndVersionNo_Last(documentName, documentYear, versionNo, orderByComparator); if (issueShiftingOrder != null) { return issueShiftingOrder; } StringBundler msg = new StringBundler(8); msg.append(_NO_SUCH_ENTITY_WITH_KEY); msg.append("documentName="); msg.append(documentName); msg.append(", documentYear="); msg.append(documentYear); msg.append(", versionNo="); msg.append(versionNo); msg.append(StringPool.CLOSE_CURLY_BRACE); throw new NoSuchIssueShiftingOrderException(msg.toString()); } /** * Returns the last issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63; and versionNo = &#63;. * * @param documentName the document name * @param documentYear the document year * @param versionNo the version no * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the last matching issue shifting order, or <code>null</code> if a matching issue shifting order could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder fetchByDocumentNameAndDocumentYearAndVersionNo_Last( long documentName, int documentYear, String versionNo, OrderByComparator orderByComparator) throws SystemException { int count = countByDocumentNameAndDocumentYearAndVersionNo(documentName, documentYear, versionNo); if (count == 0) { return null; } List<IssueShiftingOrder> list = findByDocumentNameAndDocumentYearAndVersionNo(documentName, documentYear, versionNo, count - 1, count, orderByComparator); if (!list.isEmpty()) { return list.get(0); } return null; } /** * Returns the issue shifting orders before and after the current issue shifting order in the ordered set where documentName = &#63; and documentYear = &#63; and versionNo = &#63;. * * @param id the primary key of the current issue shifting order * @param documentName the document name * @param documentYear the document year * @param versionNo the version no * @param orderByComparator the comparator to order the set by (optionally <code>null</code>) * @return the previous, current, and next issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a issue shifting order with the primary key could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder[] findByDocumentNameAndDocumentYearAndVersionNo_PrevAndNext( long id, long documentName, int documentYear, String versionNo, OrderByComparator orderByComparator) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = findByPrimaryKey(id); Session session = null; try { session = openSession(); IssueShiftingOrder[] array = new IssueShiftingOrderImpl[3]; array[0] = getByDocumentNameAndDocumentYearAndVersionNo_PrevAndNext(session, issueShiftingOrder, documentName, documentYear, versionNo, orderByComparator, true); array[1] = issueShiftingOrder; array[2] = getByDocumentNameAndDocumentYearAndVersionNo_PrevAndNext(session, issueShiftingOrder, documentName, documentYear, versionNo, orderByComparator, false); return array; } catch (Exception e) { throw processException(e); } finally { closeSession(session); } } protected IssueShiftingOrder getByDocumentNameAndDocumentYearAndVersionNo_PrevAndNext( Session session, IssueShiftingOrder issueShiftingOrder, long documentName, int documentYear, String versionNo, OrderByComparator orderByComparator, boolean previous) { StringBundler query = null; if (orderByComparator != null) { query = new StringBundler(6 + (orderByComparator.getOrderByFields().length * 6)); } else { query = new StringBundler(3); } query.append(_SQL_SELECT_ISSUESHIFTINGORDER_WHERE); query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_DOCUMENTNAME_2); query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_DOCUMENTYEAR_2); boolean bindVersionNo = false; if (versionNo == null) { query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_VERSIONNO_1); } else if (versionNo.equals(StringPool.BLANK)) { query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_VERSIONNO_3); } else { bindVersionNo = true; query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_VERSIONNO_2); } if (orderByComparator != null) { String[] orderByConditionFields = orderByComparator.getOrderByConditionFields(); if (orderByConditionFields.length > 0) { query.append(WHERE_AND); } for (int i = 0; i < orderByConditionFields.length; i++) { query.append(_ORDER_BY_ENTITY_ALIAS); query.append(orderByConditionFields[i]); if ((i + 1) < orderByConditionFields.length) { if (orderByComparator.isAscending() ^ previous) { query.append(WHERE_GREATER_THAN_HAS_NEXT); } else { query.append(WHERE_LESSER_THAN_HAS_NEXT); } } else { if (orderByComparator.isAscending() ^ previous) { query.append(WHERE_GREATER_THAN); } else { query.append(WHERE_LESSER_THAN); } } } query.append(ORDER_BY_CLAUSE); String[] orderByFields = orderByComparator.getOrderByFields(); for (int i = 0; i < orderByFields.length; i++) { query.append(_ORDER_BY_ENTITY_ALIAS); query.append(orderByFields[i]); if ((i + 1) < orderByFields.length) { if (orderByComparator.isAscending() ^ previous) { query.append(ORDER_BY_ASC_HAS_NEXT); } else { query.append(ORDER_BY_DESC_HAS_NEXT); } } else { if (orderByComparator.isAscending() ^ previous) { query.append(ORDER_BY_ASC); } else { query.append(ORDER_BY_DESC); } } } } else { query.append(IssueShiftingOrderModelImpl.ORDER_BY_JPQL); } String sql = query.toString(); Query q = session.createQuery(sql); q.setFirstResult(0); q.setMaxResults(2); QueryPos qPos = QueryPos.getInstance(q); qPos.add(documentName); qPos.add(documentYear); if (bindVersionNo) { qPos.add(versionNo); } if (orderByComparator != null) { Object[] values = orderByComparator.getOrderByConditionValues(issueShiftingOrder); for (Object value : values) { qPos.add(value); } } List<IssueShiftingOrder> list = q.list(); if (list.size() == 2) { return list.get(1); } else { return null; } } /** * Removes all the issue shifting orders where documentName = &#63; and documentYear = &#63; and versionNo = &#63; from the database. * * @param documentName the document name * @param documentYear the document year * @param versionNo the version no * @throws SystemException if a system exception occurred */ @Override public void removeByDocumentNameAndDocumentYearAndVersionNo( long documentName, int documentYear, String versionNo) throws SystemException { for (IssueShiftingOrder issueShiftingOrder : findByDocumentNameAndDocumentYearAndVersionNo( documentName, documentYear, versionNo, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) { remove(issueShiftingOrder); } } /** * Returns the number of issue shifting orders where documentName = &#63; and documentYear = &#63; and versionNo = &#63;. * * @param documentName the document name * @param documentYear the document year * @param versionNo the version no * @return the number of matching issue shifting orders * @throws SystemException if a system exception occurred */ @Override public int countByDocumentNameAndDocumentYearAndVersionNo( long documentName, int documentYear, String versionNo) throws SystemException { FinderPath finderPath = FINDER_PATH_COUNT_BY_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO; Object[] finderArgs = new Object[] { documentName, documentYear, versionNo }; Long count = (Long)FinderCacheUtil.getResult(finderPath, finderArgs, this); if (count == null) { StringBundler query = new StringBundler(4); query.append(_SQL_COUNT_ISSUESHIFTINGORDER_WHERE); query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_DOCUMENTNAME_2); query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_DOCUMENTYEAR_2); boolean bindVersionNo = false; if (versionNo == null) { query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_VERSIONNO_1); } else if (versionNo.equals(StringPool.BLANK)) { query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_VERSIONNO_3); } else { bindVersionNo = true; query.append(_FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_VERSIONNO_2); } String sql = query.toString(); Session session = null; try { session = openSession(); Query q = session.createQuery(sql); QueryPos qPos = QueryPos.getInstance(q); qPos.add(documentName); qPos.add(documentYear); if (bindVersionNo) { qPos.add(versionNo); } count = (Long)q.uniqueResult(); FinderCacheUtil.putResult(finderPath, finderArgs, count); } catch (Exception e) { FinderCacheUtil.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return count.intValue(); } private static final String _FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_DOCUMENTNAME_2 = "issueShiftingOrder.documentName = ? AND "; private static final String _FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_DOCUMENTYEAR_2 = "issueShiftingOrder.documentYear = ? AND "; private static final String _FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_VERSIONNO_1 = "issueShiftingOrder.versionNo IS NULL"; private static final String _FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_VERSIONNO_2 = "issueShiftingOrder.versionNo = ?"; private static final String _FINDER_COLUMN_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO_VERSIONNO_3 = "(issueShiftingOrder.versionNo IS NULL OR issueShiftingOrder.versionNo = '')"; public IssueShiftingOrderPersistenceImpl() { setModelClass(IssueShiftingOrder.class); } /** * Caches the issue shifting order in the entity cache if it is enabled. * * @param issueShiftingOrder the issue shifting order */ @Override public void cacheResult(IssueShiftingOrder issueShiftingOrder) { EntityCacheUtil.putResult(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderImpl.class, issueShiftingOrder.getPrimaryKey(), issueShiftingOrder); issueShiftingOrder.resetOriginalValues(); } /** * Caches the issue shifting orders in the entity cache if it is enabled. * * @param issueShiftingOrders the issue shifting orders */ @Override public void cacheResult(List<IssueShiftingOrder> issueShiftingOrders) { for (IssueShiftingOrder issueShiftingOrder : issueShiftingOrders) { if (EntityCacheUtil.getResult( IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderImpl.class, issueShiftingOrder.getPrimaryKey()) == null) { cacheResult(issueShiftingOrder); } else { issueShiftingOrder.resetOriginalValues(); } } } /** * Clears the cache for all issue shifting orders. * * <p> * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method. * </p> */ @Override public void clearCache() { if (_HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE) { CacheRegistryUtil.clear(IssueShiftingOrderImpl.class.getName()); } EntityCacheUtil.clearCache(IssueShiftingOrderImpl.class.getName()); FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY); FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION); FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION); } /** * Clears the cache for the issue shifting order. * * <p> * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method. * </p> */ @Override public void clearCache(IssueShiftingOrder issueShiftingOrder) { EntityCacheUtil.removeResult(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderImpl.class, issueShiftingOrder.getPrimaryKey()); FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION); FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION); } @Override public void clearCache(List<IssueShiftingOrder> issueShiftingOrders) { FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION); FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION); for (IssueShiftingOrder issueShiftingOrder : issueShiftingOrders) { EntityCacheUtil.removeResult(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderImpl.class, issueShiftingOrder.getPrimaryKey()); } } /** * Creates a new issue shifting order with the primary key. Does not add the issue shifting order to the database. * * @param id the primary key for the new issue shifting order * @return the new issue shifting order */ @Override public IssueShiftingOrder create(long id) { IssueShiftingOrder issueShiftingOrder = new IssueShiftingOrderImpl(); issueShiftingOrder.setNew(true); issueShiftingOrder.setPrimaryKey(id); return issueShiftingOrder; } /** * Removes the issue shifting order with the primary key from the database. Also notifies the appropriate model listeners. * * @param id the primary key of the issue shifting order * @return the issue shifting order that was removed * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a issue shifting order with the primary key could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder remove(long id) throws NoSuchIssueShiftingOrderException, SystemException { return remove((Serializable)id); } /** * Removes the issue shifting order with the primary key from the database. Also notifies the appropriate model listeners. * * @param primaryKey the primary key of the issue shifting order * @return the issue shifting order that was removed * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a issue shifting order with the primary key could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder remove(Serializable primaryKey) throws NoSuchIssueShiftingOrderException, SystemException { Session session = null; try { session = openSession(); IssueShiftingOrder issueShiftingOrder = (IssueShiftingOrder)session.get(IssueShiftingOrderImpl.class, primaryKey); if (issueShiftingOrder == null) { if (_log.isWarnEnabled()) { _log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey); } throw new NoSuchIssueShiftingOrderException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey); } return remove(issueShiftingOrder); } catch (NoSuchIssueShiftingOrderException nsee) { throw nsee; } catch (Exception e) { throw processException(e); } finally { closeSession(session); } } @Override protected IssueShiftingOrder removeImpl( IssueShiftingOrder issueShiftingOrder) throws SystemException { issueShiftingOrder = toUnwrappedModel(issueShiftingOrder); Session session = null; try { session = openSession(); if (!session.contains(issueShiftingOrder)) { issueShiftingOrder = (IssueShiftingOrder)session.get(IssueShiftingOrderImpl.class, issueShiftingOrder.getPrimaryKeyObj()); } if (issueShiftingOrder != null) { session.delete(issueShiftingOrder); } } catch (Exception e) { throw processException(e); } finally { closeSession(session); } if (issueShiftingOrder != null) { clearCache(issueShiftingOrder); } return issueShiftingOrder; } @Override public IssueShiftingOrder updateImpl( vn.dtt.duongbien.dao.vrcb.model.IssueShiftingOrder issueShiftingOrder) throws SystemException { issueShiftingOrder = toUnwrappedModel(issueShiftingOrder); boolean isNew = issueShiftingOrder.isNew(); IssueShiftingOrderModelImpl issueShiftingOrderModelImpl = (IssueShiftingOrderModelImpl)issueShiftingOrder; Session session = null; try { session = openSession(); if (issueShiftingOrder.isNew()) { session.save(issueShiftingOrder); issueShiftingOrder.setNew(false); } else { session.merge(issueShiftingOrder); } } catch (Exception e) { throw processException(e); } finally { closeSession(session); } FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION); if (isNew || !IssueShiftingOrderModelImpl.COLUMN_BITMASK_ENABLED) { FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION); } else { if ((issueShiftingOrderModelImpl.getColumnBitmask() & FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR.getColumnBitmask()) != 0) { Object[] args = new Object[] { issueShiftingOrderModelImpl.getOriginalDocumentName(), issueShiftingOrderModelImpl.getOriginalDocumentYear() }; FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR, args); FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR, args); args = new Object[] { issueShiftingOrderModelImpl.getDocumentName(), issueShiftingOrderModelImpl.getDocumentYear() }; FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR, args); FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEAR, args); } if ((issueShiftingOrderModelImpl.getColumnBitmask() & FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE.getColumnBitmask()) != 0) { Object[] args = new Object[] { issueShiftingOrderModelImpl.getOriginalDocumentName(), issueShiftingOrderModelImpl.getOriginalDocumentYear(), issueShiftingOrderModelImpl.getOriginalRequestState() }; FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE, args); FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE, args); args = new Object[] { issueShiftingOrderModelImpl.getDocumentName(), issueShiftingOrderModelImpl.getDocumentYear(), issueShiftingOrderModelImpl.getRequestState() }; FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE, args); FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_FINDISSUESHIFTINGORDERBYDOCUMENTYEARANDDOCUMENTYEARANDREQUESTSTATE, args); } if ((issueShiftingOrderModelImpl.getColumnBitmask() & FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_REQUESTCODE.getColumnBitmask()) != 0) { Object[] args = new Object[] { issueShiftingOrderModelImpl.getOriginalRequestCode() }; FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_REQUESTCODE, args); FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_REQUESTCODE, args); args = new Object[] { issueShiftingOrderModelImpl.getRequestCode() }; FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_REQUESTCODE, args); FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_REQUESTCODE, args); } if ((issueShiftingOrderModelImpl.getColumnBitmask() & FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO.getColumnBitmask()) != 0) { Object[] args = new Object[] { issueShiftingOrderModelImpl.getOriginalDocumentName(), issueShiftingOrderModelImpl.getOriginalDocumentYear(), issueShiftingOrderModelImpl.getOriginalVersionNo() }; FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO, args); FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO, args); args = new Object[] { issueShiftingOrderModelImpl.getDocumentName(), issueShiftingOrderModelImpl.getDocumentYear(), issueShiftingOrderModelImpl.getVersionNo() }; FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO, args); FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCUMENTNAMEANDDOCUMENTYEARANDVERSIONNO, args); } } EntityCacheUtil.putResult(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderImpl.class, issueShiftingOrder.getPrimaryKey(), issueShiftingOrder); return issueShiftingOrder; } protected IssueShiftingOrder toUnwrappedModel( IssueShiftingOrder issueShiftingOrder) { if (issueShiftingOrder instanceof IssueShiftingOrderImpl) { return issueShiftingOrder; } IssueShiftingOrderImpl issueShiftingOrderImpl = new IssueShiftingOrderImpl(); issueShiftingOrderImpl.setNew(issueShiftingOrder.isNew()); issueShiftingOrderImpl.setPrimaryKey(issueShiftingOrder.getPrimaryKey()); issueShiftingOrderImpl.setId(issueShiftingOrder.getId()); issueShiftingOrderImpl.setRequestCode(issueShiftingOrder.getRequestCode()); issueShiftingOrderImpl.setNumberShiftingOrder(issueShiftingOrder.getNumberShiftingOrder()); issueShiftingOrderImpl.setDocumentName(issueShiftingOrder.getDocumentName()); issueShiftingOrderImpl.setDocumentYear(issueShiftingOrder.getDocumentYear()); issueShiftingOrderImpl.setPortofAuthority(issueShiftingOrder.getPortofAuthority()); issueShiftingOrderImpl.setNameOfShip(issueShiftingOrder.getNameOfShip()); issueShiftingOrderImpl.setFlagStateOfShip(issueShiftingOrder.getFlagStateOfShip()); issueShiftingOrderImpl.setAnchoringPortCode(issueShiftingOrder.getAnchoringPortCode()); issueShiftingOrderImpl.setAnchoringPortWharfCode(issueShiftingOrder.getAnchoringPortWharfCode()); issueShiftingOrderImpl.setPortHarbourCode(issueShiftingOrder.getPortHarbourCode()); issueShiftingOrderImpl.setShiftingPortWharfCode(issueShiftingOrder.getShiftingPortWharfCode()); issueShiftingOrderImpl.setShiftingDate(issueShiftingOrder.getShiftingDate()); issueShiftingOrderImpl.setReasonToShift(issueShiftingOrder.getReasonToShift()); issueShiftingOrderImpl.setIssueDate(issueShiftingOrder.getIssueDate()); issueShiftingOrderImpl.setDirectorOfMaritime(issueShiftingOrder.getDirectorOfMaritime()); issueShiftingOrderImpl.setCertificateNo(issueShiftingOrder.getCertificateNo()); issueShiftingOrderImpl.setRequestState(issueShiftingOrder.getRequestState()); issueShiftingOrderImpl.setVersionNo(issueShiftingOrder.getVersionNo()); issueShiftingOrderImpl.setIsApproval(issueShiftingOrder.getIsApproval()); issueShiftingOrderImpl.setApprovalDate(issueShiftingOrder.getApprovalDate()); issueShiftingOrderImpl.setApprovalName(issueShiftingOrder.getApprovalName()); issueShiftingOrderImpl.setRemarks(issueShiftingOrder.getRemarks()); issueShiftingOrderImpl.setIsCancel(issueShiftingOrder.getIsCancel()); issueShiftingOrderImpl.setCancelDate(issueShiftingOrder.getCancelDate()); issueShiftingOrderImpl.setCancelName(issueShiftingOrder.getCancelName()); issueShiftingOrderImpl.setCancelNote(issueShiftingOrder.getCancelNote()); issueShiftingOrderImpl.setRepresentative(issueShiftingOrder.getRepresentative()); issueShiftingOrderImpl.setDigitalAttachedFile(issueShiftingOrder.getDigitalAttachedFile()); issueShiftingOrderImpl.setSignDate(issueShiftingOrder.getSignDate()); issueShiftingOrderImpl.setSignName(issueShiftingOrder.getSignName()); issueShiftingOrderImpl.setSignTitle(issueShiftingOrder.getSignTitle()); issueShiftingOrderImpl.setSignPlace(issueShiftingOrder.getSignPlace()); issueShiftingOrderImpl.setStampStatus(issueShiftingOrder.getStampStatus()); issueShiftingOrderImpl.setAttachedFile(issueShiftingOrder.getAttachedFile()); return issueShiftingOrderImpl; } /** * Returns the issue shifting order with the primary key or throws a {@link com.liferay.portal.NoSuchModelException} if it could not be found. * * @param primaryKey the primary key of the issue shifting order * @return the issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a issue shifting order with the primary key could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder findByPrimaryKey(Serializable primaryKey) throws NoSuchIssueShiftingOrderException, SystemException { IssueShiftingOrder issueShiftingOrder = fetchByPrimaryKey(primaryKey); if (issueShiftingOrder == null) { if (_log.isWarnEnabled()) { _log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey); } throw new NoSuchIssueShiftingOrderException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey); } return issueShiftingOrder; } /** * Returns the issue shifting order with the primary key or throws a {@link vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException} if it could not be found. * * @param id the primary key of the issue shifting order * @return the issue shifting order * @throws vn.dtt.duongbien.dao.vrcb.NoSuchIssueShiftingOrderException if a issue shifting order with the primary key could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder findByPrimaryKey(long id) throws NoSuchIssueShiftingOrderException, SystemException { return findByPrimaryKey((Serializable)id); } /** * Returns the issue shifting order with the primary key or returns <code>null</code> if it could not be found. * * @param primaryKey the primary key of the issue shifting order * @return the issue shifting order, or <code>null</code> if a issue shifting order with the primary key could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder fetchByPrimaryKey(Serializable primaryKey) throws SystemException { IssueShiftingOrder issueShiftingOrder = (IssueShiftingOrder)EntityCacheUtil.getResult(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderImpl.class, primaryKey); if (issueShiftingOrder == _nullIssueShiftingOrder) { return null; } if (issueShiftingOrder == null) { Session session = null; try { session = openSession(); issueShiftingOrder = (IssueShiftingOrder)session.get(IssueShiftingOrderImpl.class, primaryKey); if (issueShiftingOrder != null) { cacheResult(issueShiftingOrder); } else { EntityCacheUtil.putResult(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderImpl.class, primaryKey, _nullIssueShiftingOrder); } } catch (Exception e) { EntityCacheUtil.removeResult(IssueShiftingOrderModelImpl.ENTITY_CACHE_ENABLED, IssueShiftingOrderImpl.class, primaryKey); throw processException(e); } finally { closeSession(session); } } return issueShiftingOrder; } /** * Returns the issue shifting order with the primary key or returns <code>null</code> if it could not be found. * * @param id the primary key of the issue shifting order * @return the issue shifting order, or <code>null</code> if a issue shifting order with the primary key could not be found * @throws SystemException if a system exception occurred */ @Override public IssueShiftingOrder fetchByPrimaryKey(long id) throws SystemException { return fetchByPrimaryKey((Serializable)id); } /** * Returns all the issue shifting orders. * * @return the issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findAll() throws SystemException { return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null); } /** * Returns a range of all the issue shifting orders. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link vn.dtt.duongbien.dao.vrcb.model.impl.IssueShiftingOrderModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param start the lower bound of the range of issue shifting orders * @param end the upper bound of the range of issue shifting orders (not inclusive) * @return the range of issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findAll(int start, int end) throws SystemException { return findAll(start, end, null); } /** * Returns an ordered range of all the issue shifting orders. * * <p> * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link vn.dtt.duongbien.dao.vrcb.model.impl.IssueShiftingOrderModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order. * </p> * * @param start the lower bound of the range of issue shifting orders * @param end the upper bound of the range of issue shifting orders (not inclusive) * @param orderByComparator the comparator to order the results by (optionally <code>null</code>) * @return the ordered range of issue shifting orders * @throws SystemException if a system exception occurred */ @Override public List<IssueShiftingOrder> findAll(int start, int end, OrderByComparator orderByComparator) throws SystemException { boolean pagination = true; FinderPath finderPath = null; Object[] finderArgs = null; if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) && (orderByComparator == null)) { pagination = false; finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL; finderArgs = FINDER_ARGS_EMPTY; } else { finderPath = FINDER_PATH_WITH_PAGINATION_FIND_ALL; finderArgs = new Object[] { start, end, orderByComparator }; } List<IssueShiftingOrder> list = (List<IssueShiftingOrder>)FinderCacheUtil.getResult(finderPath, finderArgs, this); if (list == null) { StringBundler query = null; String sql = null; if (orderByComparator != null) { query = new StringBundler(2 + (orderByComparator.getOrderByFields().length * 3)); query.append(_SQL_SELECT_ISSUESHIFTINGORDER); appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS, orderByComparator); sql = query.toString(); } else { sql = _SQL_SELECT_ISSUESHIFTINGORDER; if (pagination) { sql = sql.concat(IssueShiftingOrderModelImpl.ORDER_BY_JPQL); } } Session session = null; try { session = openSession(); Query q = session.createQuery(sql); if (!pagination) { list = (List<IssueShiftingOrder>)QueryUtil.list(q, getDialect(), start, end, false); Collections.sort(list); list = new UnmodifiableList<IssueShiftingOrder>(list); } else { list = (List<IssueShiftingOrder>)QueryUtil.list(q, getDialect(), start, end); } cacheResult(list); FinderCacheUtil.putResult(finderPath, finderArgs, list); } catch (Exception e) { FinderCacheUtil.removeResult(finderPath, finderArgs); throw processException(e); } finally { closeSession(session); } } return list; } /** * Removes all the issue shifting orders from the database. * * @throws SystemException if a system exception occurred */ @Override public void removeAll() throws SystemException { for (IssueShiftingOrder issueShiftingOrder : findAll()) { remove(issueShiftingOrder); } } /** * Returns the number of issue shifting orders. * * @return the number of issue shifting orders * @throws SystemException if a system exception occurred */ @Override public int countAll() throws SystemException { Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL, FINDER_ARGS_EMPTY, this); if (count == null) { Session session = null; try { session = openSession(); Query q = session.createQuery(_SQL_COUNT_ISSUESHIFTINGORDER); count = (Long)q.uniqueResult(); FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL, FINDER_ARGS_EMPTY, count); } catch (Exception e) { FinderCacheUtil.removeResult(FINDER_PATH_COUNT_ALL, FINDER_ARGS_EMPTY); throw processException(e); } finally { closeSession(session); } } return count.intValue(); } @Override protected Set<String> getBadColumnNames() { return _badColumnNames; } /** * Initializes the issue shifting order persistence. */ public void afterPropertiesSet() { String[] listenerClassNames = StringUtil.split(GetterUtil.getString( com.liferay.util.service.ServiceProps.get( "value.object.listener.vn.dtt.duongbien.dao.vrcb.model.IssueShiftingOrder"))); if (listenerClassNames.length > 0) { try { List<ModelListener<IssueShiftingOrder>> listenersList = new ArrayList<ModelListener<IssueShiftingOrder>>(); for (String listenerClassName : listenerClassNames) { listenersList.add((ModelListener<IssueShiftingOrder>)InstanceFactory.newInstance( getClassLoader(), listenerClassName)); } listeners = listenersList.toArray(new ModelListener[listenersList.size()]); } catch (Exception e) { _log.error(e); } } } public void destroy() { EntityCacheUtil.removeCache(IssueShiftingOrderImpl.class.getName()); FinderCacheUtil.removeCache(FINDER_CLASS_NAME_ENTITY); FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION); FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION); } private static final String _SQL_SELECT_ISSUESHIFTINGORDER = "SELECT issueShiftingOrder FROM IssueShiftingOrder issueShiftingOrder"; private static final String _SQL_SELECT_ISSUESHIFTINGORDER_WHERE = "SELECT issueShiftingOrder FROM IssueShiftingOrder issueShiftingOrder WHERE "; private static final String _SQL_COUNT_ISSUESHIFTINGORDER = "SELECT COUNT(issueShiftingOrder) FROM IssueShiftingOrder issueShiftingOrder"; private static final String _SQL_COUNT_ISSUESHIFTINGORDER_WHERE = "SELECT COUNT(issueShiftingOrder) FROM IssueShiftingOrder issueShiftingOrder WHERE "; private static final String _ORDER_BY_ENTITY_ALIAS = "issueShiftingOrder."; private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No IssueShiftingOrder exists with the primary key "; private static final String _NO_SUCH_ENTITY_WITH_KEY = "No IssueShiftingOrder exists with the key {"; private static final boolean _HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE = GetterUtil.getBoolean(PropsUtil.get( PropsKeys.HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE)); private static Log _log = LogFactoryUtil.getLog(IssueShiftingOrderPersistenceImpl.class); private static Set<String> _badColumnNames = SetUtil.fromArray(new String[] { "id", "requestCode", "numberShiftingOrder", "documentName", "documentYear", "portofAuthority", "nameOfShip", "flagStateOfShip", "anchoringPortCode", "anchoringPortWharfCode", "portHarbourCode", "shiftingPortWharfCode", "shiftingDate", "reasonToShift", "issueDate", "directorOfMaritime", "certificateNo", "requestState", "versionNo", "isApproval", "approvalDate", "approvalName", "remarks", "isCancel", "cancelDate", "cancelName", "cancelNote", "representative", "digitalAttachedFile", "signDate", "signName", "signTitle", "signPlace", "stampStatus", "attachedFile" }); private static IssueShiftingOrder _nullIssueShiftingOrder = new IssueShiftingOrderImpl() { @Override public Object clone() { return this; } @Override public CacheModel<IssueShiftingOrder> toCacheModel() { return _nullIssueShiftingOrderCacheModel; } }; private static CacheModel<IssueShiftingOrder> _nullIssueShiftingOrderCacheModel = new CacheModel<IssueShiftingOrder>() { @Override public IssueShiftingOrder toEntityModel() { return _nullIssueShiftingOrder; } }; }
[ "longdm10@gmail.com" ]
longdm10@gmail.com
f636dc0deb2285d34bf07a2fe3a1cb8049ee4233
af4baab2468571e40ca59e073fffce1ccac0943e
/src/de/s87/eusage/StatisticsActivity.java
f9486790c497a5a4027a66375598ffb2f5ec774d
[]
no_license
s87/EUsage
68a063f04b07aa6ef733313eab6c2c50ef50e3c6
c15ce297bbb7ca478f0acbd6fdc657c1b03716a8
refs/heads/master
2016-08-08T03:40:01.468945
2015-04-24T12:52:18
2015-04-24T12:52:18
4,487,540
0
0
null
null
null
null
UTF-8
Java
false
false
2,344
java
package de.s87.eusage; import java.text.DecimalFormat; import java.util.Iterator; import android.app.ActionBar.LayoutParams; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; public class StatisticsActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.statistics); Statistics stats = new Statistics(this); TableLayout.LayoutParams rowParams = new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f); TableRow.LayoutParams itemParams = new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f); TableLayout stk = (TableLayout) findViewById(R.id.table_main); TableRow tbrow0 = new TableRow(this); tbrow0.setLayoutParams(rowParams); TextView tv0 = new TextView(this); tv0.setText(getString(R.string.type_of_usage)); tv0.setTextColor(Color.WHITE); tv0.setLayoutParams(itemParams); tbrow0.addView(tv0); TextView tv1 = new TextView(this); tv1.setText(getString(R.string.Usage_calculated_by_day)); tv1.setTextColor(Color.WHITE); tv1.setLayoutParams(itemParams); tbrow0.addView(tv1); stk.addView(tbrow0); //String[] types = stats.getUsageTypes(); Iterator<String> types = stats.getUsageTypes(); while( types.hasNext() ) { String typeId = types.next(); TableRow row = new TableRow(this); row.setLayoutParams(rowParams); TextView type = new TextView(this); type.setText( typeId ); type.setLayoutParams(itemParams); row.addView(type); TextView usageText = new TextView(this); Double usageVal = stats.getUsageForType(typeId).getUsageForDay(); DecimalFormat f = new DecimalFormat("####.##"); usageText.setText( f.format(usageVal) ); usageText.setLayoutParams(itemParams); row.addView(usageText); stk.addView( row ); } } }
[ "holger.graf-reichrt@seven-m.de" ]
holger.graf-reichrt@seven-m.de
363d553a8eb22c93b872d3efa8e4679fb59ef8e2
a2e6df89606417dce64d6fe581ec0e8d9b6f2e85
/src/weapons/Armory.java
3ad9f980e6d935b5779f4c095eeb9e0d55d5f233
[]
no_license
jeoliva222/DND-Game
0a02cc3970739628bea8af0581f5778e94dc79d6
853570ee3df12abef7ae527f37f9576c90466203
refs/heads/master
2021-11-22T20:12:40.035621
2021-11-01T14:36:08
2021-11-01T14:36:08
141,361,952
0
0
null
null
null
null
UTF-8
Java
false
false
9,166
java
package weapons; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import helpers.GPath; import weapons.special.Injector; import weapons.special.KingStaff; import weapons.special.VenomGun; /** * Class where all weapon definitions are stored */ public class Armory { // Fist Weapons ----------------------------- // // Bare fists public static final Fists bareFists = new Fists("Bare Fists", 1, 1, 0.00, 1.0, 2.0, 0, 10, "WEAPON (Fist): Slap'em!", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "bareFists.png")); // Padded Fists (Caestus) public static final Fists caestus = new Fists("Caestus", 1, 2, 0.00, 1.0, 2.5, 0, 6, "WEAPON (Fist): Studded with iron rivets. Charge attack to dish out extra pain!", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "caestus.png")); // Cactus Claws public static final Fists cactusClaws = new Fists("Cactus Claws", 2, 2, 0.00, 1.0, 2.0, 0, 6, "WEAPON (Fist): Claws studded with cactus thorns. Gets consistent results.", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "cactusClaws.png")); // Brick Pads public static final Fists brickPads = new Fists("Brick Pads", 2, 3, 0.00, 1.0, 2.5, 0, 6, "WEAPON (Fist): Sturdy bricks with hand wraps. Packs a punch.", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "caestus.png")); // Sword Weapons ---------------------------- // // Lowly Broken Sword public static final Sword brokenSword = new Sword("Broken Sword", 1, 2, 0.1, 2.0, 1.0, 0, 5, "WEAPON (Sword): Equip this with 'Enter'! Charge attack to slash multiple targets.", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "brokenSword.png")); // Iron Sword public static final Sword ironSword = new Sword("Iron Sword", 1, 3, 0.1, 2.0, 1.0, 0, 5, "WEAPON (Sword): A solid choice, although it could use sharpening.", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "ironSword.png")); // Rusted Sabre public static final Sword rustedSabre = new Sword("Rusted Sabre", 1, 4, 0.1, 1.8, 1.0, 0, 5, "WEAPON (Sword): A partially rusted antique. The blade is quite sharp in a few places.", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "rustedSabre.png")); // Steel Sword public static final Sword steelSword = new Sword("Steel Sword", 1, 5, 0.1, 1.8, 1.0, 0, 5, "WEAPON (Sword): A well-sharpened sturdy sword.", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "ironSword.png")); // Special 'D20' Sword public static final Sword luckSword = new Sword("D20 Sword", 1, 20, 0.01, 5.0, 1.0, 1, 5, "WEAPON (Sword): A roll of the dice...", GPath.createImagePath(GPath.TILE, GPath.GENERIC, "testProj.png")); // Spear Weapons ----------------------------- // // Long Stick Spear public static final Spear longStick = new Spear("Long Stick", 1, 2, 0.15, 1.5, 1.0, 0, 6, "WEAPON (Spear): A pokey stick. Charge attack for a ranged stab!", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "longStick.png")); // Iron Spear public static final Spear ironSpear = new Spear("Iron Spear", 1, 3, 0.15, 1.4, 1.0, 0, 6, "WEAPON (Spear): Keep them at bay with this!", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "ironSpear.png")); // Ceremonial Spear public static final Spear ceremonialSpear = new Spear("Ceremonial Spear", 2, 3, 0.15, 1.75, 1.0, 0, 6, "WEAPON (Spear): It feels wrong to use this.", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "ceremonialSpear.png")); // Fishing Hook Spear public static final Spear fishingHook = new Spear("Fishing Hook", 2, 4, 0.15, 1.5, 1.0, 0, 6, "WEAPON (Spear): A brutal looking hook mounted at the end of a long pole.", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "ironSpear.png")); // Ministerial Staff Spear public static final Spear ministerSpear = new Spear("Ministerial Staff", 3, 6, 0.15, 1.5, 1.2, 0, 6, "WEAPON (Spear): An odd eye watches at you from the top of this staff.", GPath.createImagePath(GPath.TILE, GPath.GENERIC, "testProj.png")); // Dagger Weapons ------------------------------ // // Glass Shard Dagger public static final Dagger glassShard = new Dagger("Glass Shard", 1, 2, 0.2, 2.5, 1.0, 0, 10, "WEAPON (Dagger): A shard of glass from a broken mirror. Charge attack to shadowstep your opponents!", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "glassShard.png")); // Spine Dagger public static final Dagger spineShiv = new Dagger("Spine Shiv", 1, 3, 0.2, 2.0, 1.0, 0, 10, "WEAPON (Dagger): Knife formed from a sharpened bone. Charge attack to shadowstep your opponents!", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "spineShiv.png")); // Box Cutter public static final Dagger boxCutter = new Dagger("Box Cutter", 2, 3, 0.2, 2.5, 1.0, 0, 10, "WEAPON (Dagger): A weaponized office tool. It's surprisingly sharp.", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "glassShard.png")); // Crossbow Weapons ---------------------------- // // Lowly Toy Crossbow public static final Crossbow toyCrossbow = new Crossbow("Toy Crossbow", 1, 1, 0.1, 2.0, 2.0, 0, 7, "WEAPON (Crossbow): Charge attack to fire a bolt! Travels instantaneously.", GPath.createImagePath(GPath.TILE, GPath.GENERIC, "testProj.png")); // Bow Weapons --------------------------------- // // Lowly Twig Bow public static final Bow twigBow = new Bow("Twig Bow", 1, 1, 0.05, 2.0, 3.0, 0, 5, "WEAPON (Bow): Charge attack to fire an arrow!", GPath.createImagePath(GPath.TILE, GPath.GENERIC, "testProj.png")); // Shield Weapons ------------------------------ // // Wooden Targe public static final Shield woodenTarge = new Shield("Wooden Targe", 1, 2, 3, 0.15, 1.5, 1.0, 0, 2, "WEAPON (Shield): [3 Block] Block some incoming damage when charging. This works even when offhanded!", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "woodenTarge.png")); // Buckler public static final Shield buckler = new Shield("Buckler", 1, 3, 4, 0.15, 1.5, 1.0, 0, 2, "WEAPON (Shield): [4 Block] Block some incoming damage when charging. This works even when offhanded!", GPath.createImagePath(GPath.PICKUP, GPath.WEAPON, "woodenTarge.png")); // Hammer Weapons ---------------------------- // // Bone Club public static final Hammer boneClub = new Hammer("Bone Club", 2, 3, 0.05, 1.75, 1.0, 0, 4, "WEAPON (Hammer): A makeshift club. Charge attacks hit all adjacents and partially ignore armor!", GPath.createImagePath(GPath.TILE, GPath.GENERIC, "testProj.png")); // Special Weapons ---------------------------- // // King's Staff public static final KingStaff kingStaff = new KingStaff(); // The Injector public static final Injector injector = new Injector(); // Venom public static final VenomGun venomGun = new VenomGun(); // Weapon testing code ------------------------- // public static void main(String[] args) { // Armor value for testing int armor = 0; // Fists dmgNums(Armory.bareFists, armor); dmgNums(Armory.caestus, armor); dmgNums(Armory.cactusClaws, armor); dmgNums(Armory.brickPads, armor); System.out.println("---------------"); // Swords dmgNums(Armory.brokenSword, armor); dmgNums(Armory.ironSword, armor); dmgNums(Armory.rustedSabre, armor); dmgNums(Armory.steelSword, armor); System.out.println("---------------"); // Spears dmgNums(Armory.longStick, armor); dmgNums(Armory.ironSpear, armor); dmgNums(Armory.ceremonialSpear, armor); dmgNums(Armory.fishingHook, armor); System.out.println("---------------"); // Daggers dmgNums(Armory.glassShard, armor); dmgNums(Armory.spineShiv, armor); dmgNums(Armory.boxCutter, armor); System.out.println("---------------"); // Maces dmgNums(Armory.boneClub, armor); System.out.println("---------------"); // Shields dmgNums(Armory.woodenTarge, armor); dmgNums(Armory.buckler, armor); System.out.println("---------------"); // Special dmgNums(Armory.kingStaff, armor); dmgNums(Armory.injector, armor); dmgNums(Armory.venomGun, armor); } private static void dmgNums(Weapon wep, int armor) { double max = wep.maxDmg - armor; double min = wep.minDmg; if (max < 0) { max = 0; } if (min > max) { min = max; } double nrmChance = 1.0 - wep.critChance; int critDmg = (int) (max * wep.critMult); double totalAvg = 0.0; totalAvg += nrmChance * ((min + max) / 2); totalAvg += wep.critChance * critDmg; totalAvg = round(totalAvg, 2); String spacer = ""; for (int i = 0; i < (18 - wep.getName().length()); i++) { spacer += " "; } DecimalFormat df = new DecimalFormat("#.00"); String formatDouble = df.format(totalAvg); if (formatDouble.startsWith(".")) { formatDouble = "0" + formatDouble; } System.out.println(wep.getName() + spacer + ": Average Damage = " + formatDouble + " | Crit Damage = " + critDmg); } public static double round(double value, int places) { if (places < 0) { throw new IllegalArgumentException(); } BigDecimal bd = new BigDecimal(value); bd = bd.setScale(places, RoundingMode.HALF_UP); return bd.doubleValue(); } }
[ "jeoliva@wpi.edu" ]
jeoliva@wpi.edu
c5022fc971f9df8b17f6d4d7823509e15e6f102f
6a2967e78c96809bfa54575587847d32f4746ae7
/src/main/java/com/lottery/api/mapper/ForeignInterfaceMapper.java
648c4b1c9297c2f801c039da913687939fdf72dd
[]
no_license
xzqlhz/lottery-api
e40e8b25e5190947cf45412b1f2cb6891044bbec
9cc91df844637c37792452996b404aca026c6803
refs/heads/master
2020-05-22T14:23:36.959884
2019-05-16T08:27:04
2019-05-16T08:27:04
186,382,628
0
0
null
null
null
null
UTF-8
Java
false
false
2,385
java
package com.lottery.api.mapper; import com.lottery.api.bean.ForeignInterface; import org.apache.ibatis.annotations.*; import org.apache.ibatis.type.JdbcType; public interface ForeignInterfaceMapper { @Delete({ "delete from foreign_interface", "where name_en = #{nameEn,jdbcType=VARCHAR}" }) int deleteByPrimaryKey(String nameEn); @Insert({ "insert into foreign_interface (name_zh, request_url, ", "request_header, request_parameters, ", "local_url, check_url)", "values (#{nameZh,jdbcType=VARCHAR}, #{requestUrl,jdbcType=VARCHAR}, ", "#{requestHeader,jdbcType=VARCHAR}, #{requestParameters,jdbcType=VARCHAR}, ", "#{localUrl,jdbcType=VARCHAR}, #{checkUrl,jdbcType=VARCHAR})" }) @SelectKey(statement="SELECT LAST_INSERT_ID()", keyProperty="nameEn", before=false, resultType=String.class) int insert(ForeignInterface record); @Select({ "select", "name_en, name_zh, request_url, request_header, request_parameters, local_url, ", "check_url", "from foreign_interface", "where name_en = #{nameEn,jdbcType=VARCHAR}" }) @Results({ @Result(column="name_en", property="nameEn", jdbcType=JdbcType.VARCHAR, id=true), @Result(column="name_zh", property="nameZh", jdbcType=JdbcType.VARCHAR), @Result(column="request_url", property="requestUrl", jdbcType=JdbcType.VARCHAR), @Result(column="request_header", property="requestHeader", jdbcType=JdbcType.VARCHAR), @Result(column="request_parameters", property="requestParameters", jdbcType=JdbcType.VARCHAR), @Result(column="local_url", property="localUrl", jdbcType=JdbcType.VARCHAR), @Result(column="check_url", property="checkUrl", jdbcType=JdbcType.VARCHAR) }) ForeignInterface selectByPrimaryKey(String nameEn); @Update({ "update foreign_interface", "set name_zh = #{nameZh,jdbcType=VARCHAR},", "request_url = #{requestUrl,jdbcType=VARCHAR},", "request_header = #{requestHeader,jdbcType=VARCHAR},", "request_parameters = #{requestParameters,jdbcType=VARCHAR},", "local_url = #{localUrl,jdbcType=VARCHAR},", "check_url = #{checkUrl,jdbcType=VARCHAR}", "where name_en = #{nameEn,jdbcType=VARCHAR}" }) int updateByPrimaryKey(ForeignInterface record); }
[ "734615757@qq.com" ]
734615757@qq.com
59f55ce4efa96dfc457898f6effcd2ff0122907d
cc06c03003f364567233a98e218f87fd8c75f254
/common-util/src/main/java/com/okmich/common/util/api/ArrayTable.java
678414f2da5804de87397bb8170276212c23b566
[]
no_license
okmich/schoolruns
c5df8be7b299f91a681c2cb630b3b523cf02ad2e
340967739fd4ee1b66901c19789d14f2461bdd7a
refs/heads/master
2016-09-12T06:11:03.544471
2016-05-10T10:50:15
2016-05-10T10:50:15
54,635,723
1
0
null
null
null
null
UTF-8
Java
false
false
11,508
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.okmich.common.util.api; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author Michael */ public class ArrayTable<T, RowType, ColType> implements Table<T, RowType, ColType> { private Map<RowType, Integer> rowIndex; private Map<ColType, Integer> colIndex; private T[][] data; private static final int INITIAL_ROW_CAPACITY = 20; private static final int INITIAL_COL_CAPACITY = 1; private int lastRowPointer; private boolean fill; /** * * */ public ArrayTable() { this(false); } /** * * */ public ArrayTable(boolean prefill) { this(prefill, INITIAL_ROW_CAPACITY, INITIAL_COL_CAPACITY); } /** * default constructor that creates a new TableCollection object with a * dimension of {@code rowCapacity} x {@code columnCapacity}. The backing * matrix of {@link T} is also created * * @param rowCapacity - the depth of this container * @param columnCapacity - the breadth of this container */ public ArrayTable(boolean prefill, int rowCapacity, int columnCapacity) { rowIndex = new HashMap<>(rowCapacity); colIndex = new HashMap<>(columnCapacity); data = createStorage(rowCapacity, columnCapacity, prefill); lastRowPointer = 0; } /** * * * @param r */ @Override public void addRow(RowType r) { if (rowIndex.containsKey(r)) { throw new IllegalArgumentException("key already exists"); } synchronized (this) { if (lastRowPointer == data.length) { //increase the size of the array by a quarter of its current size increaseCapacity(1); } rowIndex.put(r, lastRowPointer); ++lastRowPointer; } } /** * {@inheritDoc } */ @Override public void addRows(Collection<RowType> collection) { for (RowType t : collection) { addRow(t); } } /** * * * @param r */ @Override public void addColumn(ColType c) { if (containsColumn(c)) { throw new IllegalArgumentException("column already exist"); } T[][] temp = createStorage(data.length, colIndex.size() + 1, isFill()); synchronized (this) { for (int i = 0; i < lastRowPointer; i++) { //copy array from source to destination System.arraycopy(data[i], 0, temp[i], 0, data[i].length); } //add column to colIndex colIndex.put(c, colIndex.size()); //swap data data = temp; } } /** * removes all the element from this container but retains its width and * label */ public void clear() { data = null; synchronized (this) { //clear the row index rowIndex.clear(); //recreate another data reference data = createStorage(INITIAL_ROW_CAPACITY, colIndex.size(), isFill()); lastRowPointer = 0; } } // // /** // * Trims the capacity of this <tt>ArrayBasedTable</tt> instance to be // * the list's current size. An application can use this operation to // * minimize the storage of an <tt>ArrayBasedTable</tt> instance. // */ // public void trimToSize() { // if (size < oldCapacity) { // elementData = Arrays.copyOf(elementData, size); // } // } /** * * * @param r * @return */ @Override public boolean removeRow(RowType r) { if (!containsRow(r)) { throw new IllegalArgumentException("does not contain row key " + r); } int i = rowIndex.get(r); //the index of the row deleted synchronized (this) { //the object guides this by itself //remove from map rowIndex.remove(r); //remove the row from the array data[i] = null; int row = i; //initialize j //from i to rowPointer, promote all rows one step for (; row < lastRowPointer - 1; row++) { data[row] = data[row + 1]; } //data[row] = null; //set the last row to null --lastRowPointer; //reduce the row pointer for (RowType _r : rowIndex.keySet()) { if (rowIndex.get(_r) > i) { rowIndex.put(_r, rowIndex.get(_r) - 1); } } } return true; } /** * returns true if the object t is successfully added to the this container * otherwise returns false; * * @param r - the object index that represents the row to insert the data * @param c - the object index that represents the column to insert the data * @param t - data to be inserted * @return boolean if insertion is successful otherwise returns false */ @Override public boolean setValue(RowType r, ColType c, T t) { if (containsRow(r) && containsColumn(c)) { data[rowIndex.get(r)][colIndex.get(c)] = t; return true; } return false; } /** * * * @param r * @param c * @return T */ @Override public T getValue(RowType r, ColType c) { if (containsRow(r) && containsColumn(c)) { return data[rowIndex.get(r)][colIndex.get(c)]; } return null; } /** * {@inheritDoc } */ @Override public void remove(RowType r, ColType c) { if (containsRow(r) && containsColumn(c)) { data[rowIndex.get(r)][colIndex.get(c)] = null; } } /** * return a {@link Collection} that contains elements for all rows with the * column * * @param c - the column index values * @return Collection<C> - elements for all rows that belong with the column */ @Override public Collection<T> getColumn(ColType c) { List<T> tList = new ArrayList<>(); synchronized (this) { //return the empty list if the column doesn't contains such value if (!containsColumn(c)) { return tList; } int j = colIndex.get(c); //get the column index for (int i = 0; i < rowIndex.size(); i++) { tList.add(data[i][j]); } } return tList; } /** * * * @param r * @return */ @Override public Collection<T> getRow(RowType r) { List<T> tList = null; synchronized (this) { //return the empty list if the row doesn't contains such value if (!containsRow(r)) { return tList; } int i = rowIndex.get(r); //get the row index tList = new ArrayList<T>(); for (int j = 0; j < colIndex.size(); j++) { tList.add(data[i][j]); } } return tList; } /** * return true if this container instance contains no element within. If the * container contains no element but still has a defined width (column), the * method would still return true * * @return returns true if there is not data element in this container * instance */ @Override public boolean isEmpty() { return lastRowPointer == 0; } /** * resets this container column definition to container that define by the * parameterized Collection * * @param headers - the new Header or column labels for this container * instance */ @Override public void setTableHeader(Collection<ColType> headers) { //call the setTableHeader(C...) variant of this class setTableHeader(headers.toArray((ColType[]) new Object[headers.size()])); } /** * resets this container column definition to container that define by the * parameterized Collection * * @param c - the new Header or column labels for this container instance */ @Override public void setTableHeader(ColType... c) { if (lastRowPointer > 0) { throw new IllegalArgumentException("collection not empty"); } //clear the column index and repopulates synchronized (this) { colIndex.clear(); for (int i = 0; i < c.length; i++) { colIndex.put(c[i], i); } data = createStorage(INITIAL_ROW_CAPACITY, c.length, isFill()); } } /** * * * @param r * @return */ @Override public boolean containsRow(RowType r) { return rowIndex.containsKey(r); } /** * * * @param c * @return */ @Override public boolean containsColumn(ColType c) { return colIndex.containsKey(c); } /** * * * @return Collection<C> */ @Override public Collection<RowType> getRowIndexes() { return rowIndex.keySet(); } /** * * @return Collection<C> */ @Override public Collection<ColType> getColumnIndexes() { return colIndex.keySet(); } /** * @return the fill */ @Override public boolean isFill() { return fill; } /** * * */ @Override public void reset() { synchronized (this) { //clear the row index rowIndex.clear(); //clear the column index colIndex.clear(); //destroy the data reference data = null; lastRowPointer = 0; } } /** * return the number of row elements in this container. This could also be * regarded as the depth of this container * * @return the number of row elements in this container */ @Override public synchronized int size() { return lastRowPointer; } /** * return the number of column elements in this container. This can also be * called the breadth of the container * * @return the number of column elements in this container */ @Override public int width() { return colIndex.size(); } @Override public String toString() { return new StringBuilder("TableCollectionImpl::: [").append(lastRowPointer). append(" rows, ").append(colIndex.size()).append(" columns]"). toString(); } /** * * * @param step */ private void increaseCapacity(int step) { T[][] temp = createStorage(lastRowPointer + step, colIndex.size(), isFill()); System.arraycopy(data, 0, temp, 0, lastRowPointer); data = temp; } /** * * * @param rowCapacity * @param colCapacity * @param prefill * @return T[][] */ private T[][] createStorage(int rowCapacity, int colCapacity, boolean prefill) { T[][] _dataStore = (T[][]) new Object[rowCapacity][colCapacity]; if (prefill) { for (int i = 0; i < rowIndex.size(); i++) { Arrays.fill(data[i], (T) new Object()); } } return _dataStore; } }
[ "okmich2002@yahoo.com" ]
okmich2002@yahoo.com
7acca5eb5b795b6f1267778eb425c574a626454a
96d1a1886f67e84c999f30eb32b9161032c5181a
/TestDateType.java
23f09d3cbffe3ca91d71f9efbf6bca4f870ec648
[]
no_license
zeromov/Learning-Java
7a7bd9fbdc326c6ac40813e47e950dfc2715a180
11be39d6aa3ff417f4dfaac4cd7c7d3d5033b094
refs/heads/master
2021-01-20T06:05:56.268559
2017-04-30T10:29:20
2017-04-30T10:29:20
89,844,446
0
0
null
null
null
null
GB18030
Java
false
false
713
java
public class TestDateType{ public static void main(String[] args){ int a =10; //byte b = 200;//-128----127 int a2 = 010; //八进制 int a3 = 0x10;//16进制 System.out.println(a); //输出结果10 // System.out.println(b); 只能表示-128---127 System.out.println(a2); //输出结果 8 System.out.println(a3); //输出结果 16 System.out.println(Integer.toBinaryString(a)); //二进制 System.out.println(Integer.toOctalString(a)); // 8进制 System.out.println(Integer.toHexString(a)); //16进制 int a5 = 10; int a6 = 200; byte b2 = 100;//如果数据未超过byte/short/char,则自动转型 long a7 = 123456789011111L; } }
[ "355316219@qq.com" ]
355316219@qq.com
7af3f492457e3db1b5feeb7ec22f1f1b8f63680e
be020210b88d5e59936db53043ae325bc9927173
/src-ui/org/pentaho/di/ui/trans/steps/parallelgzipcsv/ParGzipCsvInputDialog.java
2d326ce7ea207cc2d4100bea9459656198d9b09d
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
cskason/pentaho-kettle4.4
124a245e26789ab81cfbea767f2a1d635de0917c
d59882f7076588e2cd007ac9bda5c95edc0bee19
refs/heads/master
2021-01-20T01:52:52.888969
2017-08-07T09:05:38
2017-08-07T09:05:38
89,341,173
0
0
null
null
null
null
UTF-8
Java
false
false
37,531
java
/******************************************************************************* * * Pentaho Data Integration * * Copyright (C) 2002-2012 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.pentaho.di.ui.trans.steps.parallelgzipcsv; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPInputStream; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.provider.local.LocalFile; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.CCombo; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ModifyEvent; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.graphics.Cursor; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.TableItem; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.di.trans.Trans; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.TransPreviewFactory; import org.pentaho.di.trans.step.BaseStepMeta; import org.pentaho.di.trans.step.StepDialogInterface; import org.pentaho.di.trans.steps.parallelgzipcsv.ParGzipCsvInputMeta; import org.pentaho.di.trans.steps.textfileinput.EncodingType; import org.pentaho.di.trans.steps.textfileinput.TextFileInput; import org.pentaho.di.trans.steps.textfileinput.TextFileInputField; import org.pentaho.di.trans.steps.textfileinput.TextFileInputMeta; import org.pentaho.di.ui.core.dialog.EnterNumberDialog; import org.pentaho.di.ui.core.dialog.EnterTextDialog; import org.pentaho.di.ui.core.dialog.ErrorDialog; import org.pentaho.di.ui.core.dialog.PreviewRowsDialog; import org.pentaho.di.ui.core.widget.ColumnInfo; import org.pentaho.di.ui.core.widget.ComboValuesSelectionListener; import org.pentaho.di.ui.core.widget.ComboVar; import org.pentaho.di.ui.core.widget.TableView; import org.pentaho.di.ui.core.widget.TextVar; import org.pentaho.di.ui.trans.dialog.TransPreviewProgressDialog; import org.pentaho.di.ui.trans.step.BaseStepDialog; import org.pentaho.di.ui.trans.steps.textfileinput.TextFileCSVImportProgressDialog; public class ParGzipCsvInputDialog extends BaseStepDialog implements StepDialogInterface { private static Class<?> PKG = ParGzipCsvInputMeta.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$ private ParGzipCsvInputMeta inputMeta; private TextVar wFilename; private CCombo wFilenameField; private Button wbbFilename; // Browse for a file private Button wIncludeFilename; private TextVar wRowNumField; private Button wbDelimiter; private TextVar wDelimiter; private TextVar wEnclosure; private TextVar wBufferSize; private Button wLazyConversion; private Button wHeaderPresent; private FormData fdAddResult; private FormData fdlAddResult; private TableView wFields; private Label wlAddResult; private Button wAddResult; private boolean isReceivingInput; private Button wRunningInParallel; private ComboVar wEncoding; private boolean gotEncodings = false; public ParGzipCsvInputDialog(Shell parent, Object in, TransMeta tr, String sname) { super(parent, (BaseStepMeta)in, tr, sname); inputMeta=(ParGzipCsvInputMeta)in; } public String open() { Shell parent = getParent(); Display display = parent.getDisplay(); shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX); props.setLook(shell); setShellImage(shell, inputMeta); ModifyListener lsMod = new ModifyListener() { public void modifyText(ModifyEvent e) { inputMeta.setChanged(); } }; changed = inputMeta.hasChanged(); FormLayout formLayout = new FormLayout (); formLayout.marginWidth = Const.FORM_MARGIN; formLayout.marginHeight = Const.FORM_MARGIN; shell.setLayout(formLayout); shell.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.Shell.Title")); //$NON-NLS-1$ int middle = props.getMiddlePct(); int margin = Const.MARGIN; // Step name line // wlStepname=new Label(shell, SWT.RIGHT); wlStepname.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.Stepname.Label")); //$NON-NLS-1$ props.setLook(wlStepname); fdlStepname=new FormData(); fdlStepname.left = new FormAttachment(0, 0); fdlStepname.right= new FormAttachment(middle, -margin); fdlStepname.top = new FormAttachment(0, margin); wlStepname.setLayoutData(fdlStepname); wStepname=new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wStepname); wStepname.addModifyListener(lsMod); fdStepname=new FormData(); fdStepname.left = new FormAttachment(middle, 0); fdStepname.top = new FormAttachment(0, margin); fdStepname.right= new FormAttachment(100, 0); wStepname.setLayoutData(fdStepname); Control lastControl = wStepname; // See if the step receives input. If so, we don't ask for the filename, but for the filename field. // isReceivingInput = transMeta.findNrPrevSteps(stepMeta)>0; if (isReceivingInput) { RowMetaInterface previousFields; try { previousFields = transMeta.getPrevStepFields(stepMeta); } catch(KettleStepException e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "ParGzipCsvInputDialog.ErrorDialog.UnableToGetInputFields.Title"), BaseMessages.getString(PKG, "ParGzipCsvInputDialog.ErrorDialog.UnableToGetInputFields.Message"), e); previousFields = new RowMeta(); } // The filename field ... // Label wlFilename = new Label(shell, SWT.RIGHT); wlFilename.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.FilenameField.Label")); //$NON-NLS-1$ props.setLook(wlFilename); FormData fdlFilename = new FormData(); fdlFilename.top = new FormAttachment(lastControl, margin); fdlFilename.left = new FormAttachment(0, 0); fdlFilename.right= new FormAttachment(middle, -margin); wlFilename.setLayoutData(fdlFilename); wFilenameField=new CCombo(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); wFilenameField.setItems(previousFields.getFieldNames()); props.setLook(wFilenameField); wFilenameField.addModifyListener(lsMod); FormData fdFilename = new FormData(); fdFilename.top = new FormAttachment(lastControl, margin); fdFilename.left = new FormAttachment(middle, 0); fdFilename.right= new FormAttachment(100, 0); wFilenameField.setLayoutData(fdFilename); lastControl = wFilenameField; // Checkbox to include the filename in the output... // Label wlIncludeFilename = new Label(shell, SWT.RIGHT); wlIncludeFilename.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.IncludeFilenameField.Label")); //$NON-NLS-1$ props.setLook(wlIncludeFilename); FormData fdlIncludeFilename = new FormData(); fdlIncludeFilename.top = new FormAttachment(lastControl, margin); fdlIncludeFilename.left = new FormAttachment(0, 0); fdlIncludeFilename.right= new FormAttachment(middle, -margin); wlIncludeFilename.setLayoutData(fdlIncludeFilename); wIncludeFilename=new Button(shell, SWT.CHECK); props.setLook(wIncludeFilename); wFilenameField.addModifyListener(lsMod); FormData fdIncludeFilename = new FormData(); fdIncludeFilename.top = new FormAttachment(lastControl, margin); fdIncludeFilename.left = new FormAttachment(middle, 0); fdIncludeFilename.right= new FormAttachment(100, 0); wIncludeFilename.setLayoutData(fdIncludeFilename); lastControl = wIncludeFilename; } else { // Filename... // // The filename browse button // wbbFilename=new Button(shell, SWT.PUSH| SWT.CENTER); props.setLook(wbbFilename); wbbFilename.setText(BaseMessages.getString(PKG, "System.Button.Browse")); wbbFilename.setToolTipText(BaseMessages.getString(PKG, "System.Tooltip.BrowseForFileOrDirAndAdd")); FormData fdbFilename = new FormData(); fdbFilename.top = new FormAttachment(lastControl, margin); fdbFilename.right= new FormAttachment(100, 0); wbbFilename.setLayoutData(fdbFilename); // The field itself... // Label wlFilename = new Label(shell, SWT.RIGHT); wlFilename.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.Filename.Label")); //$NON-NLS-1$ props.setLook(wlFilename); FormData fdlFilename = new FormData(); fdlFilename.top = new FormAttachment(lastControl, margin); fdlFilename.left = new FormAttachment(0, 0); fdlFilename.right= new FormAttachment(middle, -margin); wlFilename.setLayoutData(fdlFilename); wFilename=new TextVar(transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wFilename); wFilename.addModifyListener(lsMod); FormData fdFilename = new FormData(); fdFilename.top = new FormAttachment(lastControl, margin); fdFilename.left = new FormAttachment(middle, 0); fdFilename.right= new FormAttachment(wbbFilename, -margin); wFilename.setLayoutData(fdFilename); lastControl = wFilename; } // delimiter Label wlDelimiter = new Label(shell, SWT.RIGHT); wlDelimiter.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.Delimiter.Label")); //$NON-NLS-1$ props.setLook(wlDelimiter); FormData fdlDelimiter = new FormData(); fdlDelimiter.top = new FormAttachment(lastControl, margin); fdlDelimiter.left = new FormAttachment(0, 0); fdlDelimiter.right= new FormAttachment(middle, -margin); wlDelimiter.setLayoutData(fdlDelimiter); wbDelimiter=new Button(shell, SWT.PUSH| SWT.CENTER); props.setLook(wbDelimiter); wbDelimiter.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.Delimiter.Button")); FormData fdbDelimiter=new FormData(); fdbDelimiter.top = new FormAttachment(lastControl, margin); fdbDelimiter.right= new FormAttachment(100, 0); wbDelimiter.setLayoutData(fdbDelimiter); wDelimiter=new TextVar(transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wDelimiter); wDelimiter.addModifyListener(lsMod); FormData fdDelimiter = new FormData(); fdDelimiter.top = new FormAttachment(lastControl, margin); fdDelimiter.left = new FormAttachment(middle, 0); fdDelimiter.right= new FormAttachment(wbDelimiter, -margin); wDelimiter.setLayoutData(fdDelimiter); lastControl = wDelimiter; // enclosure Label wlEnclosure = new Label(shell, SWT.RIGHT); wlEnclosure.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.Enclosure.Label")); //$NON-NLS-1$ props.setLook(wlEnclosure); FormData fdlEnclosure = new FormData(); fdlEnclosure.top = new FormAttachment(lastControl, margin); fdlEnclosure.left = new FormAttachment(0, 0); fdlEnclosure.right= new FormAttachment(middle, -margin); wlEnclosure.setLayoutData(fdlEnclosure); wEnclosure=new TextVar(transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wEnclosure); wEnclosure.addModifyListener(lsMod); FormData fdEnclosure = new FormData(); fdEnclosure.top = new FormAttachment(lastControl, margin); fdEnclosure.left = new FormAttachment(middle, 0); fdEnclosure.right= new FormAttachment(100, 0); wEnclosure.setLayoutData(fdEnclosure); lastControl = wEnclosure; // bufferSize // Label wlBufferSize = new Label(shell, SWT.RIGHT); wlBufferSize.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.BufferSize.Label")); //$NON-NLS-1$ props.setLook(wlBufferSize); FormData fdlBufferSize = new FormData(); fdlBufferSize.top = new FormAttachment(lastControl, margin); fdlBufferSize.left = new FormAttachment(0, 0); fdlBufferSize.right= new FormAttachment(middle, -margin); wlBufferSize.setLayoutData(fdlBufferSize); wBufferSize = new TextVar(transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wBufferSize); wBufferSize.addModifyListener(lsMod); FormData fdBufferSize = new FormData(); fdBufferSize.top = new FormAttachment(lastControl, margin); fdBufferSize.left = new FormAttachment(middle, 0); fdBufferSize.right= new FormAttachment(100, 0); wBufferSize.setLayoutData(fdBufferSize); lastControl = wBufferSize; // performingLazyConversion? // Label wlLazyConversion = new Label(shell, SWT.RIGHT); wlLazyConversion.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.LazyConversion.Label")); //$NON-NLS-1$ props.setLook(wlLazyConversion); FormData fdlLazyConversion = new FormData(); fdlLazyConversion.top = new FormAttachment(lastControl, margin); fdlLazyConversion.left = new FormAttachment(0, 0); fdlLazyConversion.right= new FormAttachment(middle, -margin); wlLazyConversion.setLayoutData(fdlLazyConversion); wLazyConversion = new Button(shell, SWT.CHECK); props.setLook(wLazyConversion); FormData fdLazyConversion = new FormData(); fdLazyConversion.top = new FormAttachment(lastControl, margin); fdLazyConversion.left = new FormAttachment(middle, 0); fdLazyConversion.right= new FormAttachment(100, 0); wLazyConversion.setLayoutData(fdLazyConversion); lastControl = wLazyConversion; // header row? // Label wlHeaderPresent = new Label(shell, SWT.RIGHT); wlHeaderPresent.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.HeaderPresent.Label")); //$NON-NLS-1$ props.setLook(wlHeaderPresent); FormData fdlHeaderPresent = new FormData(); fdlHeaderPresent.top = new FormAttachment(lastControl, margin); fdlHeaderPresent.left = new FormAttachment(0, 0); fdlHeaderPresent.right= new FormAttachment(middle, -margin); wlHeaderPresent.setLayoutData(fdlHeaderPresent); wHeaderPresent = new Button(shell, SWT.CHECK); props.setLook(wHeaderPresent); FormData fdHeaderPresent = new FormData(); fdHeaderPresent.top = new FormAttachment(lastControl, margin); fdHeaderPresent.left = new FormAttachment(middle, 0); fdHeaderPresent.right= new FormAttachment(100, 0); wHeaderPresent.setLayoutData(fdHeaderPresent); lastControl = wHeaderPresent; wlAddResult=new Label(shell, SWT.RIGHT); wlAddResult.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.AddResult.Label")); props.setLook(wlAddResult); fdlAddResult=new FormData(); fdlAddResult.left = new FormAttachment(0, 0); fdlAddResult.top = new FormAttachment(wHeaderPresent, margin); fdlAddResult.right= new FormAttachment(middle, -margin); wlAddResult.setLayoutData(fdlAddResult); wAddResult=new Button(shell, SWT.CHECK ); props.setLook(wAddResult); wAddResult.setToolTipText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.AddResult.Tooltip")); fdAddResult=new FormData(); fdAddResult.left = new FormAttachment(middle, 0); fdAddResult.top = new FormAttachment(wHeaderPresent, margin); wAddResult.setLayoutData(fdAddResult); lastControl = wAddResult; // The field itself... // Label wlRowNumField = new Label(shell, SWT.RIGHT); wlRowNumField.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.RowNumField.Label")); //$NON-NLS-1$ props.setLook(wlRowNumField); FormData fdlRowNumField = new FormData(); fdlRowNumField.top = new FormAttachment(lastControl, margin); fdlRowNumField.left = new FormAttachment(0, 0); fdlRowNumField.right= new FormAttachment(middle, -margin); wlRowNumField.setLayoutData(fdlRowNumField); wRowNumField=new TextVar(transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wRowNumField); wRowNumField.addModifyListener(lsMod); FormData fdRowNumField = new FormData(); fdRowNumField.top = new FormAttachment(lastControl, margin); fdRowNumField.left = new FormAttachment(middle, 0); fdRowNumField.right= new FormAttachment(100, 0); wRowNumField.setLayoutData(fdRowNumField); lastControl = wRowNumField; // running in parallel? // Label wlRunningInParallel = new Label(shell, SWT.RIGHT); wlRunningInParallel.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.RunningInParallel.Label")); //$NON-NLS-1$ props.setLook(wlRunningInParallel); FormData fdlRunningInParallel = new FormData(); fdlRunningInParallel.top = new FormAttachment(lastControl, margin); fdlRunningInParallel.left = new FormAttachment(0, 0); fdlRunningInParallel.right= new FormAttachment(middle, -margin); wlRunningInParallel.setLayoutData(fdlRunningInParallel); wRunningInParallel = new Button(shell, SWT.CHECK); props.setLook(wRunningInParallel); FormData fdRunningInParallel = new FormData(); fdRunningInParallel.top = new FormAttachment(lastControl, margin); fdRunningInParallel.left = new FormAttachment(middle, 0); wRunningInParallel.setLayoutData(fdRunningInParallel); lastControl=wRunningInParallel; // Encoding Label wlEncoding = new Label(shell, SWT.RIGHT); wlEncoding.setText(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.Encoding.Label")); //$NON-NLS-1$ props.setLook(wlEncoding); FormData fdlEncoding = new FormData(); fdlEncoding.top = new FormAttachment(lastControl, margin); fdlEncoding.left = new FormAttachment(0, 0); fdlEncoding.right= new FormAttachment(middle, -margin); wlEncoding.setLayoutData(fdlEncoding); wEncoding=new ComboVar(transMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); props.setLook(wEncoding); wEncoding.addModifyListener(lsMod); FormData fdEncoding = new FormData(); fdEncoding.top = new FormAttachment(lastControl, margin); fdEncoding.left = new FormAttachment(middle, 0); fdEncoding.right= new FormAttachment(100, 0); wEncoding.setLayoutData(fdEncoding); lastControl = wEncoding; wEncoding.addFocusListener(new FocusListener() { public void focusLost(org.eclipse.swt.events.FocusEvent e) { } public void focusGained(org.eclipse.swt.events.FocusEvent e) { Cursor busy = new Cursor(shell.getDisplay(), SWT.CURSOR_WAIT); shell.setCursor(busy); setEncodings(); shell.setCursor(null); busy.dispose(); } } ); // Some buttons first, so that the dialog scales nicely... // wOK=new Button(shell, SWT.PUSH); wOK.setText(BaseMessages.getString(PKG, "System.Button.OK")); //$NON-NLS-1$ wCancel=new Button(shell, SWT.PUSH); wCancel.setText(BaseMessages.getString(PKG, "System.Button.Cancel")); //$NON-NLS-1$ wPreview=new Button(shell, SWT.PUSH); wPreview.setText(BaseMessages.getString(PKG, "System.Button.Preview")); //$NON-NLS-1$ wPreview.setEnabled(!isReceivingInput); wGet=new Button(shell, SWT.PUSH); wGet.setText(BaseMessages.getString(PKG, "System.Button.GetFields")); //$NON-NLS-1$ wGet.setEnabled(!isReceivingInput); setButtonPositions(new Button[] { wOK, wPreview, wGet, wCancel }, margin, null); // Fields ColumnInfo[] colinf=new ColumnInfo[] { new ColumnInfo(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.NameColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.TypeColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, ValueMeta.getTypes(), true ), new ColumnInfo(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.FormatColumn.Column"), ColumnInfo.COLUMN_TYPE_FORMAT, 2), new ColumnInfo(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.LengthColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.PrecisionColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.CurrencyColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.DecimalColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.GroupColumn.Column"), ColumnInfo.COLUMN_TYPE_TEXT, false), new ColumnInfo(BaseMessages.getString(PKG, "ParGzipCsvInputDialog.TrimTypeColumn.Column"), ColumnInfo.COLUMN_TYPE_CCOMBO, ValueMeta.trimTypeDesc), }; colinf[2].setComboValuesSelectionListener(new ComboValuesSelectionListener() { public String[] getComboValues(TableItem tableItem, int rowNr, int colNr) { String[] comboValues = new String[] { }; int type = ValueMeta.getType( tableItem.getText(colNr-1) ); switch(type) { case ValueMetaInterface.TYPE_DATE: comboValues = Const.getDateFormats(); break; case ValueMetaInterface.TYPE_INTEGER: case ValueMetaInterface.TYPE_BIGNUMBER: case ValueMetaInterface.TYPE_NUMBER: comboValues = Const.getNumberFormats(); break; default: break; } return comboValues; } }); wFields=new TableView(transMeta, shell, SWT.FULL_SELECTION | SWT.MULTI, colinf, 1, lsMod, props ); FormData fdFields = new FormData(); fdFields.top = new FormAttachment(lastControl, margin*2); fdFields.bottom= new FormAttachment(wOK, -margin*2); fdFields.left = new FormAttachment(0, 0); fdFields.right = new FormAttachment(100, 0); wFields.setLayoutData(fdFields); // Add listeners lsCancel = new Listener() { public void handleEvent(Event e) { cancel(); } }; lsOK = new Listener() { public void handleEvent(Event e) { ok(); } }; lsPreview = new Listener() { public void handleEvent(Event e) { preview(); } }; lsGet = new Listener() { public void handleEvent(Event e) { getCSV(); } }; wCancel.addListener (SWT.Selection, lsCancel ); wOK.addListener (SWT.Selection, lsOK ); wPreview.addListener(SWT.Selection, lsPreview); wGet.addListener (SWT.Selection, lsGet ); lsDef=new SelectionAdapter() { public void widgetDefaultSelected(SelectionEvent e) { ok(); } }; wStepname.addSelectionListener( lsDef ); if (wFilename!=null) wFilename.addSelectionListener( lsDef ); if (wFilenameField!=null) wFilenameField.addSelectionListener( lsDef ); wDelimiter.addSelectionListener( lsDef ); wEnclosure.addSelectionListener( lsDef ); wBufferSize.addSelectionListener( lsDef ); wRowNumField.addSelectionListener( lsDef ); // Allow the insertion of tabs as separator... wbDelimiter.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent se) { Text t = wDelimiter.getTextWidget(); if ( t != null ) t.insert("\t"); } } ); if (wbbFilename!=null) { // Listen to the browse button next to the file name wbbFilename.addSelectionListener( new SelectionAdapter() { public void widgetSelected(SelectionEvent e) { FileDialog dialog = new FileDialog(shell, SWT.OPEN); dialog.setFilterExtensions(new String[] {"*.txt;*.csv", "*.csv", "*.txt", "*"}); if (wFilename.getText()!=null) { String fname = transMeta.environmentSubstitute(wFilename.getText()); dialog.setFileName( fname ); } dialog.setFilterNames(new String[] {BaseMessages.getString(PKG, "System.FileType.CSVFiles")+", "+BaseMessages.getString(PKG, "System.FileType.TextFiles"), BaseMessages.getString(PKG, "System.FileType.CSVFiles"), BaseMessages.getString(PKG, "System.FileType.TextFiles"), BaseMessages.getString(PKG, "System.FileType.AllFiles")}); if (dialog.open()!=null) { String str = dialog.getFilterPath()+System.getProperty("file.separator")+dialog.getFileName(); wFilename.setText(str); } } } ); } // Detect X or ALT-F4 or something that kills this window... shell.addShellListener( new ShellAdapter() { public void shellClosed(ShellEvent e) { cancel(); } } ); // Set the shell size, based upon previous time... setSize(); getData(); inputMeta.setChanged(changed); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } return stepname; } private void setEncodings() { // Encoding of the text file: if (!gotEncodings) { gotEncodings = true; wEncoding.removeAll(); List<Charset> values = new ArrayList<Charset>(Charset.availableCharsets().values()); for (int i=0;i<values.size();i++) { Charset charSet = (Charset)values.get(i); wEncoding.add( charSet.displayName() ); } // Now select the default! String defEncoding = Const.getEnvironmentVariable("file.encoding", "UTF-8"); int idx = Const.indexOfString(defEncoding, wEncoding.getItems() ); if (idx>=0) wEncoding.select( idx ); } } public void getData() { getData(inputMeta); } /** * Copy information from the meta-data input to the dialog fields. */ public void getData(ParGzipCsvInputMeta inputMeta) { wStepname.setText(stepname); if (isReceivingInput) { wFilenameField.setText(Const.NVL(inputMeta.getFilenameField(), "")); wIncludeFilename.setSelection(inputMeta.isIncludingFilename()); } else { wFilename.setText(Const.NVL(inputMeta.getFilename(), "")); } wDelimiter.setText(Const.NVL(inputMeta.getDelimiter(), "")); wEnclosure.setText(Const.NVL(inputMeta.getEnclosure(), "")); wBufferSize.setText(Const.NVL(inputMeta.getBufferSize(), "")); wLazyConversion.setSelection(inputMeta.isLazyConversionActive()); wHeaderPresent.setSelection(inputMeta.isHeaderPresent()); wRunningInParallel.setSelection(inputMeta.isRunningInParallel()); wRowNumField.setText(Const.NVL(inputMeta.getRowNumField(), "")); wAddResult.setSelection(inputMeta.isAddResultFile()); wEncoding.setText(Const.NVL(inputMeta.getEncoding(), "")); for (int i=0;i<inputMeta.getInputFields().length;i++) { TextFileInputField field = inputMeta.getInputFields()[i]; TableItem item = new TableItem(wFields.table, SWT.NONE); int colnr=1; item.setText(colnr++, Const.NVL(field.getName(), "")); item.setText(colnr++, ValueMeta.getTypeDesc(field.getType())); item.setText(colnr++, Const.NVL(field.getFormat(), "")); item.setText(colnr++, field.getLength()>=0?Integer.toString(field.getLength()):"") ; item.setText(colnr++, field.getPrecision()>=0?Integer.toString(field.getPrecision()):"") ; item.setText(colnr++, Const.NVL(field.getCurrencySymbol(), "")); item.setText(colnr++, Const.NVL(field.getDecimalSymbol(), "")); item.setText(colnr++, Const.NVL(field.getGroupSymbol(), "")); item.setText(colnr++, Const.NVL(field.getTrimTypeDesc(), "")); } wFields.removeEmptyRows(); wFields.setRowNums(); wFields.optWidth(true); wStepname.selectAll(); } private void cancel() { stepname=null; inputMeta.setChanged(changed); dispose(); } private void getInfo(ParGzipCsvInputMeta inputMeta) { if (isReceivingInput) { inputMeta.setFilenameField(wFilenameField.getText()); inputMeta.setIncludingFilename(wIncludeFilename.getSelection()); } else { inputMeta.setFilename(wFilename.getText()); } inputMeta.setDelimiter(wDelimiter.getText()); inputMeta.setEnclosure(wEnclosure.getText()); inputMeta.setBufferSize(wBufferSize.getText()); inputMeta.setLazyConversionActive(wLazyConversion.getSelection()); inputMeta.setHeaderPresent(wHeaderPresent.getSelection()); inputMeta.setRowNumField(wRowNumField.getText()); inputMeta.setAddResultFile( wAddResult.getSelection() ); inputMeta.setRunningInParallel(wRunningInParallel.getSelection()); inputMeta.setEncoding(wEncoding.getText()); int nrNonEmptyFields = wFields.nrNonEmpty(); inputMeta.allocate(nrNonEmptyFields); for (int i=0;i<nrNonEmptyFields;i++) { TableItem item = wFields.getNonEmpty(i); inputMeta.getInputFields()[i] = new TextFileInputField(); int colnr=1; inputMeta.getInputFields()[i].setName( item.getText(colnr++) ); inputMeta.getInputFields()[i].setType( ValueMeta.getType( item.getText(colnr++) ) ); inputMeta.getInputFields()[i].setFormat( item.getText(colnr++) ); inputMeta.getInputFields()[i].setLength( Const.toInt(item.getText(colnr++), -1) ); inputMeta.getInputFields()[i].setPrecision( Const.toInt(item.getText(colnr++), -1) ); inputMeta.getInputFields()[i].setCurrencySymbol( item.getText(colnr++) ); inputMeta.getInputFields()[i].setDecimalSymbol( item.getText(colnr++) ); inputMeta.getInputFields()[i].setGroupSymbol( item.getText(colnr++) ); inputMeta.getInputFields()[i].setTrimType(ValueMeta.getTrimTypeByDesc( item.getText(colnr++) )); } wFields.removeEmptyRows(); wFields.setRowNums(); wFields.optWidth(true); inputMeta.setChanged(); } private void ok() { if (Const.isEmpty(wStepname.getText())) return; getInfo(inputMeta); stepname = wStepname.getText(); dispose(); } // Get the data layout private void getCSV() { InputStream inputStream = null; try { ParGzipCsvInputMeta meta = new ParGzipCsvInputMeta(); getInfo(meta); String filename = transMeta.environmentSubstitute(meta.getFilename()); FileObject fileObject = KettleVFS.getFileObject(filename); if (!(fileObject instanceof LocalFile)) { // We can only use NIO on local files at the moment, so that's what we limit ourselves to. // throw new KettleException(BaseMessages.getString(PKG, "ParGzipCsvInput.Log.OnlyLocalFilesAreSupported")); } wFields.table.removeAll(); inputStream = new GZIPInputStream(KettleVFS.getInputStream(fileObject)); InputStreamReader reader = new InputStreamReader(inputStream); EncodingType encodingType = EncodingType.guessEncodingType(reader.getEncoding()); // Read a line of data to determine the number of rows... // String line = TextFileInput.getLine(log, reader, encodingType, TextFileInputMeta.FILE_FORMAT_MIXED, new StringBuilder(1000)); // Split the string, header or data into parts... // String[] fieldNames = Const.splitString(line, meta.getDelimiter()); if (!meta.isHeaderPresent()) { // Don't use field names from the header... // Generate field names F1 ... F10 // DecimalFormat df = new DecimalFormat("000"); // $NON-NLS-1$ for (int i=0;i<fieldNames.length;i++) { fieldNames[i] = "Field_"+df.format(i); // $NON-NLS-1$ } } else { if (!Const.isEmpty(meta.getEnclosure())) { for (int i=0;i<fieldNames.length;i++) { if (fieldNames[i].startsWith(meta.getEnclosure()) && fieldNames[i].endsWith(meta.getEnclosure()) && fieldNames[i].length()>1) fieldNames[i] = fieldNames[i].substring(1, fieldNames[i].length()-1); } } } // Trim the names to make sure... // for (int i=0;i<fieldNames.length;i++) { fieldNames[i] = Const.trim(fieldNames[i]); } // Update the GUI // for (int i=0;i<fieldNames.length;i++) { TableItem item = new TableItem(wFields.table, SWT.NONE); item.setText(1, fieldNames[i]); item.setText(2, ValueMeta.getTypeDesc(ValueMetaInterface.TYPE_STRING)); } wFields.removeEmptyRows(); wFields.setRowNums(); wFields.optWidth(true); // Now we can continue reading the rows of data and we can guess the // Sample a few lines to determine the correct type of the fields... // String shellText = BaseMessages.getString(PKG, "ParGzipCsvInputDialog.LinesToSample.DialogTitle"); String lineText = BaseMessages.getString(PKG, "ParGzipCsvInputDialog.LinesToSample.DialogMessage"); EnterNumberDialog end = new EnterNumberDialog(shell, 100, shellText, lineText); int samples = end.open(); if (samples >= 0) { getInfo(meta); TextFileCSVImportProgressDialog pd = new TextFileCSVImportProgressDialog(shell, meta, transMeta, reader, samples, true); String message = pd.open(); if (message!=null) { wFields.removeAll(); // OK, what's the result of our search? getData(meta); wFields.removeEmptyRows(); wFields.setRowNums(); wFields.optWidth(true); EnterTextDialog etd = new EnterTextDialog(shell, BaseMessages.getString(PKG, "ParGzipCsvInputDialog.ScanResults.DialogTitle"), BaseMessages.getString(PKG, "ParGzipCsvInputDialog.ScanResults.DialogMessage"), message, true); etd.setReadOnly(); etd.open(); } } } catch(IOException e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "ParGzipCsvInputDialog.IOError.DialogTitle"), BaseMessages.getString(PKG, "ParGzipCsvInputDialog.IOError.DialogMessage"), e); } catch(KettleException e) { new ErrorDialog(shell, BaseMessages.getString(PKG, "System.Dialog.Error.Title"), BaseMessages.getString(PKG, "ParGzipCsvInputDialog.ErrorGettingFileDesc.DialogMessage"), e); } finally { try { inputStream.close(); } catch(Exception e) { } } } // Preview the data private void preview() { // Create the XML input step ParGzipCsvInputMeta oneMeta = new ParGzipCsvInputMeta(); getInfo(oneMeta); TransMeta previewMeta = TransPreviewFactory.generatePreviewTransformation(transMeta, oneMeta, wStepname.getText()); EnterNumberDialog numberDialog = new EnterNumberDialog(shell, props.getDefaultPreviewSize(), BaseMessages.getString(PKG, "ParGzipCsvInputDialog.PreviewSize.DialogTitle"), BaseMessages.getString(PKG, "ParGzipCsvInputDialog.PreviewSize.DialogMessage")); int previewSize = numberDialog.open(); if (previewSize>0) { TransPreviewProgressDialog progressDialog = new TransPreviewProgressDialog(shell, previewMeta, new String[] { wStepname.getText() }, new int[] { previewSize } ); progressDialog.open(); Trans trans = progressDialog.getTrans(); String loggingText = progressDialog.getLoggingText(); if (!progressDialog.isCancelled()) { if (trans.getResult()!=null && trans.getResult().getNrErrors()>0) { EnterTextDialog etd = new EnterTextDialog(shell, BaseMessages.getString(PKG, "System.Dialog.PreviewError.Title"), BaseMessages.getString(PKG, "System.Dialog.PreviewError.Message"), loggingText, true ); etd.setReadOnly(); etd.open(); } } PreviewRowsDialog prd =new PreviewRowsDialog(shell, transMeta, SWT.NONE, wStepname.getText(), progressDialog.getPreviewRowsMeta(wStepname.getText()), progressDialog.getPreviewRows(wStepname.getText()), loggingText); prd.open(); } } }
[ "cskason@gmail.com" ]
cskason@gmail.com
10bad6f7a93a5a14b50bc56eb3497320244b1810
32666e3c79aec07c8682d7557b9960e822280656
/HMRs/src/collections/Listm.java
c0acba691ed6c123d253aded3586aa2f3a6e66e3
[]
no_license
bsadar/sadar
7643fa38d761cd921a016e85b64be449f53c2c2c
36aebceebaf92f1bbce76c25ace3973f8882cad8
refs/heads/master
2023-08-05T05:50:37.704998
2023-07-27T12:29:59
2023-07-27T12:29:59
200,335,636
1
1
null
null
null
null
UTF-8
Java
false
false
329
java
package collections; import java.util.ArrayList; import java.util.List; public class Listm { public static void main(String[] args) { // TODO Auto-generated method stub List obj=new ArrayList(); obj.add("sadar"); obj.add(234); obj.add('m'); obj.add("sadar"); System.out.print(obj); } } .
[ "qaplanet@qaplanet-PC" ]
qaplanet@qaplanet-PC
e1fc6a0f43371c836aaf8781ae6565f4f70917f9
ee9e5d76f2826febe8f86f82c30f74d004509cb0
/src/galileo/util/GeoHash.java
f6ddd7c96585a78bf01d244c7201f4b21d30d991
[ "BSD-2-Clause", "Apache-2.0" ]
permissive
jkachika/galileo-spacetime
734fd19cac804542c879fc4af89ada17e6d02011
7826cef86f3b2a263a5465489e701ed2b564192a
refs/heads/master
2021-06-19T00:39:00.415727
2017-04-25T10:53:37
2017-04-25T10:53:37
42,688,150
0
1
null
null
null
null
UTF-8
Java
false
false
17,169
java
/* Copyright (c) 2013, Colorado State University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. This software is provided by the copyright holders and contributors "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright holder or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. */ package galileo.util; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Set; import galileo.dataset.Coordinates; import galileo.dataset.Point; import galileo.dataset.SpatialRange; import galileo.dht.Partitioner; /** * This class provides an implementation of the GeoHash (http://www.geohash.org) * algorithm. * * See http://en.wikipedia.org/wiki/Geohash for implementation details. */ public class GeoHash { public final static byte BITS_PER_CHAR = 5; public final static int LATITUDE_RANGE = 90; public final static int LONGITUDE_RANGE = 180; public final static int MAX_PRECISION = 30; // 6 character precision = 30 (~ // 1.2km x 0.61km) /** * This character array maps integer values (array indices) to their GeoHash * base32 alphabet equivalents. */ public final static char[] charMap = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; /** * Allows lookups from a GeoHash character to its integer index value. */ public final static HashMap<Character, Integer> charLookupTable = new HashMap<Character, Integer>(); /** * Initialize HashMap for character to integer lookups. */ static { for (int i = 0; i < charMap.length; ++i) { charLookupTable.put(charMap[i], i); } } private String binaryHash; private Rectangle2D bounds; public GeoHash() { this(""); } public GeoHash(String binaryString) { this.binaryHash = binaryString; ArrayList<Boolean> bits = new ArrayList<>(); for (char bit : this.binaryHash.toCharArray()) bits.add(bit == '0' ? false : true); float[] longitude = decodeBits(bits, false); float[] latitude = decodeBits(bits, true); SpatialRange range = new SpatialRange(latitude[0], latitude[1], longitude[0], longitude[1]); Pair<Coordinates, Coordinates> coordsPair = range.get2DCoordinates(); Point<Integer> upLeft = coordinatesToXY(coordsPair.a); Point<Integer> lowRight = coordinatesToXY(coordsPair.b); this.bounds = new Rectangle(upLeft.X(), upLeft.Y(), lowRight.X() - upLeft.X(), lowRight.Y() - upLeft.Y()); } public int getPrecision() { return this.binaryHash.length(); } public String getBinaryHash() { return this.binaryHash; } public String[] getValues(int precision) { String[] values = null; String hash = ""; for (int i = 0; i < this.binaryHash.length(); i += 5) { String hashChar = this.binaryHash.substring(i, java.lang.Math.min(i + 5, this.binaryHash.length())); if (hashChar.length() == 5) hash += charMap[Integer.parseInt(hashChar, 2)]; else { String beginHash = hashChar; String endHash = hashChar; while (beginHash.length() < BITS_PER_CHAR) { beginHash += "0"; endHash += "1"; } values = new String[2]; values[0] = hash + charMap[Integer.parseInt(beginHash, 2)]; values[1] = hash + charMap[Integer.parseInt(endHash, 2)]; while (values[0].length() < precision){ values[0] += "0"; values[1] += "z"; } } } if (values == null){ if (hash.length() < precision){ String beginHash = hash; String endHash = hash; while (beginHash.length() < precision){ beginHash += "0"; endHash += "z"; } values = new String[] { beginHash, endHash }; } else { values = new String[] {hash}; } } return values; } public Rectangle2D getRectangle() { return this.bounds; } @Override public boolean equals(Object obj) { if (obj instanceof GeoHash) { GeoHash other = (GeoHash) obj; return this.binaryHash.equals(other.binaryHash); } return false; } @Override public int hashCode() { return this.binaryHash.hashCode(); } /** * Encode a set of {@link Coordinates} into a GeoHash string. * * @param coords * Coordinates to get GeoHash for. * * @param precision * Desired number of characters in the returned GeoHash String. * More characters means more precision. * * @return GeoHash string. */ public static String encode(Coordinates coords, int precision) { return encode(coords.getLatitude(), coords.getLongitude(), precision); } /** * Encode {@link SpatialRange} into a GeoHash string. * * @param range * SpatialRange to get GeoHash for. * * @param precision * Number of characters in the returned GeoHash String. More * characters is more precise. * * @return GeoHash string. */ public static String encode(SpatialRange range, int precision) { Coordinates rangeCoords = range.getCenterPoint(); return encode(rangeCoords.getLatitude(), rangeCoords.getLongitude(), precision); } /** * Encode latitude and longitude into a GeoHash string. * * @param latitude * Latitude coordinate, in degrees. * * @param longitude * Longitude coordinate, in degrees. * * @param precision * Number of characters in the returned GeoHash String. More * characters is more precise. * * @return resulting GeoHash String. */ public static String encode(float latitude, float longitude, int precision) { while (latitude < -90f || latitude > 90f) latitude = latitude < -90f ? 180.0f + latitude : latitude > 90f ? -180f + latitude : latitude; while (longitude < -180f || longitude > 180f) longitude = longitude < -180f ? 360.0f + longitude : longitude > 180f ? -360f + longitude : longitude; /* * Set up 2-element arrays for longitude and latitude that we can flip * between while encoding */ float[] high = new float[2]; float[] low = new float[2]; float[] value = new float[2]; high[0] = LONGITUDE_RANGE; high[1] = LATITUDE_RANGE; low[0] = -LONGITUDE_RANGE; low[1] = -LATITUDE_RANGE; value[0] = longitude; value[1] = latitude; String hash = ""; for (int p = 0; p < precision; ++p) { float middle = 0.0f; int charBits = 0; for (int b = 0; b < BITS_PER_CHAR; ++b) { int bit = (p * BITS_PER_CHAR) + b; charBits <<= 1; middle = (high[bit % 2] + low[bit % 2]) / 2; if (value[bit % 2] > middle) { charBits |= 1; low[bit % 2] = middle; } else { high[bit % 2] = middle; } } hash += charMap[charBits]; } return hash; } /** * Convert a GeoHash String to a long integer. * * @param hash * GeoHash String to convert. * * @return The GeoHash as a long integer. */ public static long hashToLong(String hash) { long longForm = 0; /* Long can fit 12 GeoHash characters worth of precision. */ if (hash.length() > 12) { hash = hash.substring(0, 12); } for (char c : hash.toCharArray()) { longForm <<= BITS_PER_CHAR; longForm |= charLookupTable.get(c); } return longForm; } /** * Decode a GeoHash to an approximate bounding box that contains the * original GeoHashed point. * * @param geoHash * GeoHash string * * @return Spatial Range (bounding box) of the GeoHash. */ public static SpatialRange decodeHash(String geoHash) { ArrayList<Boolean> bits = getBits(geoHash); float[] longitude = decodeBits(bits, false); float[] latitude = decodeBits(bits, true); return new SpatialRange(latitude[0], latitude[1], longitude[0], longitude[1]); } /** * @param geohash * - geohash of the region for which the neighbors are needed * @param direction * - one of nw, n, ne, w, e, sw, s, se * @return */ public static String getNeighbour(String geohash, String direction) { if (geohash == null || geohash.trim().length() == 0) throw new IllegalArgumentException("Invalid Geohash"); geohash = geohash.trim(); int precision = geohash.length(); SpatialRange boundingBox = decodeHash(geohash); Coordinates centroid = boundingBox.getCenterPoint(); float widthDiff = boundingBox.getUpperBoundForLongitude() - centroid.getLongitude(); float heightDiff = boundingBox.getUpperBoundForLatitude() - centroid.getLatitude(); switch (direction) { case "nw": return encode(boundingBox.getUpperBoundForLatitude() + heightDiff, boundingBox.getLowerBoundForLongitude() - widthDiff, precision); case "n": return encode(boundingBox.getUpperBoundForLatitude() + heightDiff, centroid.getLongitude(), precision); case "ne": return encode(boundingBox.getUpperBoundForLatitude() + heightDiff, boundingBox.getUpperBoundForLongitude() + widthDiff, precision); case "w": return encode(centroid.getLatitude(), boundingBox.getLowerBoundForLongitude() - widthDiff, precision); case "e": return encode(centroid.getLatitude(), boundingBox.getUpperBoundForLongitude() + widthDiff, precision); case "sw": return encode(boundingBox.getLowerBoundForLatitude() - heightDiff, boundingBox.getLowerBoundForLongitude() - widthDiff, precision); case "s": return encode(boundingBox.getLowerBoundForLatitude() - heightDiff, centroid.getLongitude(), precision); case "se": return encode(boundingBox.getLowerBoundForLatitude() - heightDiff, boundingBox.getUpperBoundForLongitude() + widthDiff, precision); default: return ""; } } public static String[] getNeighbours(String geoHash) { String[] neighbors = new String[8]; if (geoHash == null || geoHash.trim().length() == 0) throw new IllegalArgumentException("Invalid Geohash"); geoHash = geoHash.trim(); int precision = geoHash.length(); SpatialRange boundingBox = decodeHash(geoHash); Coordinates centroid = boundingBox.getCenterPoint(); float widthDiff = boundingBox.getUpperBoundForLongitude() - centroid.getLongitude(); float heightDiff = boundingBox.getUpperBoundForLatitude() - centroid.getLatitude(); neighbors[0] = encode(boundingBox.getUpperBoundForLatitude() + heightDiff, boundingBox.getLowerBoundForLongitude() - widthDiff, precision); neighbors[1] = encode(boundingBox.getUpperBoundForLatitude() + heightDiff, centroid.getLongitude(), precision); neighbors[2] = encode(boundingBox.getUpperBoundForLatitude() + heightDiff, boundingBox.getUpperBoundForLongitude() + widthDiff, precision); neighbors[3] = encode(centroid.getLatitude(), boundingBox.getLowerBoundForLongitude() - widthDiff, precision); neighbors[4] = encode(centroid.getLatitude(), boundingBox.getUpperBoundForLongitude() + widthDiff, precision); neighbors[5] = encode(boundingBox.getLowerBoundForLatitude() - heightDiff, boundingBox.getLowerBoundForLongitude() - widthDiff, precision); neighbors[6] = encode(boundingBox.getLowerBoundForLatitude() - heightDiff, centroid.getLongitude(), precision); neighbors[7] = encode(boundingBox.getLowerBoundForLatitude() - heightDiff, boundingBox.getUpperBoundForLongitude() + widthDiff, precision); return neighbors; } /** * @param coordinates * - latitude and longitude values * @return Point - x, y pair obtained from a geohash precision of 12. x,y * values range from [0, 4096) */ public static Point<Integer> coordinatesToXY(Coordinates coords) { int width = 1 << MAX_PRECISION; float xDiff = coords.getLongitude() + 180; float yDiff = 90 - coords.getLatitude(); int x = (int) (xDiff * width / 360); int y = (int) (yDiff * width / 180); return new Point<>(x, y); } public static Coordinates xyToCoordinates(int x, int y) { int width = 1 << MAX_PRECISION; return new Coordinates(90 - y * 180f / width, x * 360f / width - 180f); } public static String[] getIntersectingGeohashes(List<Coordinates> polygon) { Set<String> hashes = new HashSet<String>(); Polygon geometry = new Polygon(); for (Coordinates coords : polygon) { Point<Integer> point = coordinatesToXY(coords); geometry.addPoint(point.X(), point.Y()); } // center may not lie inside polygon so start with any vertex of the // polygon Coordinates spatialCenter = polygon.get(0); Rectangle2D box = geometry.getBounds2D(); String geohash = encode(spatialCenter, Partitioner.SPATIAL_PRECISION); Queue<String> hashQue = new LinkedList<String>(); Set<String> computedHashes = new HashSet<String>(); hashQue.offer(geohash); while (!hashQue.isEmpty()) { String hash = hashQue.poll(); computedHashes.add(hash); SpatialRange hashRange = decodeHash(hash); Pair<Coordinates, Coordinates> coordsPair = hashRange.get2DCoordinates(); Point<Integer> upLeft = coordinatesToXY(coordsPair.a); Point<Integer> lowRight = coordinatesToXY(coordsPair.b); Rectangle2D hashRect = new Rectangle(upLeft.X(), upLeft.Y(), lowRight.X() - upLeft.X(), lowRight.Y() - upLeft.Y()); if (hash.equals(geohash) && hashRect.contains(box)) { hashes.add(hash); break; } if (geometry.intersects(hashRect)) { hashes.add(hash); String[] neighbors = getNeighbours(hash); for (String neighbour : neighbors) if (!computedHashes.contains(neighbour) && !hashQue.contains(neighbour)) hashQue.offer(neighbour); } } return hashes.size() > 0 ? hashes.toArray(new String[hashes.size()]) : new String[] {}; } /** * Decode GeoHash bits from a binary GeoHash. * * @param bits * ArrayList of Booleans containing the GeoHash bits * * @param latitude * If set to <code>true</code> the latitude bits are decoded. If * set to <code>false</code> the longitude bits are decoded. * * @return low, high range that the GeoHashed location falls between. */ private static float[] decodeBits(ArrayList<Boolean> bits, boolean latitude) { float low, high, middle; int offset; if (latitude) { offset = 1; low = -90.0f; high = 90.0f; } else { offset = 0; low = -180.0f; high = 180.0f; } for (int i = offset; i < bits.size(); i += 2) { middle = (high + low) / 2; if (bits.get(i)) { low = middle; } else { high = middle; } } if (latitude) { return new float[] { low, high }; } else { return new float[] { low, high }; } } /** * Converts a GeoHash string to its binary representation. * * @param hash * GeoHash string to convert to binary * * @return The GeoHash in binary form, as an ArrayList of Booleans. */ private static ArrayList<Boolean> getBits(String hash) { hash = hash.toLowerCase(); /* Create an array of bits, 5 bits per character: */ ArrayList<Boolean> bits = new ArrayList<Boolean>(hash.length() * BITS_PER_CHAR); /* Loop through the hash string, setting appropriate bits. */ for (int i = 0; i < hash.length(); ++i) { int charValue = charLookupTable.get(hash.charAt(i)); /* Set bit from charValue, then shift over to the next bit. */ for (int j = 0; j < BITS_PER_CHAR; ++j, charValue <<= 1) { bits.add((charValue & 0x10) == 0x10); } } return bits; } public static Polygon buildAwtPolygon(List<Coordinates> geometry) { Polygon polygon = new Polygon(); for (Coordinates coords : geometry) { Point<Integer> point = coordinatesToXY(coords); polygon.addPoint(point.X(), point.Y()); } return polygon; } public static void getGeohashPrefixes(Polygon polygon, GeoHash gh, int precision, Set<GeoHash> intersections) { if (gh.getPrecision() >= precision) { intersections.add(gh); } else { if (polygon.contains(gh.getRectangle())) { intersections.add(gh); } else { GeoHash leftGH = new GeoHash(gh.getBinaryHash() + "0"); GeoHash rightGH = new GeoHash(gh.getBinaryHash() + "1"); if (polygon.intersects(leftGH.getRectangle())) getGeohashPrefixes(polygon, leftGH, precision, intersections); if (polygon.intersects(rightGH.getRectangle())) getGeohashPrefixes(polygon, rightGH, precision, intersections); } } } }
[ "johnsoncharles26@gmail.com" ]
johnsoncharles26@gmail.com
280538d3b799e4f67ad4f7dff8e6da7e1a9d9e6b
e90f7f00481e3c8c71fbb802841c39f015acec75
/src/main/java/com/etnlgravtnl/test/example9/Job1Listener.java
a8ed5a642ff330112ba2cb79a6122ed8b7783130
[]
no_license
yangcongyuan/admin
bf91ea351d2bbce64577eaa6962ece8d45cc7f98
6c260707e1af44d65e6db7347515fcfd72da7e9c
refs/heads/master
2020-07-28T12:53:25.004511
2016-09-09T05:43:44
2016-09-09T05:43:44
67,769,336
0
0
null
null
null
null
UTF-8
Java
false
false
2,168
java
/* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. 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.etnlgravtnl.test.example9; import static org.quartz.JobBuilder.newJob; import static org.quartz.TriggerBuilder.newTrigger; import org.quartz.JobDetail; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.quartz.JobListener; import org.quartz.SchedulerException; import org.quartz.Trigger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author wkratzer */ public class Job1Listener implements JobListener { private static Logger _log = LoggerFactory.getLogger(Job1Listener.class); public String getName() { return "job1_to_job2"; } public void jobToBeExecuted(JobExecutionContext inContext) { _log.info("Job1Listener says: Job Is about to be executed."); } public void jobExecutionVetoed(JobExecutionContext inContext) { _log.info("Job1Listener says: Job Execution was vetoed."); } public void jobWasExecuted(JobExecutionContext inContext, JobExecutionException inException) { _log.info("Job1Listener says: Job was executed."); _log.info("小伙子,你被监听啦."); // Simple job #2 JobDetail job2 = newJob(SimpleJob2.class).withIdentity("job2").build(); Trigger trigger = newTrigger().withIdentity("job2Trigger").startNow().build(); try { // schedule the job to run! inContext.getScheduler().scheduleJob(job2, trigger); } catch (SchedulerException e) { _log.warn("Unable to schedule job2!"); e.printStackTrace(); } } }
[ "newman123" ]
newman123
2ef70aa27b98fe9ea8821f0a4ccde912b6a3c8e6
7e0f6a0ea1cbf6b612fa854d08bcd316df6ce2ef
/src/MonthsEnum.java
be30b1a8e21c94c59f339d9045e980565311a367
[]
no_license
OShiman/Enum-Months
29f016d9de53504fb71db90326fadd12aa95d93d
4566ab38770772785786649f87048fdbeaad3fad
refs/heads/master
2020-05-05T11:14:08.402060
2019-04-07T15:00:37
2019-04-07T15:00:37
179,980,741
0
0
null
null
null
null
UTF-8
Java
false
false
1,350
java
public enum MonthsEnum { JANUARY(31,"01 сычня -новий рік. 07 січня Різдво Христове. ","Січень"), FEBRUARY(28,"14 лютого День закоханих.","Лютий"), MARCH(31,"08 березня Міжнароний жіночий день.","Березень"), APRIL(30,"28 квітня Великдень.","Квітень"), MAY(31,"01 травня День праці.","Травень"), JUNE(30,"09 червня День Перемоги. 28 червня День Конституції України.","Червень"), JULY(31,"","Липень"), AUGUST(31,"24 серпня День Незалежності України.","Серпень"), SEPTEMBER(30,"","Вересень"), OCTOBER(31,"14 Жовтня День Захисника України","Жовтень"), NOVEMBER(30,"","Листопад"), DECEMBER(31,"","Грудень"); int day; String holidays; String translation; MonthsEnum(int day,String holidays,String translation){ this.day = day; this.holidays = holidays; this.translation = translation; } public String getTranslation(){ return translation; } public String getHolidays(){ return holidays; } public int getDay(){ return day; } }
[ "oleksandrshimasky@gmail.com" ]
oleksandrshimasky@gmail.com
fa2b938feab6dbc12b5a0a606f92eeb66494bc52
59a69c3fbd7cfab42e800cdaf3b508ceb58655a6
/app/src/main/java/cn/xiaocool/android_etong/MainActivity.java
b11e3d73913d837cd27f6fee9ebb9991c8b8a46e
[]
no_license
1091390146/Android_etong
ada117ef48cb144a1a61f757a4088a69c497cfbe
ff1783c85191b73a793a62dc45017d7adb6857cb
refs/heads/master
2021-01-20T18:33:11.108598
2016-06-12T06:35:13
2016-06-12T06:35:13
60,950,790
0
0
null
null
null
null
UTF-8
Java
false
false
1,784
java
package cn.xiaocool.android_etong; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) 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(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
[ "1091390146@qq.com" ]
1091390146@qq.com
0373c34919619b8e73f0a22093cd191e10613b26
53d677a55e4ece8883526738f1c9d00fa6560ff7
/com/tencent/qqmusic/mediaplayer/audioplaylist/charsetdetector/CharsetRecog_Unicode$CharsetRecog_UTF_32_BE.java
b6a736419b4b5e86beb9bf0677c8d63c3c565427
[]
no_license
0jinxing/wechat-apk-source
544c2d79bfc10261eb36389c1edfdf553d8f312a
f75eefd87e9b9ecf2f76fc6d48dbba8e24afcf3d
refs/heads/master
2020-06-07T20:06:03.580028
2019-06-21T09:17:26
2019-06-21T09:17:26
193,069,132
9
4
null
null
null
null
UTF-8
Java
false
false
781
java
package com.tencent.qqmusic.mediaplayer.audioplaylist.charsetdetector; class CharsetRecog_Unicode$CharsetRecog_UTF_32_BE extends CharsetRecog_Unicode.CharsetRecog_UTF_32 { int getChar(byte[] paramArrayOfByte, int paramInt) { return (paramArrayOfByte[(paramInt + 0)] & 0xFF) << 24 | (paramArrayOfByte[(paramInt + 1)] & 0xFF) << 16 | (paramArrayOfByte[(paramInt + 2)] & 0xFF) << 8 | paramArrayOfByte[(paramInt + 3)] & 0xFF; } String getName() { return "UTF-32BE"; } } /* Location: C:\Users\Lin\Downloads\dex-tools-2.1-SNAPSHOT\dex-tools-2.1-SNAPSHOT\classes6-dex2jar.jar * Qualified Name: com.tencent.qqmusic.mediaplayer.audioplaylist.charsetdetector.CharsetRecog_Unicode.CharsetRecog_UTF_32_BE * JD-Core Version: 0.6.2 */
[ "172601673@qq.com" ]
172601673@qq.com