text
stringlengths
10
2.72M
package com.mtsoft.animal.activity; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.mtsoft.animal.R; public class StartActivity extends AppCompatActivity implements View.OnClickListener{ private boolean isRunning = true; private int[] imgNumber = { R.drawable.ic_3, R.drawable.ic_2, R.drawable.ic_1, R.drawable.ic, R.drawable.ic, R.drawable.ic, R.drawable.ic }; private ImageView icNumber; private TextView icFruit, icAlphabet; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_start); initViews(); } private void initViews() { icNumber = (ImageView) findViewById(R.id.ic_number); Animation scale = AnimationUtils.loadAnimation(this, R.anim.anim_image); icNumber.startAnimation(scale); icAlphabet = (TextView) findViewById(R.id.ic_alphabet); icFruit = (TextView) findViewById(R.id.ic_fruit); icAlphabet.setOnClickListener(this); icFruit.setOnClickListener(this); MyAsync mAsync = new MyAsync(); mAsync.execute(); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.ic_fruit: Intent intent = new Intent(this, MainActivity.class); startActivity(intent); break; case R.id.ic_alphabet: Toast.makeText(this, "Click!", Toast.LENGTH_SHORT).show(); finish(); break; } } @Override protected void onDestroy() { super.onDestroy(); } class MyAsync extends AsyncTask<Void, Integer, Void>{ @Override protected Void doInBackground(Void... voids) { int i = 0; while (isRunning){ try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (i == 3){ isRunning = false; } publishProgress(i); i++; } return null; } @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); icNumber.setVisibility(View.INVISIBLE); icAlphabet.setVisibility(View.VISIBLE); isRunning = false; icFruit.setVisibility(View.VISIBLE); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); int i = values[0]; icNumber.setImageResource(imgNumber[i]); } } }
package com.bramgussekloo.projectb.Activities.Login; import android.content.Intent; import android.support.annotation.NonNull; import android.support.design.widget.TextInputEditText; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Patterns; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.bramgussekloo.projectb.Activities.EditProduct.ChooseProduct; import com.bramgussekloo.projectb.R; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; public class LoginActivity extends AppCompatActivity { private FirebaseAuth mAuth; private TextInputEditText email; private TextInputEditText password; private TextInputLayout emailLayout; private TextInputLayout passwordLayout; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); getSupportActionBar().hide();//hide action bar LoginButton(); mAuth = FirebaseAuth.getInstance(); } public void LoginButton() { progressBar = findViewById(R.id.progressbar); email = findViewById(R.id.Email); password = findViewById(R.id.Password); emailLayout = findViewById(R.id.textInputLayoutEmail); passwordLayout = findViewById(R.id.textInputLayoutPassword); Button login_button = findViewById(R.id.LoginButton); Button register_button = findViewById(R.id.RegisterButton); TextView reset_password = findViewById(R.id.rest_pass); register_button.setOnClickListener( // button to go to the register page new View.OnClickListener() { @Override public void onClick(View v) { Intent Registerintent = new Intent(getBaseContext(), Register.class); startActivity(Registerintent); } } ); login_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // button to login if (email == null || email.getText().toString().trim().isEmpty()){ emailLayout.setError("Email required."); email.requestFocus(); return; // error if email is empty } if (password == null || password.getText().toString().trim().isEmpty()){ passwordLayout.setError("Password required."); password.requestFocus(); return; // check if password is empty } if (!Patterns.EMAIL_ADDRESS.matcher(email.getText().toString().trim()).matches()){ email.setError("Enter a valid email."); email.requestFocus(); return; // check if email is an email-address or not } progressBar.setVisibility(View.VISIBLE); mAuth.signInWithEmailAndPassword(email.getText().toString().trim(), password.getText().toString().trim()).addOnCompleteListener(new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()){ // sign in to the app sendToMain(); emptyInputEditText(); } else { Toast.makeText(LoginActivity.this, "Log in failed", Toast.LENGTH_SHORT).show(); emptyInputEditText(); } progressBar.setVisibility(View.INVISIBLE); } }); } }); reset_password.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getBaseContext(), ResetPassword.class); startActivity(intent); } }); } private void emptyInputEditText() { // empty input fields email.setText(null); password.setText(null); } @Override protected void onStart() { // will automatically run in background super.onStart(); FirebaseUser currentUser = mAuth.getCurrentUser(); // get current user if(currentUser != null){ sendToMain(); // sends user to mainactivity } } private void sendToMain() { Intent mainIntent = new Intent(getApplicationContext(), MainActivity.class); startActivity(mainIntent); finish(); // ensures user can't go back } }
package org.bca.training.spring.core; import java.util.List; import org.bca.training.spring.core.beans.data.Model; import org.bca.training.spring.core.beans.read.Datasource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.stereotype.Component; @Component public class Application { @Autowired Datasource datasource; public static void main(String ... args) throws Exception { /// INITIALISATION // On initialise un contexte qui est le moteur d'injection Spring, en utilisant la configuration de la classe Config AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); // On instancie un objet Application depuis ce contexte, ainsi l'injection fonctionnera // ce qui n'aurait pas été le cas si on avait fait Application app = new Application(); Application app = context.getBean(Application.class); /// TRAITEMENT METIER // // Cette application utilise CsvFileDatasource pour lire le fichier data.csv, // dont chaque ligne décrit un objet "Model" : soit Car, Animal, CupCake ou Human // // On va utiliser l'injection de dépendance Spring pour modifier le comportement // de l'application avec uniquement des annotations, sans toucher aux algorithmes. List<Model> list = app.datasource.read(); list.forEach(Model::display); } }
package rso.dfs.dummy.server; import java.util.ArrayList; /** * @author Adam Papros <adam.papros@gmail.com> * * */ public class Storage { private ArrayList<Data> data; public Storage() { data = new ArrayList<Data>(); } public Storage(ArrayList<Data> data) { super(); this.data = data; } public ArrayList<Data> getData() { return data; } public void setData(ArrayList<Data> data) { this.data = data; } }
package com.wifisec; import android.annotation.TargetApi; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.location.Location; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.AsyncTask; import android.os.Build; import android.util.Log; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class HandleWifi extends AsyncTask<Void, Void, Void> { private Context context; public MyAdapter adapter; WifiManager wifimanager; WifiScanReceiver wifireceiver; List<ScanResult> wifiScanList; double location_x; double location_y; String type; public HandleWifi(Context context, String type) { Log.w("TEST_SEC_WIFI", "HandleWifi constructeur HandleWifi"+type); this.type = type; this.context = context; this.adapter = new MyAdapter(context, type); this.wifimanager = (WifiManager) this.context.getSystemService(Context.WIFI_SERVICE); this.wifireceiver = new WifiScanReceiver(); IntentFilter filter1 = new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); filter1.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); this.context.registerReceiver(wifireceiver, filter1); IntentFilter filter2 = new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION); filter2.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); this.context.registerReceiver(wifireceiver, filter2); IntentFilter filter3 = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); filter3.addAction(ConnectivityManager.CONNECTIVITY_ACTION); this.context.registerReceiver(wifireceiver, filter3); if(this.type == "scan") getWifis(); else if(this.type == "delete_vulnerables") deleteVulnerablesWifis(); else if(this.type == "show_vulnerables") getVulnerablesWifis(); this.adapter.callbackwifi = this; } public void deleteVulnerablesWifis() { adapter.wifis.clear(); FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(this.context); SQLiteDatabase db = mDbHelper.getWritableDatabase(); db.delete(FeedReaderContract.FeedEntry.TABLE_NAME_WIFI, null, null); adapter.notifyDataSetChanged(); } public boolean PasswordsWifis(String ssid, String bssid) { FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(this.context); SQLiteDatabase db = mDbHelper.getReadableDatabase(); SQLiteDatabase db2 = mDbHelper.getWritableDatabase(); String[] projection = { FeedReaderContract.FeedEntry._ID, FeedReaderContract.FeedEntry.COLUMN_NAME_PASSWORDS_TITLE }; String sortOrder = FeedReaderContract.FeedEntry._ID + " DESC"; Cursor c = db.query( FeedReaderContract.FeedEntry.TABLE_NAME_PASSWORDS, projection, null, null, null, null, sortOrder ); while (c.moveToNext()) { long itemId = c.getLong(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry._ID)); String password = c.getString(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_PASSWORDS_TITLE)); if(this.TestPasswordsWifis(this.context, bssid, ssid, password)) { Log.w("TEST_SEC_WIFI", "add entry TestPasswordsWifis"); ContentValues values = new ContentValues(); values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_TITLE, ssid); values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_BSSID, bssid); values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_LASTSCAN, ssid); values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_SECURITY, 1); values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_ROBUSTNESS, 0); values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_PASSWORD, password); values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_ROBUSTNESS, 0); values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_COORDINATES_X, this.location_x); values.put(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_COORDINATES_Y, this.location_y); long newRowId = db2.insert(FeedReaderContract.FeedEntry.TABLE_NAME_WIFI, null, values); return true; } } return false; } void getVulnerablesWifis() { Log.w("TEST_SEC_WIFI","getVulnerablesWifis"); adapter.wifis.clear(); FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(this.context); SQLiteDatabase db = mDbHelper.getReadableDatabase(); String[] projection = { FeedReaderContract.FeedEntry._ID, FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_TITLE, FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_BSSID, FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_SECURITY, FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_PASSWORD, FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_COORDINATES_X, FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_COORDINATES_Y }; // How you want the results sorted in the resulting Cursor String sortOrder = FeedReaderContract.FeedEntry._ID + " DESC"; Cursor c = db.query( FeedReaderContract.FeedEntry.TABLE_NAME_WIFI, // The table to query projection, // The columns to return FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_ROBUSTNESS + " = 0", // The columns for the WHERE clause null, // The values for the WHERE clause null, // don't group the rows null, // don't filter by row groups sortOrder // The sort order ); while (c.moveToNext()) { long itemId = c.getLong(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry._ID)); String title = c.getString(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_TITLE)); String bssid = c.getString(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_BSSID)); int security = c.getInt(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_SECURITY)); String password = c.getString(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_PASSWORD)); double coordinates_x = c.getDouble(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_COORDINATES_X)); double coordinates_y = c.getDouble(c.getColumnIndexOrThrow(FeedReaderContract.FeedEntry.COLUMN_NAME_WIFI_COORDINATES_Y)); adapter.wifis.add(new WifiSec(title, bssid, security, password, coordinates_x, coordinates_y)); Log.w("TEST_SEC_WIFI", "getVulnerablesWifis add = "+title); } adapter.notifyDataSetChanged(); } private class WifiScanReceiver extends BroadcastReceiver { @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1) public void onReceive(Context c, Intent intent) { if(intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) { NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO); if(networkInfo.isConnected()) { if (networkInfo.getState() == NetworkInfo.State.CONNECTED) { List<WifiConfiguration> item = wifimanager.getConfiguredNetworks(); int i = item.size(); Iterator<WifiConfiguration> iter = item.iterator(); WifiConfiguration config = item.get(0); Log.w("TEST_SEC_WIFI","est connecté"); Log.w("TEST_SEC_WIFI", "SSID" + config.SSID); Log.w("TEST_SEC_WIFI", "PASSWORD" + config.preSharedKey); } } } else if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI && !networkInfo.isConnected()) { // Wifi is disconnected } } else if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) { wifiScanList = wifimanager.getScanResults(); for (int i = 0; i < wifiScanList.size(); i++) { if (!(((wifiScanList.get(i)).SSID).isEmpty())) { Log.w("TEST_SEC_WIFI", "scan wifi = " + ((wifiScanList.get(i)).SSID)); if(check_security(wifiScanList.get(i).capabilities) == 1) adapter.wifis.add(new WifiSec(((wifiScanList.get(i)).SSID), ((wifiScanList.get(i)).BSSID), check_security(wifiScanList.get(i).capabilities), "", location_x, location_y )); } } adapter.notifyDataSetChanged(); } } } public boolean isConnected(Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = null; if (connectivityManager != null) { networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if(networkInfo.isConnected()) return true; } return false; } public class Foo implements Runnable { public Context tmpcontext; public String bssid; public String ssid; public String password; private volatile boolean value = false; public boolean getValue() { return value; } @Override public void run() { try { if (!wifimanager.isWifiEnabled()) { wifimanager.setWifiEnabled(true); } WifiConfiguration conf = new WifiConfiguration(); conf.SSID = "\"" + ssid + "\""; conf.preSharedKey = "\"" + password + "\""; int ret = wifimanager.addNetwork(conf); boolean returne = wifimanager.enableNetwork(ret, true); wifimanager.saveConfiguration(); wifimanager.reconnect(); for(int i = 0; i < 7; i ++) { Log.w("TEST_SEC_WIFI", "isConnected i = " + i); if (isConnected(tmpcontext)) { value = true; break; } Thread.sleep(1000); } } catch (Exception e) { } } }; public boolean TestPasswordsWifis(final Context tmpcontext, final String bssid, final String ssid, final String password) { this.clearWifi(); Log.w("TEST_SEC_WIFI", "1 PasswordsWifis ssid = " + ssid); Foo foo = new Foo(); foo.tmpcontext = tmpcontext; foo.bssid = bssid; foo.ssid = ssid; foo.password = password; Thread t = new Thread(foo); t.start(); try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } Log.w("TEST_SEC_WIFI", "2 PasswordsWifis foo.getValue() = " + foo.getValue()); return foo.getValue(); } private int check_security(String capabilities) { if (capabilities.toLowerCase().contains("WEP".toLowerCase()) || (capabilities.toLowerCase().contains("WPA2".toLowerCase())) || (capabilities.toLowerCase().contains("WPA".toLowerCase()))) return 1; return 0; } public boolean clearWifi() { if (!disconnectAP()) { return false; } // Disable Wifi if (!this.wifimanager.setWifiEnabled(false)) { return false; } // Wait for the actions to be completed try { Thread.sleep(5*1000); } catch (InterruptedException e) {} return true; } public boolean disconnectAP() { if (this.wifimanager.isWifiEnabled()) { //remove the current network Id WifiInfo curWifi = this.wifimanager.getConnectionInfo(); if (curWifi == null) { return false; } int curNetworkId = curWifi.getNetworkId(); this.wifimanager.removeNetwork(curNetworkId); this.wifimanager.saveConfiguration(); // remove other saved networks List<WifiConfiguration> netConfList = this.wifimanager.getConfiguredNetworks(); if (netConfList != null) { for (int i = 0; i < netConfList.size(); i++) { WifiConfiguration conf = new WifiConfiguration(); conf = netConfList.get(i); this.wifimanager.removeNetwork(conf.networkId); } } } this.wifimanager.saveConfiguration(); return true; } @Override protected Void doInBackground(Void... params) { String locationProvider = LocationManager.NETWORK_PROVIDER; LocationManager locationManager = (LocationManager) this.context.getSystemService(Context.LOCATION_SERVICE); Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); this.location_x = lastKnownLocation.getLatitude(); this.location_y = lastKnownLocation.getLongitude(); this.wifimanager.startScan(); return null; } void getWifis() { adapter.wifis.clear(); this.execute(); Log.w("TEST_SEC_WIFI", "requetewifi getWifis "); } protected void onPostExecute() { } }
package com.example.tecomca.mylogin_seccion05.Fragments.InstructionsFragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.tecomca.mylogin_seccion05.Fragments.Juegos.ListaJuegosFragment; import com.example.tecomca.mylogin_seccion05.Fragments.categorisFragment.CategoriesAdapter; import com.example.tecomca.mylogin_seccion05.Fragments.categorisFragment.CatergorisFragment; import com.example.tecomca.mylogin_seccion05.Model.Category; import com.example.tecomca.mylogin_seccion05.Model.Instructions; import com.example.tecomca.mylogin_seccion05.R; import com.example.tecomca.mylogin_seccion05.Sql.DatabaseHelper; import com.example.tecomca.mylogin_seccion05.Utils.ComunViews; import java.util.ArrayList; import java.util.List; public class AlertFragment extends Fragment implements AlertAdapter.OnItemClickListener { private ComunViews comunViews; private RecyclerView recyclerInstrutions; private DatabaseHelper databaseHelper; private AlertAdapter adapter; private List<Instructions> instructions; private final String TAG = AlertFragment.class.getSimpleName(); public AlertFragment() { // Required empty public constructor } public static AlertFragment newInstance(ComunViews cv) { Bundle args = new Bundle(); args.putParcelable("comun", cv); AlertFragment fragment = new AlertFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); comunViews = (ComunViews) getArguments().getParcelable("comun"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_alert, container, false); recyclerInstrutions = view.findViewById(R.id.listInstrucciones); // /initAll(view); databaseHelper = new DatabaseHelper(getContext()); RecyclerViewUpdate(); return view; } public void RecyclerViewUpdate() { recyclerInstrutions.setLayoutManager(new LinearLayoutManager(getContext())); // if (adapter == null) { //Log.i(TAG, "--->listadoAdapter null"); instructions = new ArrayList<>(); adapter = new AlertAdapter(this.databaseHelper.getInstruction(), getContext()); adapter.setOnItemClickListener(this); recyclerInstrutions.setAdapter(adapter); } @Override public void onClickSelectedItem(Instructions instructions) { Log.i(TAG, "--->Instructions description: " + instructions.getDescription()); // comunViews.changeFragment(ListaJuegosFragment.newInstance(comunViews, instructions.getId())); } }
package server; import Utils.Message; import tanks.model.RectModel; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.util.HashMap; import java.util.LinkedHashMap; public class Receiver implements Runnable { private final LinkedHashMap<Integer, Bullet> bullets; private boolean isRunning; private Thread t; private final HashMap<Integer, Player> players; public Receiver(LinkedHashMap<Integer, Bullet> bullets, HashMap<Integer, Player> players) { this.players = players; isRunning = false; this.bullets = bullets; } public void start() { isRunning = true; t = new Thread(this); t.start(); } @Override public void run(){ DatagramSocket socket = null; try { socket = new DatagramSocket(Server.ADDRESS.getPort()); } catch (SocketException e) { e.printStackTrace(); isRunning = false; } while (isRunning) { try { byte []buffer = new byte[256]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); socket.receive(packet); Message m = new Message(packet.getData()); int i = m.getInt("id"); synchronized (players) { Player p = players.get(i); switch (m.getType()){ case ROTATE: p.getModel().rotate(m.getInt("value")); break; case MOVE: p.getModel().move(); break; case SET_DIRECTION: p.getModel().setDirection(m.getInt("value")); break; case SHOOT: Bullet bullet = new Bullet(p.getModel().getAzimutDeg(), p.getModel().getX() + p.getModel().getWidth()/2, p.getModel().getY() + p.getModel().getHeight()/2, 20, 20, 5, p); bullet.setDirection(RectModel.DIRECTION_FRONT); bullet.move(15); int index = 0; for (Integer key: bullets.keySet()){ if(key > index){ index = key; } } synchronized (bullets) { bullets.put(++index, bullet); } break; case LOGOUT: // players.remove(m.getInt("id")); players.get(m.getInt("id")).setActive(false); System.out.println(m.getInt("id") + " odstranen"); break; } } } catch (IOException e) { e.printStackTrace(); } } } public void stop() { isRunning = false; try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } }
package game.states; import java.awt.Graphics; import game.worlds.World; /** * Estado de un juego mientras se lo est� jugando. */ public class GameState extends State { private static GameState instance; @Override public void update() { World.getInstance().update(); } @Override public void draw(Graphics g) { World.getInstance().draw(g); } public static State getInstance() { if (instance == null) { instance = new GameState(); } return (instance); } }
package zseurekaclient.ll.service.impl; import zseurekaclient.ll.bean.ConsultContent; import zseurekaclient.ll.service.UserService; import java.util.List; public class UserServiceImpl implements UserService { @Override public List<ConsultContent> queryContents() { return null; } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.socket.sockjs.transport.handler; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.springframework.util.Assert; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.SubProtocolCapable; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import org.springframework.web.socket.handler.WebSocketHandlerDecorator; import org.springframework.web.socket.sockjs.transport.SockJsServiceConfig; import org.springframework.web.socket.sockjs.transport.session.WebSocketServerSockJsSession; /** * An implementation of {@link WebSocketHandler} that adds SockJS messages frames, sends * SockJS heartbeat messages, and delegates lifecycle events and messages to a target * {@link WebSocketHandler}. * * <p>Methods in this class allow exceptions from the wrapped {@link WebSocketHandler} to * propagate. However, any exceptions resulting from SockJS message handling (e.g. while * sending SockJS frames or heartbeat messages) are caught and treated as transport * errors, i.e. routed to the * {@link WebSocketHandler#handleTransportError(WebSocketSession, Throwable) * handleTransportError} method of the wrapped handler and the session closed. * * @author Rossen Stoyanchev * @since 4.0 */ public class SockJsWebSocketHandler extends TextWebSocketHandler implements SubProtocolCapable { private final SockJsServiceConfig sockJsServiceConfig; private final WebSocketServerSockJsSession sockJsSession; private final List<String> subProtocols; private final AtomicInteger sessionCount = new AtomicInteger(); public SockJsWebSocketHandler(SockJsServiceConfig serviceConfig, WebSocketHandler webSocketHandler, WebSocketServerSockJsSession sockJsSession) { Assert.notNull(serviceConfig, "serviceConfig must not be null"); Assert.notNull(webSocketHandler, "webSocketHandler must not be null"); Assert.notNull(sockJsSession, "session must not be null"); this.sockJsServiceConfig = serviceConfig; this.sockJsSession = sockJsSession; webSocketHandler = WebSocketHandlerDecorator.unwrap(webSocketHandler); this.subProtocols = ((webSocketHandler instanceof SubProtocolCapable subProtocolCapable) ? new ArrayList<>(subProtocolCapable.getSubProtocols()) : Collections.emptyList()); } @Override public List<String> getSubProtocols() { return this.subProtocols; } protected SockJsServiceConfig getSockJsConfig() { return this.sockJsServiceConfig; } @Override public void afterConnectionEstablished(WebSocketSession wsSession) throws Exception { Assert.state(this.sessionCount.compareAndSet(0, 1), "Unexpected connection"); this.sockJsSession.initializeDelegateSession(wsSession); } @Override public void handleTextMessage(WebSocketSession wsSession, TextMessage message) throws Exception { this.sockJsSession.handleMessage(message, wsSession); } @Override public void afterConnectionClosed(WebSocketSession wsSession, CloseStatus status) throws Exception { this.sockJsSession.delegateConnectionClosed(status); } @Override public void handleTransportError(WebSocketSession webSocketSession, Throwable exception) throws Exception { this.sockJsSession.delegateError(exception); } }
/* * (C) Mississippi State University 2009 * * The WebTOP employs two licenses for its source code, based on the intended use. The core license for WebTOP applications is * a Creative Commons GNU General Public License as described in http://*creativecommons.org/licenses/GPL/2.0/. WebTOP libraries * and wapplets are licensed under the Creative Commons GNU Lesser General Public License as described in * http://creativecommons.org/licenses/*LGPL/2.1/. Additionally, WebTOP uses the same licenses as the licenses used by Xj3D in * all of its implementations of Xj3D. Those terms are available at http://www.xj3d.org/licenses/license.html. */ package org.webtop.x3d.output; import org.web3d.x3d.sai.*; import org.webtop.x3d.AbstractNode; import org.webtop.x3d.NamedNode; import org.webtop.x3d.NodeInputField; import org.webtop.x3d.SAI; /** * <p>Title: X3DWebTOP</p> * * <p>Description: The X3D version of The Optics Project for the Web * (WebTOP)</p> * * <p>Copyright: Copyright (c) 2006</p> * * <p>Company: MSU Department of Physics and Astronomy</p> * * @author Paul Cleveland, Peter Gilbert * @version 0.0 */ public class FloatMatrixNode extends AbstractNode { public static final String SET_POINT="point",SET_COLOR="color"; private final NamedNode node; private final MFVec3f input3; private final MFVec2f input2; private final MFColor inputC; public FloatMatrixNode(SAI sai, NamedNode nn, String event) { node = nn; /*nn contains the geometric property (color, coord, etc.) node.*/ // SFNode sfnode = (SFNode)nn.node; final X3DField input = nn.node.getField(event); if (input == null)throw new IllegalArgumentException("no such event"); //Only one of these will yield non-null: input3 = input instanceof MFVec3f ? (MFVec3f) input : null; input2 = input instanceof MFVec2f ? (MFVec2f) input : null; inputC = input instanceof MFColor ? (MFColor) input : null; if (input3 == null && input2 == null & inputC == null) throw new ClassCastException("Not a float-matrix accepting EventIn"); } public NamedNode getNode() { return node; } public void set(float[][] array) { //Only one of these will ever run: /*I believe that the first argument to setValue should be the number of vec3f values contained in 'array'. [PC]*/ if(array==null) System.out.println("FloatMatrixNode.set()::array is null"); if (input3 != null) input3.setValue(array.length, array); if (input2 != null) input2.setValue(array.length, array); if (inputC != null) inputC.setValue(array.length, array); } }
package com.example.demo.mongodb.model; import java.util.List; public class Preguntas { private String pregunta; private List<String> listaRespuestas; private int respuesta_correcta; private int puntuacion_pregunta; public Preguntas() { } public String getPregunta() { return pregunta; } public void setPregunta(String pregunta) { this.pregunta = pregunta; } public List<String> getListaRespuestas() { return listaRespuestas; } public void setListaRespuestas(List<String> listaRespuestas) { this.listaRespuestas = listaRespuestas; } public int getRespuesta_correcta() { return respuesta_correcta; } public void setRespuesta_correcta(int respuesta_correcta) { this.respuesta_correcta = respuesta_correcta; } public int getPuntuacion_pregunta() { return puntuacion_pregunta; } public void setPuntuacion_pregunta(int puntuacion_pregunta) { this.puntuacion_pregunta = puntuacion_pregunta; } }
package app; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Scanner; public class PersistanceStorage { private static String dimensionsFile = "data/dimensions"; public static void storeDimensions(Dimension dimension) throws IOException { if (dimension != null) { PrintWriter pw = new PrintWriter(new File(dimensionsFile + "_temp")); while (dimension.getParent() != null) dimension = dimension.getParent(); storeAllChildNodes(pw, dimension); pw.flush(); pw.close(); File dims = new File(dimensionsFile); if (dims.exists()) dims.delete(); dims = new File(dimensionsFile + "_temp"); if (dims.exists()) dims.renameTo(new File(dimensionsFile)); } } private static void storeAllChildNodes(PrintWriter fw, Dimension dimension) { if (dimension.getSubDimension().size() == 0) { fw.println(dimension.getId()); return; } for (Dimension subDim : dimension.getSubDimension()) storeAllChildNodes(fw, subDim); } public static Dimension getRootDimension() throws FileNotFoundException { Dimension rootDimension = new Dimension("root"); Scanner sc = new Scanner(new File(dimensionsFile)); while (sc.hasNext()) { String line = sc.nextLine(); Dimension dim = rootDimension; String[] path = line.split("\\."); for (int i = 1; i < path.length; i++) { Dimension matching = dim.getMatchingSubDimension(path[i]); if (matching == null) { matching = dim.addDimension(path[i]); } dim = matching; } } return rootDimension; } }
package io.breen.socrates.model.event; import io.breen.socrates.model.wrapper.SubmittedFileWrapperNode; import io.breen.socrates.util.ObservableChangedEvent; /** * The event that is generated by a SubmittedFileWrapperNode when it changes its "completed" state * --- in other words, if it changes from not complete to complete, or the inverse. */ public class FileCompletedChangeEvent extends ObservableChangedEvent<SubmittedFileWrapperNode> { public final boolean isNowComplete; public FileCompletedChangeEvent(SubmittedFileWrapperNode source, boolean isNowComplete) { super(source); this.isNowComplete = isNowComplete; } @Override public String toString() { return "FileCompletedChangeEvent(source=" + source + ", isNowComplete=" + isNowComplete + ")"; } }
package me.okx.rankup.placeholders; import me.okx.rankup.Rankup; import me.okx.rankup.Utils; import me.okx.rankup.data.Rank; import me.okx.rankup.exception.NotInLadderException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import java.text.DecimalFormat; import java.util.Map; public class Placeholders { public static String onPlaceholderRequest(Player player, String id) { if (player == null) { return ""; } Rankup r = Rankup.getInstance(); FileConfiguration config = r.getConfig(); // map aliases for(Map.Entry<String, String> entry : r.placeholderAliases.entrySet()) { if(id.equalsIgnoreCase(entry.getValue())) { id = entry.getKey(); break; } } if (id.equalsIgnoreCase("player")) { return player.getName(); } if (id.equalsIgnoreCase("current_rank")) { try { return Utils.getRank(player, false).getName(); } catch (NotInLadderException e) { return Utils.getString("placeholders.notInLadder"); } } if (id.equalsIgnoreCase("next_rank")) { try { return Utils.getRank(player, true).getName(); } catch (NotInLadderException e) { return Utils.getString("placeholders.notInLadder"); } catch(ArrayIndexOutOfBoundsException e) { return Utils.getString("placeholders.highestRank"); } } if (id.equalsIgnoreCase("current_rank")) { try { return Utils.getRank(player, false).getName(); } catch (NotInLadderException e) { return Utils.getString("placeholders.notInLadder"); } } if (id.equalsIgnoreCase("next_rank_cost")) { return getCost(player, true); } if (id.equalsIgnoreCase("next_rank_cost_formatted")) { return getRankCost(config, getCost(player, true)); } if (id.equalsIgnoreCase("current_rank_cost")) { return getCost(player, false); } if (id.equalsIgnoreCase("current_rank_cost_formatted")) { return getRankCost(config, getCost(player, false)); } // PRESTIGE START if (id.equalsIgnoreCase("current_prestige_rank")) { try { return Utils.getPrestigeRank(player, false).getName(); } catch (NotInLadderException ignored) { return Utils.getString("placeholders.noPrestigeRank"); } catch(ArrayIndexOutOfBoundsException ignored) { } } if (id.equalsIgnoreCase("next_prestige_rank")) { try { return Utils.getPrestigeRank(player, true).getName(); } catch (NotInLadderException ignored) { return Utils.getString("placeholders.notInLadder"); } catch (ArrayIndexOutOfBoundsException e) { return Utils.getString("placeholders.highestRank"); } } if (id.equalsIgnoreCase("current_prestige_rank_prefix")) { try { return r.chat.getGroupPrefix((String) null, Utils.getPrestigeRank(player, false).getName()); } catch (NotInLadderException e) { return Utils.getString("placeholders.notInLadder"); } } if (id.equalsIgnoreCase("next_prestige_rank_prefix")) { try { return r.chat.getGroupPrefix((String) null, Utils.getPrestigeRank(player, true).getName()); } catch (NotInLadderException e) { return Utils.getString("placeholders.notInLadder"); } catch (ArrayIndexOutOfBoundsException e) { return Utils.getString("placeholders.highestRank"); } } if (id.equalsIgnoreCase("next_prestige_cost")) { return getPrestigeCost(player, true); } if (id.equalsIgnoreCase("next_prestige_cost_formatted")) { return Utils.getShortened(Double.valueOf(getPrestigeCost(player, true))); } // PRESTIGE END if (id.equalsIgnoreCase("percent_done")) { if (isAtLastRank(player)) { return "100"; } double percentLeft = getPercentLeft(player); String s = String.valueOf(100 - percentLeft); if (s.startsWith("-")) { return "0"; } else if (Double.valueOf(s) > 100) { return "100"; } else { return s; } } if (id.equalsIgnoreCase("percent_done_formatted")) { DecimalFormat df = new DecimalFormat(config.getString("placeholders.percentDoneFormat")); if (isAtLastRank(player)) { return df.format(100); } double percentLeft = getPercentLeft(player); String s = df.format(100 - percentLeft); if (s.startsWith("-")) { return df.format(0); } else if (Double.valueOf(s) > 100) { return df.format(100); } else { return s; } } if (id.equalsIgnoreCase("percent_left")) { if (isAtLastRank(player)) { return "0"; } double percentLeft = getPercentLeft(player); String s = String.valueOf(percentLeft); if (s.startsWith("-")) { return "0"; } else { return s; } } if (id.equalsIgnoreCase("percent_left_formatted")) { DecimalFormat df = new DecimalFormat(config.getString("placeholders.percentLeftFormat")); if (isAtLastRank(player)) { return df.format("0"); } double percentLeft = getPercentLeft(player); String s = df.format(percentLeft); if (s.startsWith("-")) { return df.format(0); } else { return s; } } if (id.equalsIgnoreCase("current_rank_prefix")) { try { return r.chat.getGroupPrefix((String) null, Utils.getRank(player, false).getName()); } catch (NotInLadderException e) { return Utils.getString("placeholders.notInLadder"); } } if (id.equalsIgnoreCase("next_rank_prefix")) { try { return r.chat.getGroupPrefix((String) null, Utils.getRank(player, true).getName()); } catch (NotInLadderException e) { return Utils.getString("placeholders.notInLadder"); } catch (IndexOutOfBoundsException e) { return Utils.getString("placeholders.highestRank"); } } return null; } private static double getPercentLeft(Player player) { double percentLeft = 0; try { Rank rank = Utils.getRank(player, true); if (rank != null) { double cost = rank.getCostWithPrestige(player); percentLeft = ((cost - Rankup.getInstance().economy.getBalance(player)) / cost) * 100; } } catch (NotInLadderException ignored) { } return percentLeft; } private static String getRankCost(FileConfiguration config, String rankCost) { DecimalFormat df = new DecimalFormat(config.getString("placeholders.rankCostFormat")); double cost = Double.parseDouble(rankCost); String formatted; if (config.getBoolean("placeholders.useShortening")) { formatted = Utils.getShortened(cost); // if we can't shorten it if(formatted.equals(String.valueOf(cost))) { // just add commas formatted = df.format(cost); } } else { formatted = String.valueOf(cost); } return formatted; } public static boolean isAtLastRank(Player p) { try { return Rankup.getInstance().ranks.get(Rankup.getInstance().ranks.size() - 1).getName() .equals(Utils.getRank(p, false).getName()); } catch (NotInLadderException e) { return false; } } private static String getCost(Player player, boolean next) { try { return String.valueOf(Utils.getRank(player, next).getCostWithPrestige(player)); } catch (NotInLadderException | ArrayIndexOutOfBoundsException e) { return "0"; } } private static String getPrestigeCost(Player player, boolean next) { try { return String.valueOf(Utils.getPrestigeRank(player, next).getCost()); } catch (NotInLadderException | ArrayIndexOutOfBoundsException e) { return "0"; } } }
package com.apap.tugas1_apap.controller; import java.util.HashMap; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.apap.tugas1_apap.model.JabatanModel; import com.apap.tugas1_apap.model.PegawaiModel; import com.apap.tugas1_apap.service.JabatanService; import com.apap.tugas1_apap.service.PegawaiService; @Controller public class JabatanController { @Autowired private JabatanService jabatanService; @Autowired private PegawaiService pegawaiService; @RequestMapping(value="/jabatan/tambah", method = RequestMethod.GET) private String tambah(Model model) { model.addAttribute("jabatan", new JabatanModel()); model.addAttribute("title", "Tambah Jabatan"); return "add-jabatan"; } @RequestMapping(value="/jabatan/tambah", method = RequestMethod.POST) private String tambah(@ModelAttribute JabatanModel jabatan, Model model, RedirectAttributes ra) { jabatanService.addJabatan(jabatan); ra.addFlashAttribute("alert", "alert-green"); ra.addFlashAttribute("alertText", "Data Berhasil Disimpan"); model.addAttribute("title", "Tambah Jabatan"); String link = "redirect:/jabatan/view?idJabatan="+String.valueOf(jabatan.getId()); return link; } @RequestMapping(value="/jabatan/view", method = RequestMethod.GET) private String view(@RequestParam(value="idJabatan") long idJabatan, Model model) { Optional<JabatanModel> jabatan = jabatanService.findJabatanByIdJabatan(idJabatan); if (jabatan.isPresent()) { model.addAttribute("jabatan", jabatan.get()); return "view-jabatan"; } return "notFound"; } @RequestMapping(value="/jabatan/ubah", method = RequestMethod.GET) private String ubah(@RequestParam(value="idJabatan") long idJabatan, Model model) { Optional<JabatanModel> jabatan = jabatanService.findJabatanByIdJabatan(idJabatan); if (jabatan.isPresent()) { model.addAttribute("jabatan", jabatan.get()); model.addAttribute("title", "Ubah Jabatan"); return "ubah-jabatan"; }else { return "notFound"; } } @RequestMapping(value="/jabatan/ubah", method = RequestMethod.POST) private String ubah(@ModelAttribute JabatanModel jabatan, Model model, RedirectAttributes ra) { jabatanService.addJabatan(jabatan); ra.addFlashAttribute("alert", "alert-green"); ra.addFlashAttribute("alertText", "Data Berhasil Disimpan"); String link = "redirect:/jabatan/view?idJabatan="+String.valueOf(jabatan.getId()); return link; } @RequestMapping(value="/jabatan/hapus", method = RequestMethod.POST) private String hapus(@ModelAttribute JabatanModel jabatan, RedirectAttributes ra) { List<PegawaiModel> allPegawai = pegawaiService.findByJabatan(jabatan); if (allPegawai.size() > 0) { ra.addFlashAttribute("alert", "alert-red"); ra.addFlashAttribute("alertText", "Data Tidak Berhasil Dihapus, masih ada pegawainya"); String link = "redirect:/jabatan/view?idJabatan="+String.valueOf(jabatan.getId()); return link; } System.out.println(jabatan.getDeskripsi()); jabatanService.deleteJabatan(jabatan.getId()); ra.addFlashAttribute("alert", "alert-green"); ra.addFlashAttribute("alertText", "Data Berhasil Dihapus"); return "redirect:/"; } @RequestMapping(value="/jabatan/viewall") private String viewall(Model model) { List<JabatanModel> allJabatan = jabatanService.getListJabatan(); HashMap<String, Integer> pegawaiNumOnJabatan = pegawaiService.getPegawaiNumOnJabatan(allJabatan); model.addAttribute("allJabatan", allJabatan); model.addAttribute("pegawaiNumOnJabatan", pegawaiNumOnJabatan); return "viewall-jabatan"; } }
package com.zqs.model.message.e; /** * 手机验证码类别 * * @author qiushi.zhou * @date 2017年7月20日 下午12:52:49 */ public interface EMessageStatus { /** 注册 */ int REGISTER_CODE = 1; /** 忘记密码 */ int FORGET_PWD_CODE = 2; }
package prosjektoppgave.gui; import prosjektoppgave.controller.Controller; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; /** * The main window of the program, that all user-interaction is happening from. */ public class MainWindow extends BaseWindow { // Declare GUI components. private JButton exitButton, houseButton, personButton, contractButton, statsButton, homeButton; private JPanel homePanel, activePanel; private static enum PanelTypes{HOUSING, PERSON, CONTRACT, STATISTICS} private final Controller controller; /** * Lays out the layout of the window. * @param controller The controller used to modify the data-models. */ public MainWindow(Controller controller) { super(controller); this.controller = controller; Container c = getContentPane(); c.setLayout(new BorderLayout()); homeButton = new JButton("Tilbake til hovedmeny"); houseButton = new JButton("Boliger"); personButton = new JButton("Personer"); contractButton = new JButton("Kontrakter"); statsButton = new JButton("Statistikk"); homePanel = new HomePanel(houseButton, personButton, contractButton, statsButton); exitButton = new JButton("Avslutt"); Listener l = new Listener(); homeButton.addActionListener(l); houseButton.addActionListener(l); personButton.addActionListener(l); contractButton.addActionListener(l); exitButton.addActionListener(l); statsButton.addActionListener(l); //heading = new JLabel(PROGRAM_NAME); //c.add(heading, BorderLayout.PAGE_START); c.add(homePanel, BorderLayout.CENTER); c.add(exitButton, BorderLayout.PAGE_END); setDefaultCloseOperation(DISPOSE_ON_CLOSE); } /** * Returns to the homeview. */ public void setToHome(){ getContentPane().remove(activePanel); getContentPane().remove(homeButton); getContentPane().add(homePanel, BorderLayout.CENTER); activePanel = null; revalidate(); repaint(); } /** * Creates a new panel, and sets the window to show this panel. * @param panelType The type of panel to be created and shown. */ public void setToPanel(PanelTypes panelType){ switch(panelType){ case HOUSING: activePanel = new HousingListContainerPanel(getController()); break; case PERSON: activePanel = new PersonListContainerPanel(getController()); break; case CONTRACT: activePanel = new ContractContainerPanel(getController()); break; case STATISTICS: activePanel = new StatisticsPanel(getController()); break; } getContentPane().remove(homePanel); getContentPane().add(homeButton, BorderLayout.PAGE_START); getContentPane().add(activePanel, BorderLayout.CENTER); revalidate(); repaint(); } public void saveToFileOnClose(final String path) { this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent event) { try { MainWindow.this.controller.save(path); } catch (IOException ioe) { JOptionPane.showMessageDialog(MainWindow.this, "Kunne ikke lagre programdata!\n" + ioe.toString(), "Kritisk programfeil", JOptionPane.ERROR_MESSAGE); } } }); } private class Listener implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getSource() == homeButton){ setToHome(); } else if (e.getSource() == houseButton) { setToPanel(PanelTypes.HOUSING); } else if (e.getSource() == personButton) { setToPanel(PanelTypes.PERSON); } else if(e.getSource() == contractButton){ setToPanel(PanelTypes.CONTRACT); } else if (e.getSource() == statsButton) { setToPanel(PanelTypes.STATISTICS); } else if (e.getSource() == exitButton) { // Lukk vinduet slik at saveToFileOnClose kalles. // Basert på eksempel fra http://stackoverflow.com/a/5454119 Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( new WindowEvent(MainWindow.this, WindowEvent.WINDOW_CLOSING) ); } } } }
/** * This code compares version number * Problem statment: Compare two version numbers version1 and version2. 1. If version1 > version2 return 1, 2. If version1 < version2 return -1, 3. otherwise return 0. Reference: https://github.com/varunu28/InterviewBit-Java-Solutions/blob/master/Strings/Compare%20Version%20Numbers.java https://www.tutorialspoint.com/java/number_compareto.htm Example: 0.1 < 1.1 < 1.2 < 1.13 < 1.13.4 1.30 < 1.351 1.30 < 1.32 1.30 < 1.15.1 1.30 < 2.15 10.15 < 12.10 Java – String compareTo() Method example. The method compareTo() is used for comparing two strings lexicographically. */ public class CompareVersionNumber { // function to check version number public static int compareVersion(String str1, String str2) { String[] arrA = str1.split("\\."); String[] arrB = str2.split("\\."); int length = Math.max(arrA.length, arrB.length); for (int i = 0; i < length; i++) { // to cover scenario 1.30 < 1.1.5.1 if (i < arrA.length && i < arrB.length) { // do not forget this. very important if (arrA[i].length() > arrB[i].length()) return 1; else if (arrA[i].length() < arrB[i].length()) return -1; } Long n1 = i < arrA.length ? Long.parseLong(arrA[i]) : 0; Long n2 = i < arrB.length ? Long.parseLong(arrB[i]) : 0; int comp = n1.compareTo(n2); if (comp != 0) return comp; } return 0; } // main method public static void main(String args[]) { String str2 = "1.30"; String str1 = "1.15.1"; int result = compareVersion(str1, str2); System.out.println(result); } }
/* ComplexRuleTemplate -- a class within the Cellular Automaton Explorer. Copyright (C) 2005 David B. Bahr (http://academic.regis.edu/dbahr/) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package cellularAutomata.rules.templates; import javax.swing.JOptionPane; import cellularAutomata.Cell; import cellularAutomata.cellState.model.CellState; import cellularAutomata.cellState.model.ComplexState; import cellularAutomata.cellState.view.CellStateView; import cellularAutomata.cellState.view.ComplexModulusView; import cellularAutomata.rules.Rule; import cellularAutomata.util.math.Complex; /** * A convenience class/template for any rules that need cell states based on a * complex number. (In other words, this class uses the cell state * cellularAutomaton.cellState.model.ComplexState.) * <p> * This class uses the Template Method design pattern. Subclasses implement the * abstract methods complexRule(), getAlternateState(), getEmptyState(), and * getFullState() which are called by the template method calculateNewState(). * * @author David Bahr */ public abstract class ComplexRuleTemplate extends Rule { /** * Create a rule based on cells that use an Object for a state value. * <p> * When building child classes, the minimalOrLazyInitialization parameter * must be included but may be ignored. However, the boolean is intended to * indicate when the child's constructor should build a rule with as small a * footprint as possible. In order to load rules by reflection, the * application must query the child classes for information like their * display names, tooltip descriptions, etc. At these times it makes no * sense to build the complete rule which may have a large footprint in * memory. * <p> * It is recommended that the child's constructor and instance variables do * not initialize any variables and that variables be initialized only when * first needed (lazy initialization). Or all initializations in the * constructor may be placed in an <code>if</code> statement. * * <pre> * if(!minimalOrLazyInitialization) * { * ...initialize * } * </pre> * * @param minimalOrLazyInitialization * When true, the constructor instantiates an object with as * small a footprint as possible. When false, the rule is fully * constructed. If uncertain, set this variable to false. */ public ComplexRuleTemplate(boolean minimalOrLazyInitialization) { super(minimalOrLazyInitialization); // check for error if(getAlternateState() == null) { // Failed because the state can't be null String warning = "For any child class of ComplexRuleTemplate, \n" + "the alternate state cannot be null."; JOptionPane.showMessageDialog(null, warning, "Developer Warning", JOptionPane.WARNING_MESSAGE); } else if(getEmptyState() == null) { // Failed because the state can't be null String warning = "For any child class of ComplexRuleTemplate, \n" + "the empty state cannot be null."; JOptionPane.showMessageDialog(null, warning, "Developer Warning", JOptionPane.WARNING_MESSAGE); } else if(getFullState() == null) { // Failed because the state can't be null String warning = "For any child class of ComplexRuleTemplate, \n" + "the full state cannot be null."; JOptionPane.showMessageDialog(null, warning, "Developer Warning", JOptionPane.WARNING_MESSAGE); } } /** * Creates a new ComplexState based on a complex number provided by the * method complexRule(). The method complexRule() is where the actual CA * rule is written. <br> * By convention the neighbors should be indexed clockwise starting to the * northwest of the cell. * * @see cellularAutomata.rules.Rule#calculateNewState(cellularAutomata.Cell, * cellularAutomata.Cell[]) */ public CellState calculateNewState(Cell cell, Cell[] neighbors) { // the current generation int generation = cell.getGeneration(); // get the state for the cell Complex cellObject = (Complex) cell.getState(generation).getValue(); // get the state for each neighbor Complex[] neighborObjects = new Complex[neighbors.length]; for(int i = 0; i < neighbors.length; i++) { neighborObjects[i] = (Complex) neighbors[i].getState(generation) .getValue(); } // apply the rule that gives a cell state as a complex number. Complex cellState = complexRule(cellObject, neighborObjects, generation); // create a new state from the value returned by objectRule ComplexState state = new ComplexState(cellState, getAlternateState(), getEmptyState(), getFullState()); return state; } /** * Gets a complex number that represents the alternate state (a state that * is drawn with a right mouse click). If no alternate state is desired, * recommended to return getEmptyState()). Implementations should be careful * to return a new instance each time this is called. Otherwise, multiple CA * cells may be sharing the same instance and a change to one cell could * change many cells. * * @return The alternate state. */ public abstract Complex getAlternateState(); /** * @see cellularAutomata.rules.Rule#getCompatibleCellState() */ public final CellState getCompatibleCellState() { return new ComplexState(getEmptyState(), getAlternateState(), getEmptyState(), getFullState()); } /** * Gets an instance of the CellStateView class that will be used to display * cells being updated by this rule. Note: This method must return a view * that is able to display cell states of the type returned by the method * getCompatibleCellState(). Appropriate CellStatesViews to return include * BinaryCellStateView, IntegerCellStateView, HexagonalIntegerCellStateView, * IntegerVectorArrowView, IntegerVectorDefaultView, and * RealValuedDefaultView among others. the user may also create their own * views (see online documentation). * <p> * Any values passed to the constructor of the CellStateView should match * those values needed by this rule. * * @return An instance of the CellStateView (any values passed to the * constructor of the CellStateView should match those values needed * by this rule). */ public CellStateView getCompatibleCellStateView() { return new ComplexModulusView(getEmptyState(), getFullState()); } /** * A list of lattices with which this Rule will work; in this case, returns * all lattices by default, though child classes may wish to override this * and restrict the lattices with which the child rule will work. <br> * Well-designed Rules should work with any lattice, but some may require * particular topological or geometrical information (like the lattice gas). * Appropriate strings to return in the array include * SquareLattice.DISPLAY_NAME, HexagonalLattice.DISPLAY_NAME, * StandardOneDimensionalLattice.DISPLAY_NAME, etc. If null, will be * compatible with all lattices. * * @return A list of lattices compatible with this Rule (returns the display * names for the lattices). Returns null if compatible with all * lattices. */ public String[] getCompatibleLattices() { // String[] lattices = {SquareLattice.DISPLAY_NAME, // HexagonalLattice.DISPLAY_NAME, // StandardOneDimensionalLattice.DISPLAY_NAME, // TriangularLattice.DISPLAY_NAME, // TwelveNeighborTriangularLattice.DISPLAY_NAME, // FourNeighborSquareLattice.DISPLAY_NAME}; return null; } /** * Gets a complex number that represents the empty state. This value is * intended to represent the minimum possible modulus. So if the returned * value is value is 0+i, then the intention is that the maximum possible * modulus allowed in this rule will be mod(0+i) or 1.0. However, every rule * is free to ignore or interpret this value as desired. (For example, in * some cases it may be simpler to interpret the value as the minimum real * and imaginary values respectively -- effectively a square in the complex * plane instead of a circle.) Together with getFullState(), these two * methods define an annulus or ring of acceptable complex values. * <p> * Implementations should be careful to return a new instance each time this * is called. Otherwise, multiple CA cells may be sharing the same instance * and a change to one cell could change many cells. * * @return The empty state. */ public abstract Complex getEmptyState(); /** * Gets a complex number that represents the full or filled state. This * value is intended to represent the maximum possible modulus. So if the * returned value is value is 1+i, then the intention is that the maximum * possible modulus allowed in this rule will be mod(1+i) or sqrt(2). * However, every rule is free to ignore or interpret this value as desired. * (For example, in some cases it may be simpler to interpret the value as * the maximum real and imaginary values respectively -- effectively a * square in the complex plane instead of a circle.) Together with * getEmptyState(), these two methods define an annulus or ring of * acceptable complex values. * <p> * Implementations should be careful to return a new instance each time this * is called. Otherwise, multiple CA cells may be sharing the same instance * and a change to one cell could change many cells. * * @return The full state. */ public abstract Complex getFullState(); /** * The rule for the cellular automaton which will be a function of the cell * and its neighbors. The cell and its neighbors are complex numbers. <br> * By convention the neighbors' geometry should be indexed clockwise * starting to the northwest of the cell. * * @param cellValue * The current value of the cell being updated. * @param neighborValues * The current values of each neighbor. In other words, the array * index is the number of the neighbor. By convention the * neighbors' geometry should be indexed clockwise starting to * the northwest of the cell. * @param generation * The current generation of the CA. * @return A new state for the cell which may be any complex number. */ protected abstract Complex complexRule(Complex cellValue, Complex[] neighborValues, int generation); }
package com.wannabe.ontop; public class Map { private String[] MAP = new String [] { "............", "............", "............", "............", "............", "------------", "############" }; private int height; private int width; public Map() { height = MAP.length; width = MAP[0].length(); } public int getHeight() { return height; } public int getWidth() { return width; } public boolean hasGroundAt(int r, int c) { return MAP[r].charAt(c) == '#'; } public boolean hasGrassAt(int r, int c) { return MAP[r].charAt(c) == '-'; } }
package com.iodgram.smsticket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.preference.PreferenceManager; public class Utils { public static String[] gAlphabet = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; public static String getNews(Activity context) { try { String version = getVersion(context); String sId = PreferenceManager.getDefaultSharedPreferences(context) .getString("uniqid", "NaN"); String url = "http://smsticket.fejkbiljett.com/" + version + "/getnews?id=" + sId; HttpURLConnection conn = (HttpURLConnection) new URL(url) .openConnection(); BufferedReader br = new BufferedReader(new InputStreamReader( conn.getInputStream())); char[] buf = new char[1024]; int read = br.read(buf, 0, 1024); if (read < 0) { return null; } String str = new String(buf); return str.substring(0, read); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public static String generateRandomString() { return Utils.generateRandomString(9, false); } public static String generateRandomString(int length, boolean bLetters) { String letters = ""; for (int i = 0; i < length; i++) { if (bLetters == true && Math.random() > 0.5) { letters += gAlphabet[(int) Math.floor(Math.random() * 26)]; } else { letters += Math.round(Math.random() * 9); } } return letters; } public static void showAlert(Activity activity, String title, String message) { Utils.showAlert(activity, title, message, "OK!"); } public static void showAlert(Activity activity, String title, String message, String button) { new AlertDialog.Builder(activity) .setTitle(title) .setMessage(message) .setNeutralButton(button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }).show(); } public static String getVersion(Activity context) { String version = ""; try { version = context.getPackageManager().getPackageInfo( context.getPackageName(), 0).versionName; } catch (NameNotFoundException e) { e.printStackTrace(); } return version; } }
package net.leloubil.mcpwn.carvinglabs; import com.google.gson.annotations.SerializedName; import lombok.Getter; import java.util.ArrayList; import java.util.Date; @Getter public class CLReward { @SerializedName("burnProducts") public ArrayList<CLProduct> burnProducts = new ArrayList<>(); @SerializedName("channels") public ArrayList<String> channels = new ArrayList<>(); @SerializedName("consumption") public ArrayList<CLConsumption> consumption = new ArrayList<>(); @SerializedName("createdAt") public Date createdAt; @SerializedName("expiresAt") public Date expiresAt; @SerializedName("id") public Long id; @SerializedName("membershipId") public Long membershipId; @SerializedName("nbPoints") public Long nbPoints; @SerializedName("restaurants") public ArrayList<String> restaurants = new ArrayList<>(); @SerializedName("usedAt") public Date usedAt; }
package com.altmedia.billboard.service; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import com.altmedia.billboard.entity.Listing; import com.amazonaws.auth.DefaultAWSCredentialsProviderChain; import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper; import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBScanExpression; import com.amazonaws.services.dynamodbv2.datamodeling.S3Link; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.util.IOUtils; public class ListingService { private DynamoDBMapper mapper; private String bucketName; private static final ListingService instance = new ListingService(); public static ListingService getInstance() { return instance; } private ListingService() { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); mapper = new DynamoDBMapper(client, new DefaultAWSCredentialsProviderChain()); bucketName = System.getenv("IMAGES_BUCKET_NAME") == null ? "billboard-images-whitebid-use1" : System.getenv("IMAGES_BUCKET_NAME"); } public void create(Listing listing) { mapper.save(listing); } public URL storeImageInS3(InputStream imageInput, String fileName, String listingId) throws IOException { try { S3Link s3Link = mapper.createS3Link(System.getenv("AWS_REGION"), bucketName, listingId + "/" + fileName); s3Link.uploadFrom(IOUtils.toByteArray(imageInput)); return s3Link.getUrl(); } finally { imageInput.close(); } } public Listing retrieve(String listingId) { return mapper.load(Listing.class, listingId); } public void update(Listing listing) { mapper.save(listing); } public void delete(String listingId) { Listing listing = new Listing(); listing.setId(listingId); mapper.delete(listing); } public List<Listing> getAllListings() { return mapper.scan(Listing.class, new DynamoDBScanExpression()); } public List<Listing> getListingsByUserId(String userId) { Map<String, AttributeValue> eav = new HashMap<String, AttributeValue>(); eav.put(":val1", new AttributeValue().withS(userId)); DynamoDBScanExpression queryExpression = new DynamoDBScanExpression() .withFilterExpression("CreatedById = :val1").withExpressionAttributeValues(eav); return mapper.scan(Listing.class, queryExpression); } }
package com.zarokima.mastersproject.game; import java.util.ArrayList; import org.andengine.engine.handler.IUpdateHandler; import org.andengine.entity.scene.Scene; import org.andengine.entity.sprite.AnimatedSprite; import org.andengine.extension.physics.box2d.PhysicsConnector; import org.andengine.extension.physics.box2d.PhysicsFactory; import org.andengine.extension.physics.box2d.PhysicsWorld; import org.andengine.opengl.texture.TextureManager; import org.andengine.opengl.texture.TextureOptions; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.andengine.opengl.texture.region.TiledTextureRegion; import org.andengine.opengl.vbo.VertexBufferObjectManager; import android.content.Context; import android.graphics.Point; import android.graphics.PointF; import android.util.Log; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.physics.box2d.Body; import com.badlogic.gdx.physics.box2d.BodyDef.BodyType; import com.badlogic.gdx.physics.box2d.FixtureDef; import com.zarokima.mastersproject.util.GravityHelper; import com.zarokima.mastersproject.util.ICollidable; import com.zarokima.mastersproject.util.PhysicsWorldHelper; import com.zarokima.mastersproject.util.SceneHelper; import com.zarokima.mastersproject.util.UserData; public class Character implements ICollidable { protected AnimatedSprite sprite; protected Body body; protected BitmapTextureAtlas textureAtlas; protected TiledTextureRegion textureRegion; protected FixtureDef fixtureDef = PhysicsFactory.createFixtureDef(1, 0f, 0.7f); protected float moveSpeed = 5; protected float jumpForce = -7.5f; protected IUpdateHandler movementHandler; protected boolean grounded; protected UserData userData; protected ArrayList<Body> touchingGrounds; protected GameActivity context; // ============== // |Constructors| // ============== public Character(Context c, PointF p, TextureManager textureManager, String path, VertexBufferObjectManager vbom) { PhysicsWorld physicsWorld = PhysicsWorldHelper.GetPhysicsWorld(); context = (GameActivity) c; touchingGrounds = new ArrayList<Body>(); textureAtlas = new BitmapTextureAtlas(textureManager, 64, 64, TextureOptions.BILINEAR); textureAtlas.load(); textureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(textureAtlas, c, path, 0, 0, 2, 1); sprite = new AnimatedSprite(p.x, p.y, textureRegion, vbom); sprite.animate(new long[] { 200, 200 }, 0, 1, true); body = PhysicsFactory.createBoxBody(physicsWorld, sprite, BodyType.DynamicBody, fixtureDef); physicsWorld.registerPhysicsConnector(new PhysicsConnector(sprite, body, true, true)); sprite.setUserData(body); if (userData == null) userData = new UserData(); userData.isCharacter = true; userData.container = this; body.setUserData(userData); SceneHelper.GetScene().attachChild(sprite); grounded = true; } // ========= // |Getters| // ========= public AnimatedSprite getSprite() { return sprite; } public Body getBody() { return body; } public PointF getPosition() { return new PointF(sprite.getX(), sprite.getY()); } public BitmapTextureAtlas getTextureAtlas() { return textureAtlas; } public TiledTextureRegion getTextureRegion() { return textureRegion; } // ========= // |Setters| // ========= public void setTextureAtlas(BitmapTextureAtlas textureAtlas) { this.textureAtlas = textureAtlas; } public void setTiledTextureRegion(TiledTextureRegion textureRegion) { this.textureRegion = textureRegion; } public void setPosition(float x, float y) { sprite.setPosition(x, y); } public void setPosition(Point p) { sprite.setPosition(p.x, p.y); } // ========= // |Methods| // ========= public void MoveLeft(Scene scene) { scene.unregisterUpdateHandler(movementHandler); movementHandler = new IUpdateHandler() { @Override public void onUpdate(float pSecondsElapsed) { Vector2 current = GravityHelper.CalculateUnRotatedVelocity(body.getLinearVelocity()); Vector2 velocity = GravityHelper.CalculateDirectionalVelocity(new Vector2(-moveSpeed, current.y)); body.setLinearVelocity(velocity); } @Override public void reset() { // TODO Auto-generated method stub } }; scene.registerUpdateHandler(movementHandler); } public void MoveRight(Scene scene) { scene.unregisterUpdateHandler(movementHandler); movementHandler = new IUpdateHandler() { @Override public void onUpdate(float pSecondsElapsed) { Vector2 current = GravityHelper.CalculateUnRotatedVelocity(body.getLinearVelocity()); Vector2 velocity = GravityHelper.CalculateDirectionalVelocity(new Vector2(moveSpeed, current.y)); body.setLinearVelocity(velocity); } @Override public void reset() { // TODO Auto-generated method stub } }; scene.registerUpdateHandler(movementHandler); } public void StopMovement(Scene scene) { scene.unregisterUpdateHandler(movementHandler); Vector2 current = GravityHelper.CalculateUnRotatedVelocity(body.getLinearVelocity()); Vector2 velocity = GravityHelper.CalculateDirectionalVelocity(new Vector2(0, current.y)); body.setLinearVelocity(velocity); } public void Jump() { if(!grounded) return; Vector2 current = GravityHelper.CalculateUnRotatedVelocity(body.getLinearVelocity()); Vector2 velocity = GravityHelper.CalculateDirectionalVelocity(new Vector2(current.x, jumpForce)); body.setLinearVelocity(velocity); } public void UpdateRotation() { if (!grounded) { body.setTransform(body.getPosition(), (float) Math.toRadians(180 - GravityHelper.GetGravityAngle())); } } public void die() { final Character character = this; context.runOnUpdateThread(new Runnable() { @Override public void run() { character.sprite.detachSelf(); Body body = character.body; PhysicsWorld physicsWorld = PhysicsWorldHelper.GetPhysicsWorld(); physicsWorld.unregisterPhysicsConnector(physicsWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(character.getSprite())); physicsWorld.destroyBody(body); } }); SceneHelper.GetScene().unregisterUpdateHandler(movementHandler); } @Override public void beginCollideWith(Body other) { UserData ud = (UserData) other.getUserData(); Vector2 relativeLocation = body.getLocalPoint(other.getWorldCenter()); if(ud.killOnContact) { die(); return; } if (ud.isGround && relativeLocation.y > 0) { grounded = true; if(!touchingGrounds.contains(other)) { touchingGrounds.add(other); } } } @Override public void endCollideWith(Body other) { UserData ud = (UserData) other.getUserData(); if (ud.isGround) { touchingGrounds.remove(other); grounded = !touchingGrounds.isEmpty(); } } }
package com.najasoftware.fdv.service; import android.content.Context; import android.util.Log; import com.najasoftware.fdv.model.Parametro; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import livroandroid.lib.utils.FileUtils; /** * Created by Lemoel Marques - NajaSoftware on 02/05/2016. * lemoel@gmail.com */ public class ParametroService { private static final boolean LOG_ON = false; private static final String TAG = "ProdutoService"; public static Parametro getParametros(Context context) throws IOException { try { String fileName = String.format("parametros_fdv.json"); Log.d(TAG,"Abrindo arquivo: " + fileName); //Lê o arquivo da memoria interna String json = FileUtils.readFile(context,fileName,"UTF-8"); if(json == null) { Log.d(TAG,"Arquivo " + fileName + " Não encontrado"); return null; } Parametro parametro = parserJson(context,json); return parametro; } catch (Exception e) { Log.e(TAG, "Erro ao ler os produtos: " + e.getMessage(),e); return null; } } public static Parametro parserJson(Context context,String json) throws IOException { Parametro parametro = new Parametro(); try { JSONObject root = new JSONObject(json); JSONObject obj = root.getJSONObject("configuracoes"); //Lê informações de cada produto parametro.setVerTodosClientes(obj.optBoolean("ContrVend")); if (LOG_ON) { Log.d(TAG, "Parametros " + parametro.isVerTodosClientes()); } } catch (JSONException e) { Log.d(TAG,e.getMessage() + " Parametros "); throw new IOException(e.getMessage(),e); } return parametro; } }
package com.example.security; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import com.example.dao.UserInfoDao; public class CustomUserDetailsService implements UserDetailsService { //@Autowired //数据库服务类 //private SUserService suserService; @Override public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException { SecurityUser user =new UserInfoDao().getDatabase(userName); System.out.println(userName); if (user==null) { throw new UsernameNotFoundException("UserName " + userName + " not found"); } SecurityUser securityUser = new SecurityUser(user.getId(),user.getUsername(), user.getPassword().toLowerCase(),user.isEnabled(),getAuthorities(user.getAccess())); System.out.println(securityUser); return securityUser; } /** * 获得访问角色权限 * @param access * @return */ public Collection<GrantedAuthority> getAuthorities(Integer access) { List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(2); authList.add(new SimpleGrantedAuthority("ROLE_USER")); if (access.compareTo(1) == 0) { authList.add(new SimpleGrantedAuthority("ROLE_ADMIN")); } return authList; } }
package com.openfarmanager.android.fragments; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.RadioGroup; import com.openfarmanager.android.R; import com.openfarmanager.android.utils.ParcelableWrapper; import static com.openfarmanager.android.utils.Extensions.tryParse; public class EditViewGotoDialog extends EditViewDialog { public static final int GOTO_LINE_POSITION = 0; public static final int GOTO_PERSENTS = 1; @Override protected void restoreSettings(View view) { } @Override protected void saveSettings(View view) { } @Override protected int getLayout() { return R.layout.dialog_edit_view_goto; } @Override protected void handleAction(View view) { int position = tryParse(((EditText) view.findViewById(R.id.go_to)).getText().toString(), 0); RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.go_to_type); int checkedType = radioGroup.getCheckedRadioButtonId(); getListener().goTo(position, checkedType == R.id.line_number ? GOTO_LINE_POSITION : GOTO_PERSENTS); } public static EditViewGotoDialog newInstance(EditViewDialog.EditDialogListener listener) { EditViewGotoDialog dialog = new EditViewGotoDialog(); Bundle args = new Bundle(); args.putParcelable("listener", new ParcelableWrapper<EditDialogListener>(listener)); dialog.setArguments(args); return dialog; } }
package com.explore.service.Impl; import com.explore.common.ServerResponse; import com.explore.dao.*; import com.explore.pojo.*; import com.explore.service.IManageService; import com.explore.dao.QuartersMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; @Service public class ManageServiceImpl implements IManageService { @Autowired StudentMapper studentMapper; @Autowired CoachMapper coachMapper; @Autowired StaffMapper staffMapper; @Autowired CampusMapper campusMapper; @Autowired SubjectMapper subjectMapper; @Autowired QuartersMapper quartersMapper; @Override public ServerResponse<Staff> login(String name, String password) { Staff staff = staffMapper.login(name,password); if(staff==null){ return ServerResponse.createByErrorMessage("用户名或密码错误"); } return ServerResponse.createBySuccessMessage("登陆成功",staff); } @Override public ServerResponse revise(String name, String oldPassword, String newPassword) { Staff staff = staffMapper.login(name,oldPassword); if(staff==null) return ServerResponse.createByErrorMessage("密码输入错误"); staff.setPassword(newPassword); int count = staffMapper.updateByPrimaryKeySelective(staff); if(count==1) return ServerResponse.createBySuccessMessage("修改成功"); return ServerResponse.createByErrorMessage("修改失败"); } @Override public ServerResponse Students() { List<HashMap<String,Object>> allData=new ArrayList<>(); List<Student> students = studentMapper.getAllStudent(); for(int i=0;i<students.size();i++){ Campus campus = campusMapper.selectByPrimaryKey(students.get(i).getCampusId()); Coach coach = coachMapper.selectByPrimaryKey(students.get(i).getCoachId()); HashMap<String,Object> data=new HashMap<>(); data.put("student",students.get(i)); data.put("campus",campus); data.put("coach",coach); allData.add(data); } return ServerResponse.createBySuccess(allData); } @Override public ServerResponse addStudent(Student student) { Student student1 = studentMapper.getiIdCard(student.getIdcard()); if(student1==null) { int count = studentMapper.insert(student); if(count==1) { return ServerResponse.createBySuccessMessage("学生增加成功"); } return ServerResponse.createByErrorMessage("学生增加失败"); } return ServerResponse.createByErrorMessage("学生相同"); } @Override public ServerResponse outStudent(Integer id) { int count = studentMapper.deleteByPrimaryKey(id); if(count==1) return ServerResponse.createBySuccessMessage("学生删除成功"); return ServerResponse.createByErrorMessage("学生删除失败"); } @Override public ServerResponse reviseStudent(Student student) { int count = studentMapper.updateByPrimaryKeySelective(student); if(count==1) return ServerResponse.createBySuccessMessage("学生修改成功"); return ServerResponse.createByErrorMessage("学生修改失败"); } @Override public ServerResponse Coaches() { List<HashMap<String,Object>> allData=new ArrayList<>(); List<Coach> coaches= coachMapper.getAllCoach(); for(int i=0;i<coaches.size();i++){ Campus campus = campusMapper.selectByPrimaryKey(coaches.get(i).getCampusId()); HashMap<String,Object> data=new HashMap<>(); data.put("coach",coaches.get(i)); data.put("campus",campus); allData.add(data); } // for (Coach coach : coaches) { // // } return ServerResponse.createBySuccess(allData); } @Override public ServerResponse addCoach(Coach coach) { Date creat_time = new Date(); coach.setCreateTime(creat_time); coach.setUpdateTime(creat_time); int count = coachMapper.insert(coach); if(count==1) return ServerResponse.createBySuccessMessage("教练增加成功"); return ServerResponse.createByErrorMessage("教练增加失败"); } @Override public ServerResponse outCoach(Integer id) { int count=coachMapper.deleteByPrimaryKey(id); if(count==1) return ServerResponse.createBySuccessMessage("教练删除成功"); return ServerResponse.createByErrorMessage("教练删除失败"); } @Override public ServerResponse reviseCoach(Coach coach) { Date update_time = new Date(); coach.setUpdateTime(update_time); int count = coachMapper.updateByPrimaryKeySelective(coach); if(count==1) return ServerResponse.createBySuccessMessage("教练修改成功"); return ServerResponse.createByErrorMessage("教练修改失败"); } @Override public ServerResponse showAllCampus() { List<Campus> campuses = campusMapper.getAllCampus(); return ServerResponse.createBySuccess(campuses); } @Override public ServerResponse showAllSubject() { List<Subject> subjects = subjectMapper.showSubject(); return ServerResponse.createBySuccess(subjects); } @Override public ServerResponse showStudents(Student student) { List<HashMap<String,Object>> allData=new ArrayList<>(); List<Student> students = studentMapper.showStudents(student); for(int i=0;i<students.size();i++){ Campus campus = campusMapper.selectByPrimaryKey(students.get(i).getCampusId()); Coach coach = coachMapper.selectByPrimaryKey(students.get(i).getCoachId()); Quarters quarters = quartersMapper.selectByPrimaryKey(students.get(i).getQuarterId()); HashMap<String,Object> data=new HashMap<>(); data.put("student",students.get(i)); data.put("campus",campus); data.put("coach",coach); data.put("quarters",quarters); allData.add(data); } return ServerResponse.createBySuccess(allData); } }
/** * Copyright (c) 2004-2021 All Rights Reserved. */ package com.adomy.mirpc.samples.simple.consumer; import java.util.concurrent.TimeUnit; import com.adomy.mirpc.core.remoting.invoker.MiRpcInvokerFactory; import com.adomy.mirpc.core.remoting.invoker.enums.InvokeTypeEnum; import com.adomy.mirpc.core.remoting.invoker.reference.MiRpcReferenceBean; import com.adomy.mirpc.core.remoting.invoker.router.enums.LoadBalanceEnum; import com.adomy.mirpc.core.remoting.network.impl.netty.client.NettyMiRpcClient; import com.adomy.mirpc.core.serialize.impl.HessianMiRpcSerializer; import com.adomy.mirpc.samples.simple.api.DemoDTO; import com.adomy.mirpc.samples.simple.api.DemoService; /** * @author adomyzhao * @version $Id: ConsumerApplication.java, v 0.1 2021年03月24日 5:27 PM adomyzhao Exp $ */ public class ConsumerApplication { public static void main(String[] args) throws Exception { MiRpcReferenceBean referenceBean = new MiRpcReferenceBean(); referenceBean.setClientClass(NettyMiRpcClient.class); referenceBean.setSerializerClass(HessianMiRpcSerializer.class); referenceBean.setInvokeType(InvokeTypeEnum.SYNC); referenceBean.setLoadBalance(LoadBalanceEnum.RANDOM); referenceBean.setInterfaceClass(DemoService.class); referenceBean.setServiceVersion("DEFAULT"); referenceBean.setRemoteAddress("127.0.0.1:5200"); referenceBean.setTimeout(3000); DemoService object = (DemoService) referenceBean.getObject(); DemoDTO dto = object.test("hhhhhh"); System.out.println(dto); TimeUnit.SECONDS.sleep(20); MiRpcInvokerFactory.getInstance().stop(); } }
package br.edu.com.entities; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class Atividade { @Id @GeneratedValue private Long id; private String Descricao; @ManyToOne private Disciplina disciplina; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getDescricao() { return Descricao; } public void setDescricao(String descricao) { Descricao = descricao; } public Disciplina getDisciplina() { return disciplina; } public void setDisciplina(Disciplina disciplina) { this.disciplina = disciplina; } }
package com.gxtc.huchuan.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.widget.ImageView; import android.widget.TextView; import com.gxtc.commlibrary.base.BaseRecyclerAdapter; import com.gxtc.commlibrary.base.BaseRecyclerTypeAdapter; import com.gxtc.commlibrary.helper.ImageHelper; import com.gxtc.huchuan.R; import com.gxtc.huchuan.bean.VisitorBean; import com.gxtc.huchuan.utils.DateUtil; import java.util.List; /** * Created by zzg on 2018/3/20 . */ public class StatisticVisitorAdapter extends BaseRecyclerAdapter<VisitorBean> { public StatisticVisitorAdapter(Context mContext, List<VisitorBean> mDatas, int resId) { super(mContext, mDatas, resId); } @Override public void bindData(ViewHolder holder, int position, VisitorBean visitorBean) { holder.setText(R.id.viditor_count,"访客:"+visitorBean.getCount()); holder.setText(R.id.time,visitorBean.getDateName()); } }
package com.rohraff.netpccontactapp.mapper; import com.rohraff.netpccontactapp.model.Contact; import com.rohraff.netpccontactapp.model.ContactDao; import org.apache.ibatis.annotations.*; import java.util.List; import java.util.Optional; @Mapper public interface ContactMapper { @Insert("INSERT INTO CONTACTS (firstname, lastname, email, key, password, phoneNumber, dateOfBirth) VALUES(#{firstname}, #{lastname}, #{email}, #{key}, #{password}, #{phoneNumber}, #{dateOfBirth})") @Options(useGeneratedKeys = true, keyProperty = "contactId") int insertContacts(ContactDao contact); @Select("SELECT * FROM CONTACTS") List<Contact> getContacts(); @Delete("DELETE FROM CONTACTS WHERE contactId = #{contactId}") void deleteContact(int contactId); @Update("UPDATE CONTACTS SET firstname=#{firstname}, lastname=#{lastname}, email=#{email}, password=#{password}, phoneNumber=#{phoneNumber} where contactId =#{contactId}") void updateContacts(ContactDao contact); @Select("SELECT EMAIL FROM CONTACTS") List<String> getAllEmailAddresses(); @Select("SELECT EMAIL FROM CONTACTS WHERE contactId = #{contactId}") String getEmail(int contactId); }
package br.com.kessel.test; import br.com.kessel.controller.LevelController; public class TestClassLevel { public static void main(String[] args) { LevelController lc = new LevelController(); lc.read(); } }
package selenium_web.Practice; import org.junit.jupiter.api.Test; //import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class StartSelenium { @Test public void startSelenium() { WebDriver webDriver = new ChromeDriver(); webDriver.get("https://home.testing-studio.com/"); webDriver.findElement(By.xpath("//span[contains(text(),'登录')]")).click(); } @Test void startSeleniumTwo(){ WebDriver webDriver = new ChromeDriver(); webDriver.get("https://www.baidu.com/"); } }
package com.weili.dao; import java.sql.Connection; import java.sql.SQLException; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import com.shove.data.DataException; import com.shove.data.DataSet; import com.shove.util.BeanMapUtils; import com.weili.database.Dao; public class ServiceTypeDao { /** * 添加服务类型 * @param conn * @param name * @param sortIndex * @param status * @return * @throws SQLException */ public long addServiceType(Connection conn,String title,String linkPath,int sortIndex,int status) throws SQLException{ Dao.Tables.t_service_type serviceType = new Dao().new Tables().new t_service_type(); serviceType.title.setValue(title); serviceType.linkPath.setValue(linkPath); serviceType.sortIndex.setValue(sortIndex); serviceType.status.setValue(status); serviceType.addTime.setValue(new Date()); return serviceType.insert(conn); } /** * 修改服务类型 * @param conn * @param id * @param name * @param sortIndex * @param status * @return * @throws SQLException */ public long updateServiceType(Connection conn,long id,String title,String linkPath, int sortIndex,int status) throws SQLException{ Dao.Tables.t_service_type serviceType = new Dao().new Tables().new t_service_type(); if(StringUtils.isNotBlank(title)){ serviceType.title.setValue(title); } if(StringUtils.isNotBlank(linkPath)){ serviceType.linkPath.setValue(linkPath); } if(sortIndex>0){ serviceType.sortIndex.setValue(sortIndex); } if(status>0){ serviceType.status.setValue(status); } return serviceType.update(conn, " id = "+id); } /** * 删除服务类型 * @param conn * @param ids * @return * @throws SQLException */ public long deleteServiceType(Connection conn,String ids) throws SQLException{ Dao.Tables.t_service_type serviceType = new Dao().new Tables().new t_service_type(); return serviceType.delete(conn, " id in("+ids+") "); } /** * 根据id查询 * @param conn * @param id * @return * @throws SQLException * @throws DataException */ public Map<String,String> queryServiceTypeById(Connection conn,long id) throws SQLException, DataException{ Dao.Tables.t_service_type serviceType = new Dao().new Tables().new t_service_type(); DataSet ds = serviceType.open(conn, " ", " id = "+id, "", -1, -1); return BeanMapUtils.dataSetToMap(ds); } /** * 根据条件查询 * @param conn * @param fieldList * @param condition * @param order * @return * @throws SQLException * @throws DataException */ public List<Map<String, Object>> queryServiceTypeAll(Connection conn,String fieldList,String condition,String order)throws SQLException, DataException { Dao.Tables.t_service_type serviceType = new Dao().new Tables().new t_service_type(); DataSet ds = serviceType.open(conn, fieldList, condition,order, -1, -1); ds.tables.get(0).rows.genRowsMap(); return ds.tables.get(0).rows.rowsMap; } }
package com.prakriti.favlistapp; import android.content.Context; import android.content.SharedPreferences; import androidx.preference.PreferenceManager; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Map; public class CategoryManager { // save data to Shared Preferences (SP) private Context context; public CategoryManager(Context context) { this.context = context; } // save categories to SP public void saveCategory(Category category) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = sharedPreferences.edit(); // to convert arraylist to set HashSet itemsHashSet = new HashSet(category.getItems()); // saving key - value pairs using SP // category and items inside it -> string set (no duplicate values) editor.putStringSet(category.getName(), itemsHashSet); editor.apply(); } public ArrayList<Category> retrieveCategories() { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); // ? refers to data of any type Map<String, ?> data = sharedPreferences.getAll(); ArrayList<Category> categories = new ArrayList<>(); for(Map.Entry<String, ?> entry : data.entrySet()) { // getValue is cast to HashSet (bcoz HashSet was passed in saveCategory() method) and converted to ArrayList categories.add(new Category(entry.getKey(), new ArrayList<String>((HashSet) entry.getValue()))); } return categories; } }
import java.util.Scanner; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.FileReader; import java.io.BufferedReader; import java.io.File; import java.io.PrintWriter; import javax.swing.*; import java.awt.Color; import java.awt.Font; import java.awt.event.*; public class AddStudent extends JFrame implements ActionListener{ private JPanel AddStudentMenu; static JTextField logo; static JButton /*addbutton,*/ backButton, submitButton; static StudentGUI StudentMenu; static JLabel Lname, Laddress, Lemail, Lphn, LRoll, Lcourse, LCGPA, Ldept; static JTextField fname, faddress, femail, fphn, fRoll, fcourse, fCGPA, fdept; AddStudent(){ this.setTitle("Adding a new student"); this.setResizable(false); //non-extending this.setSize(800,600); //frame dimensions. allocated pixels on screen this.setLocationRelativeTo(null); //default panel setting-> screen mid AddStudentMenu=new JPanel(); AddStudentMenu.setSize(800,600); AddStudentMenu.setLayout(null); AddStudentMenu.setBackground(Color.WHITE); logo=new JTextField(); logo.setText("ADD A NEW STUDENT"); logo.setFont(new Font("Courier New",Font.BOLD,26)); logo.setSize(380,90); logo.setBorder(null); logo.setBackground(Color.WHITE); logo.setEditable(false); logo.setLocation(248,50); AddStudentMenu.add(logo); backButton=new JButton(); backButton.setSize(180,60); backButton.setText("Back"); backButton.setFont(new Font("Courier New", Font.BOLD, 18)); backButton.setLocation(2,2); backButton.setBackground(Color.WHITE); AddStudentMenu.add(backButton); backButton.addActionListener(this); //name label and field Lname=new JLabel(); Lname.setSize(80,20); Lname.setLocation(25,180); Lname.setBackground(Color.WHITE); Lname.setText("Name: "); fname=new JTextField(); fname.setSize(450,20); fname.setLocation(109,180); fname.setBackground(Color.WHITE); AddStudentMenu.add(fname); AddStudentMenu.add(Lname); //address field and label Laddress=new JLabel(); Laddress.setSize(80,20); Laddress.setLocation(25,205); Laddress.setBackground(Color.WHITE); Laddress.setText("Address: "); faddress=new JTextField(); faddress.setSize(450,20); faddress.setLocation(109,205); faddress.setBackground(Color.WHITE); AddStudentMenu.add(faddress); AddStudentMenu.add(Laddress); //email field and label Lemail=new JLabel(); Lemail.setSize(80,20); Lemail.setLocation(25,230); Lemail.setBackground(Color.WHITE); Lemail.setText("Email: "); femail=new JTextField(); femail.setSize(450,20); femail.setLocation(109,230); femail.setBackground(Color.WHITE); AddStudentMenu.add(femail); AddStudentMenu.add(Lemail); //phone no field and label Lphn=new JLabel(); Lphn.setSize(80,20); Lphn.setLocation(25,255); Lphn.setBackground(Color.WHITE); Lphn.setText("Phone #: "); fphn=new JTextField(); fphn.setSize(450,20); fphn.setLocation(109,255); fphn.setBackground(Color.WHITE); AddStudentMenu.add(fphn); AddStudentMenu.add(Lphn); //course label and field LRoll=new JLabel(); LRoll.setSize(80,20); LRoll.setLocation(25,280); LRoll.setBackground(Color.WHITE); LRoll.setText("Roll #: "); fRoll=new JTextField(); fRoll.setSize(450,20); fRoll.setLocation(109,280); fRoll.setBackground(Color.WHITE); AddStudentMenu.add(fRoll); AddStudentMenu.add(LRoll); //rank label and field LCGPA=new JLabel(); LCGPA.setSize(80,20); LCGPA.setLocation(25,305); LCGPA.setBackground(Color.WHITE); LCGPA.setText("CGPA: "); fCGPA=new JTextField(); fCGPA.setSize(450,20); fCGPA.setLocation(109,305); fCGPA.setBackground(Color.WHITE); AddStudentMenu.add(fCGPA); AddStudentMenu.add(LCGPA); //salary label and field Ldept=new JLabel(); Ldept.setSize(80,20); Ldept.setLocation(25,330); Ldept.setBackground(Color.WHITE); Ldept.setText("Major: "); fdept=new JTextField(); fdept.setSize(450,20); fdept.setLocation(109,330); fdept.setBackground(Color.WHITE); AddStudentMenu.add(fdept); AddStudentMenu.add(Ldept); //office field and label Lcourse=new JLabel(); Lcourse.setSize(80,20); Lcourse.setLocation(25,355); Lcourse.setBackground(Color.WHITE); Lcourse.setText("Courses: "); fcourse=new JTextField(); fcourse.setSize(450,20); fcourse.setLocation(109,355); fcourse.setBackground(Color.WHITE); AddStudentMenu.add(fcourse); AddStudentMenu.add(Lcourse); //submit button record save<-> submitButton=new JButton(); submitButton.setSize(140,40); submitButton.setLocation(380,480); submitButton.setBackground(Color.WHITE); submitButton.setText("SAVE"); AddStudentMenu.add(submitButton); submitButton.addActionListener(this); this.add(AddStudentMenu); } public void actionPerformed(ActionEvent e) { if(e.getSource() == backButton){ StudentMenu=new StudentGUI(); this.dispose(); StudentMenu.setVisible(true); } else if(e.getSource() == submitButton){ Student t=new Student(); t.set_name(String.valueOf(fname.getText())); t.set_Address(String.valueOf(faddress.getText())); t.set_email(String.valueOf(femail.getText())); t.set_Roll(String.valueOf(fRoll.getText())); t.set_Courses(String.valueOf(fcourse.getText())); t.set_Dept(String.valueOf(fdept.getText())); t.set_CGPA(Double.valueOf(String.valueOf(fCGPA.getText()))); //System.out.println(String.valueOf(fname.getText())); //t.set_salary(Double.valueOf(fname.getText())); //System.out.println(t.get_name()); FileWriter fileWritter; try { fileWritter = new FileWriter("Student.txt",true); PrintWriter pr=new PrintWriter(fileWritter); pr.println(t.get_name()); pr.println(t.get_Address()); pr.println(t.get_email()); pr.println(t.get_Roll()); pr.println(t.get_Courses()); pr.println(t.get_Dept()); pr.println(t.get_CGPA()); pr.println(" "); pr.close(); } catch (IOException e1) { e1.printStackTrace(); } //going back to the student window StudentMenu=new StudentGUI(); this.dispose(); StudentMenu.setVisible(true); } } }
package MainRuns; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import jp.ac.ut.csis.pflow.geom.LonLat; import DisasterAlert.DayChooser; import MobilityAnalyser.HomeOfficeMaps; public class NormalDayExp { private static final String homepath = "/home/c-tyabe/Data/expALL2/"; protected static final SimpleDateFormat SDF_TS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//change time format protected static final SimpleDateFormat SDF_MDS = new SimpleDateFormat("HH:mm:ss");//change time format public static void main(String args[]) throws NumberFormatException, IOException, ParseException{ run(); } public static void run() throws IOException, NumberFormatException, ParseException{ ArrayList<String> idlist = getIDs(new File(homepath+"id_home.csv")); String ymd = "20150101"; String dataforexp = homepath+"dataforexp.csv"; HashSet<String> targetdays = DayChooser.getTargetDates2(ymd); System.out.println("#the number of days are " + targetdays.size()); Makedata4exp.makedata2(dataforexp, targetdays, idlist); System.out.println("#successfully made data for exp"); executeAnalyser(dataforexp, FilePaths.dirfile(homepath,"id_office.csv"), homepath); File data = new File(dataforexp); data.delete(); } public static ArrayList<String> getIDs(File in) throws IOException{ ArrayList<String> res = new ArrayList<String>(); BufferedReader br = new BufferedReader(new FileReader(in)); String line = null; while((line = br.readLine())!= null){ String[] tokens = line.split("\t"); String id = tokens[0]; res.add(id); } br.close(); return res; } public static void executeAnalyser(String infile, String idoffice, String outputpath) throws NumberFormatException, IOException, ParseException{ File in = new File(infile); File Office = new File(idoffice); HashMap<String,HashMap<String,ArrayList<Integer>>> omap = getLogsnearX(in,Office); System.out.println("#done getting logs near office"); HashMap<String, HashMap<String, Integer>> officeenter = officeEnterTime(omap); //System.out.println("#done getting office enter time"); System.out.println("#writing everything out..."); writeout(officeenter, outputpath, "office_enter.csv"); } public static HashMap<String, HashMap<String, Integer>> officeEnterTime(HashMap<String,HashMap<String,ArrayList<Integer>>> omap){ HashMap<String, HashMap<String, Integer>> OEntertimes = new HashMap<String, HashMap<String, Integer>>(); for(String id : omap.keySet()){ HashMap<String, Integer> day_lastlog = new HashMap<String, Integer>(); for(String day : omap.get(id).keySet()){ ArrayList<Integer> list = omap.get(id).get(day); Collections.sort(list); if(list.size()>1){ day_lastlog.put(day, list.get(0)); } } OEntertimes.put(id, day_lastlog); } return OEntertimes; } public static File writeout(HashMap<String, HashMap<String, Integer>> map, String path, String name) throws IOException{ File out = new File(path+name); BufferedWriter bw = new BufferedWriter(new FileWriter(out)); for(String id : map.keySet()){ for(String day : map.get(id).keySet()){ double time = (double)map.get(id).get(day)/(double)3600; BigDecimal x = new BigDecimal(time); x = x.setScale(2, BigDecimal.ROUND_HALF_UP); bw.write(id + "," + day + "," + x); bw.newLine(); } } bw.close(); return out; } public static HashMap<String,HashMap<String,ArrayList<Integer>>> getLogsnearX(File in, File X) throws IOException, NumberFormatException, ParseException{ HashMap<String,LonLat> id_X = HomeOfficeMaps.getXMap(X); HashMap<String,HashMap<String,ArrayList<Integer>>> res = new HashMap<String,HashMap<String,ArrayList<Integer>>>(); BufferedReader br = new BufferedReader(new FileReader(in)); String line = null; while((line=br.readLine())!=null){ String[] tokens = line.split("\t"); String id = (tokens[0]); if(id_X.containsKey(id)){ Double lon = Double.parseDouble(tokens[2]); Double lat = Double.parseDouble(tokens[1]); LonLat point = new LonLat(lon,lat); String date = tokens[3]; String[] youso = date.split(" "); String ymd = youso[0]; String[] youso2 = ymd.split("-"); String month = youso2[1]; String hiniti = youso2[2]; String hms = youso[1]; String hour = hms.substring(0,2); if(point.distance(id_X.get(id))<500){ Integer time = HomeOfficeMaps.converttoSecs(SDF_MDS.format(SDF_TS.parse(tokens[3]))); if(Integer.valueOf(hour)<3){ time = time + 86400; } if(res.containsKey(id)){ if(res.get(id).containsKey(month+"-"+hiniti)){ res.get(id).get(month+"-"+hiniti).add(time); } else{ ArrayList<Integer> list = new ArrayList<Integer>(); list.add(time); res.get(id).put(month+"-"+hiniti, list); } } else{ HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>(); ArrayList<Integer> list = new ArrayList<Integer>(); list.add(time); map.put(month+"-"+hiniti, list); res.put(id, map); } } } } br.close(); return res; } }
package com.standardchartered.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.standardchartered.models.Customer; import com.standardchartered.services.CustomerService; @RestController public class CustomerController { @Autowired private CustomerService customerService; @RequestMapping(value="/customers", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) public List<Customer> getCustomers(){ List<Customer> customers = this.customerService.findAll(); return customers; } }
package org.point85.domain.proficy; import java.util.List; import com.google.gson.annotations.SerializedName; /** * A serialized list of tag data * */ public class TagValues extends TagError { @SerializedName(value = "Data") private List<TagData> tagData; public List<TagData> getTagData() { return tagData; } }
package com.flowedu.controller; import com.flowedu.util.Util; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; /** * Created by jihoan on 2017. 9. 26.. */ @Controller public class PopupController { @RequestMapping(value = {"/popup", "/popup/{page_gbn}"}) public ModelAndView popup(@RequestParam(value = "page_gbn", required = false) String page_gbn) throws Exception { ModelAndView mvc = new ModelAndView(); page_gbn = Util.isNullValue(page_gbn, ""); if ("school_search".equals(page_gbn)) { mvc.setViewName("/popup/school_search_popup"); } return mvc; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cput.codez.angorora.eventstar.model; import java.util.Calendar; import java.util.List; /** * * @author allen */ public final class Meeting { private String id; private String eventName; private String eventId; private Venue venue; private List<Attendee> attendees; private EventOwner owner; private String organisationName; private Calendar date; private int duration; private Meeting() { } private Meeting(Builder build) { this.organisationName=build.organisationName; this.id=build.id; this.eventName = build.eventName; this.eventId=build.eventId; this.venue=build.venue; this.attendees=build.attendees; this.owner=build.owner; this.date=build.date; this.duration=build.duration; } public String getId() { return id; } public String getEventName() { return eventName; } public String getEventId() { return eventId; } public Venue getVenue() { return venue; } public List<Attendee> getAttendees() { return attendees; } public EventOwner getOwner() { return owner; } public String getOrganisationName() { return organisationName; } public Calendar getDate() { return date; } public int getDuration() { return duration; } public static class Builder{ private String id; private String eventName; private String eventId; private Venue venue; private List<Attendee> attendees; private EventOwner owner; private String organisationName; private Calendar date; private int duration; public Builder(String org) { this.organisationName=org; } public Builder id(String id){ this.id=id; return this; } public Builder eventName(String evName){ this.eventName = evName; return this; } public Builder eventId(String evId){ this.eventId=evId; return this; } public Builder venueId(Venue venue){ this.venue=venue; return this; } public Builder attendeeList(List<Attendee> attList){ this.attendees=attList; return this; } public Builder eventOwner(EventOwner owner){ this.owner=owner; return this; } public Builder date(Calendar date){ this.date=date; return this; } public Builder duration(int duration){ this.duration=duration; return this; } public Meeting build(){ return new Meeting(this); } public Builder copier(Meeting meet){ this.organisationName=meet.organisationName; this.id=meet.id; this.eventName = meet.eventName; this.eventId=meet.eventId; this.venue=meet.venue; this.attendees=meet.attendees; this.owner=meet.owner; this.date=meet.date; this.duration=meet.duration; return this; } } @Override public int hashCode() { int hash = 7; hash = 79 * hash + (this.id != null ? this.id.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Meeting other = (Meeting) obj; if ((this.id == null) ? (other.id != null) : !this.id.equals(other.id)) { return false; } return true; } }
package in.anandm.oj.model; import in.anandm.oj.repository.EvaluationResultRepository; import in.anandm.oj.repository.SolutionRepository; import in.anandm.oj.repository.TestCaseRepository; import in.anandm.oj.service.PathHelper; import in.anandm.oj.utils.FileUtils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class JavaJudge extends AbstractJudge { /** * @param pathHelper * @param testCaseRepository * @param evaluationResultRepository * @param solutionRepository */ public JavaJudge(PathHelper pathHelper, TestCaseRepository testCaseRepository, EvaluationResultRepository evaluationResultRepository, SolutionRepository solutionRepository) { super(pathHelper, testCaseRepository, evaluationResultRepository, solutionRepository); } @Override public String sourceFileName() { return "Main.java"; } @Override public String executableFileName() { return "Main"; } @Override public String compile(String stagingDirectoryPath) { try { ProcessBuilder processBuilder = new ProcessBuilder("javac", sourceFileName()); processBuilder.directory(new File(pathHelper .absoluteStagingDirectoryPath(stagingDirectoryPath))); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); int exitCode = process.waitFor(); StringBuilder builder = new StringBuilder(); if (exitCode != 0) { String line = null; while ((line = reader.readLine()) != null) { builder.append(line); } } reader.close(); process.destroy(); return builder.toString(); } catch (Exception e) { throw new ApplicationException("failed to compile staging area : " + stagingDirectoryPath, e); } } @Override public EvaluationResultStatus test(String stagingDirectoryPath, TestCase testCase, long timeLimit, long memoryLimit) { try { String outputFileName = testCase.getId() + ".out.txt"; String outputFilePath = pathHelper.stagingFilePath( stagingDirectoryPath, outputFileName); String scriptFilePath = pathHelper.stagingFilePath( stagingDirectoryPath, "run.bat"); File runScript = new File( pathHelper.absoluteStagingFilePath(scriptFilePath)); BufferedWriter writer = new BufferedWriter( new FileWriter(runScript)); writer.write("echo off"); writer.write(System.getProperty("line.separator")); writer.write("java " + executableFileName() + " < " + pathHelper.absoluteFilePath(testCase.getInputFilePath()) + " > " + outputFileName); writer.close(); ProcessBuilder processBuilder = new ProcessBuilder( pathHelper.absoluteStagingFilePath(scriptFilePath)); processBuilder.directory(new File(pathHelper .absoluteStagingDirectoryPath(stagingDirectoryPath))); final Process process = processBuilder.start(); final List<Boolean> timeOut = new ArrayList<Boolean>(1); timeOut.add(0, Boolean.FALSE); final Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { try { process.exitValue(); } catch (IllegalThreadStateException e) { process.destroy(); timeOut.add(0, Boolean.TRUE); } timer.cancel(); } }, timeLimit); int exitCode = -1; try { exitCode = process.waitFor(); timer.cancel(); process.destroy(); } catch (InterruptedException e) { // ignore } if (exitCode == 0) { File result = new File( pathHelper.absoluteStagingFilePath(outputFilePath)); File expected = new File(pathHelper.absoluteFilePath(testCase .getOutputFilePath())); if (FileUtils.hasSameContent(result, expected)) { return EvaluationResultStatus.AC; } else { return EvaluationResultStatus.WO; } } else { if (timeOut.get(0)) { return EvaluationResultStatus.TLE; } else { return EvaluationResultStatus.RE; } } } catch (Exception e) { throw new ApplicationException( "failed to execute test case, staging area : " + stagingDirectoryPath + " , test case id : " + testCase.getId(), e); } } }
package camera.toandoan.com.cameraproject; import android.Manifest; import android.app.Activity; import android.content.pm.PackageManager; import android.hardware.Camera; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.util.Log; import android.view.View; import android.widget.FrameLayout; import android.widget.Toast; import java.io.File; public class MainActivity extends Activity implements View.OnClickListener { private static final String TAG = "MainActivity"; private static final String[] PERMISSIONS = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; private static final int REQUEST_CAMERA_PERMISION = 1; private Camera mCamera; private CameraPreview mCameraPreview; private int mCameraType = Camera.CameraInfo.CAMERA_FACING_FRONT; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initActionButton(); if (!CameraUtils.checkCameraHardware(this)) { return; } if (!checkCameraPermission()) { return; } initCameraPreview(mCameraType); } private void initActionButton() { findViewById(R.id.button_screen_shot).setOnClickListener(this); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode != REQUEST_CAMERA_PERMISION) { return; } if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { initCameraPreview(mCameraType); } } @Override public void onClick(View view) { mCameraPreview.takePicture(new CameraPreview.TakePictureCallback() { @Override public void onTakePictureSuccess(File file) { Toast.makeText(MainActivity.this, file.getPath(), Toast.LENGTH_SHORT).show(); } @Override public void onTakePictureFailure(Exception error) { Toast.makeText(MainActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show(); } }); } private void initCameraPreview(int typeCamera) { mCamera = CameraUtils.getCameraInstance(typeCamera); mCameraPreview = new CameraPreview(this, mCamera); FrameLayout previewLayout = findViewById(R.id.frame_camera); previewLayout.addView(mCameraPreview); } private boolean isCameraPermisionGrant(String permission) { if (ActivityCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED) { return true; } return false; } private void requestPermision(String permission) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) { // TODO: 4/9/18 } else { ActivityCompat.requestPermissions(this, new String[]{permission}, REQUEST_CAMERA_PERMISION); } } private boolean checkCameraPermission() { boolean result = true; for (String permission : PERMISSIONS) { if (!isCameraPermisionGrant(permission)) { requestPermision(permission); result = false; } } return result; } }
import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 给定一个整数数组,返回两个数字的索引,使得它们相加到一个特定的目标。 * * @author song.liu@ele.me * @version v1.0,2017-02-07 17:01 */ public class TwoSum { public static void main(String[] args) { int[] answer = twoSumA(new int[]{1, 2, 4, 3, 6, 9, 7, 4, 8, 12, 32}, 5); for (int i = 0; i < answer.length; i++) { System.out.println(answer[i]); } } /** * 1. 先对数组进行过排序 * 2. 从排序后数组两端开始,定义两个游标向中间移动,大于目标值减小右边的游标,小于目标则增加左边的游标 * <p> * Time Complexity: O(n) * Space Complexity: O(n) */ public static int[] twoSumA(int[] nums, int target) { int[] copy = new int[nums.length]; for (int j = 0; j < nums.length; j++) { copy[j] = nums[j]; } // 从小到大排序 Arrays.sort(copy); int[] answer = new int[2]; int l = 0, r = copy.length - 1; while (l < r && l >= 0 && r < copy.length) { int temp = copy[l] + copy[r]; if (temp > target) { r--; } else if (temp < target) { l++; } else { break; } } boolean rr = true, ll = true; for (int k = 0; k < nums.length; k++) { if (nums[k] == copy[l] && ll) { answer[0] = k; ll = false; } else if (nums[k] == copy[r] && rr) { answer[1] = k; rr = false; } } return answer; } /** * HashMap查找速度最快为O(1),最差为O(n),整体速度取决于hash算法的优劣 * (Two-pass Hash Table) * To improve our run time complexity, we need a more efficient way to check if the complement exists in the array. * If the complement exists, we need to look up its index. What is the best way to maintain a mapping of each element * in the array to its index? A hash table. We reduce the look up time from O(n)O(n) to O(1)O(1) by trading space for * speed. A hash table is built exactly for this purpose, it supports fast look up in near constant time. I say "near" * because if a collision occurred, a look up could degenerate to O(n)O(n) time. But look up in hash table should be * amortized O(1)O(1) time as long as the hash function was chosen carefully. A simple implementation uses two iterations. * In the first iteration, we add each element's value and its index to the table. Then, in the second iteration we check * if each element's complement (target - nums[i]target−nums[i]) exists in the table. Beware that the complement mus * -t not be nums[i]nums[i] itself! * <p> * Complexity Analysis: * Time complexity : O(n)O(n). We traverse the list containing nn elements exactly twice. Since the hash table reduc * -es the look up time to O(1)O(1), the time complexity is O(n)O(n). * Space complexity : O(n)O(n). The extra space required depends on the number of items stored in the hash table, wh * -ich stores exactly nn elements. */ public static int[] twoSumB(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement) && map.get(complement) != i) { return new int[]{i, map.get(complement)}; } } throw new IllegalArgumentException("No two sum solution"); } /** * It turns out we can do it in one-pass. While we iterate and inserting elements into the table, we also look back * to check if current element's complement already exists in the table. If it exists, we have found a solution and * return immediately. * <p> * Time complexity : O(n)O(n). We traverse the list containing nn elements only once. Each look up in the table cost * -s only O(1)O(1) time. * Space complexity : O(n)O(n). The extra space required depends on the number of items stored in the hash table, wh * -ich stores at most nn elements. */ public static int[] twoSumC(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[]{map.get(complement), i}; } map.put(nums[i], i); } throw new IllegalArgumentException("No two sum solution"); } }
package lib.basenet.okhttp.upload_down; import java.io.Serializable; /** * 断点下载文件信息 */ public final class DownloadFileInfo implements Serializable { //状态值 //下载成功:完成 public static final int SUCCESS = 4; //下载失败:网络错误 public static final int FAILURE = 1; //下载中:下载中 此状态不缓存 public static final int DOWNLOADING = 2; //暂停:暂停下载 public static final int DOWNLOAD_PAUSE = 3; //下载未开始:触发下载任务,但是还未发起网络请求 public static final int NOT_BEGIN = 0; //下载状态 protected volatile int status; //文件URL地址 public String fileUrl; //文件本地存储地址 public String localFilePath; //当前下载完成量 public long currentFinished; //文件总大小 public long fileSize; public DownloadFileInfo(String fileUrl, String localFilePath) { if (fileUrl == null || localFilePath == null) { throw new NullPointerException("DownloadFileInfo's param must not be null"); } this.fileUrl = fileUrl; this.localFilePath = localFilePath; this.status = NOT_BEGIN; } protected void reset() { currentFinished = 0; this.status = NOT_BEGIN; } }
package work.binder.ui; import java.util.List; import java.util.Map; import com.vaadin.event.FieldEvents; import com.vaadin.event.FieldEvents.TextChangeEvent; import com.vaadin.ui.TextArea; public class PackageCommands extends LayoutReloadComponent { private static final long serialVersionUID = 4035499611555525481L; @Override public void reload() { // TODO Auto-generated method stub TextArea commandsForPackages = new TextArea( "Please enter every new command for the slaves in the new line."); commandsForPackages.setWidth("600"); commandsForPackages.addListener(new FieldEvents.TextChangeListener() { private static final long serialVersionUID = 3818211730859843892L; public void textChange(TextChangeEvent event) { String commandsString = (String) event.getText(); String[] commands = commandsString.split("\n"); Package job = UserContext.getContext().getJob(); List<String> ipAddresses = job.getIpAddresses(); Map<String, PackageData> packagesForSendingMap = UserContext .getContext().getPackagesForSending(); // TODO add handling: what if there is less commands // than it // should be int i = 0; for (String ipAddressComment : ipAddresses) { int indexOfNewLine = ipAddressComment.indexOf(" "); String ip = null; if (indexOfNewLine < 0) { ip = ipAddressComment; } else { ip = ipAddressComment.substring(0, indexOfNewLine); } PackageData packageData = packagesForSendingMap.get(ip); if (packageData == null) { packageData = new PackageData(); packagesForSendingMap.put(ip, packageData); } packageData.setCommand(commands[i++]); } } }); commandsForPackages.setImmediate(true); removeAllComponents(); addComponent(commandsForPackages); } }
package escolasis.modelo.dao.interfaces; import java.util.List; import escolasis.modelo.PapelPessoa; public interface PapelPessoaDao { public void salvar(PapelPessoa papelPessoa); public List<PapelPessoa> listar(); public PapelPessoa getPapelPessoa(Long idPapelPessoa); }
package Matrimony.matrimonyart; import java.awt.Robot; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.imageio.ImageIO; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; public class ImageCropCheck extends BaseTest { Actions acc; String marital_statuswid; public static WebDriver driver; String marital_statusany; String marital_statussep5; String shwoprofilewith5; String marital_statussep6; String marital_statuswid5; String marital_statusdiv6; String marital_statuswid6; String marital_statusdiv5; String marital_statussep; String marital_statusdiv; Boolean flag=false; String[] photoUrl = new String[10]; Boolean repeatFlag=false; int count = 0; @BeforeMethod public void setup() throws MalformedURLException { // ChromeOptions options = new ChromeOptions(); // options.addArguments("--disable-notifications"); System.setProperty("webdriver.chrome.driver","D:\\Java\\Window7\\First\\matrimonyart\\driver\\chromedriver.exe"); driver = new ChromeDriver(); } @Test public void setup6() throws Throwable { searchPOM g = new searchPOM(driver); acc = new Actions(driver); Robot r = new Robot(); WebDriverWait wait = new WebDriverWait(driver, 30); JavascriptExecutor js = (JavascriptExecutor)driver; //Open URL Thread.sleep(3000); driver.get(BaseTest.getExcelControl("Authenticate", getControlRow(), 3)); driver.manage().window().maximize(); //Enter Username and Password from Excel Thread.sleep(1000); BaseTest.click(g.getMatriID()); BaseTest.typeData(g.getMatriID(), getExcelControl("Authenticate", getControlRow(), 0)); Thread.sleep(1000); BaseTest.click(g.getPasswordClear()); BaseTest.typeData(g.getPassword(), getExcelControl("Authenticate", getControlRow(), 1)); //Click on the LoginButton Thread.sleep(3000); BaseTest.click(g.getLogin_btn()); //Skip the intermediate page try { Thread.sleep(5000); BaseTest.click(driver.findElement(By.xpath("//a[@class='clr7']"))); } catch (Exception e) { System.err.println("There is some Exception in the above Topic"); } //Handling the Notification Thread.sleep(4000); Runtime.getRuntime().exec("D:\\Java\\Window7\\First\\matrimonyart\\Exe\\ClickNotification.exe"); Thread.sleep(5000); try { driver.findElement(By.xpath("//*[@alt='close']")).click(); } catch (Exception e) { //driver.findElement(By.xpath("//*[@alt='close']")).click(); System.out.println("popup is not available"); Thread.sleep(2000); } Thread.sleep(2000); ///////////////////////////////Seleting the profile//////////////////////////// String parent = driver.getWindowHandle(); WebElement profilePic = null; try { profilePic = driver.findElement(By.xpath("//*[@class='prfile_icon']")); } catch (Exception e) { System.out.println("no profile photo is available"); profilePic = driver.findElement(By.xpath("//*[@class='addphoto prfile_icon']")); } profilePic.click(); Thread.sleep(3000); Set<String> child = driver.getWindowHandles(); for (String string : child) { if (!parent.equals(string)) { driver.switchTo().window(string); System.out.println("New Window is Handeled"); Thread.sleep(5000); } } List<WebElement> countofImages = driver.findElements(By.xpath("(//*[@class='adfotolistitem'])")); System.out.println(countofImages.size()); driver.findElement(By.xpath("//*[@class='v-profile-link mediumtxt']")).click(); Set<String> child2 = driver.getWindowHandles(); for (String string : child2) { if (!parent.equals(string) && !child.equals(string)) { driver.switchTo().window(string); System.out.println("New Window is Handeled"); Thread.sleep(5000); } } Thread.sleep(5000); driver.findElement(By.xpath("//*[@id='imgdiv1']")).click(); Thread.sleep(5000); String imagepath = driver.findElement(By.xpath("(//*[@class='wraptocenter'])[1]//img")).getAttribute("src"); driver.get("https://image.online-convert.com/convert/webp-to-jpg"); driver.manage().window().maximize(); Thread.sleep(2000); try { Thread.sleep(2000); driver.findElement(By.className("btn-extension-cancel")).click(); } catch (Exception e) { System.out.println("Exception Handled - 'btn-extension-cancel'"); } try { Thread.sleep(2000); driver.findElement(By.className("btn btn-info btn-lg qg-consent-ok")).click(); } catch (Exception e) { System.out.println("Exception Handled - 'btn btn-info btn-lg qg-consent-ok'"); driver.findElement(By.xpath("//*[text()='Ok']")).click(); } Thread.sleep(2000); driver.findElement(By.xpath("//*[@class='uploadbutton']")).click(); WebElement EnterURL = driver.findElement(By.xpath("//*[@id='externalUrlInput']")); EnterURL.click(); EnterURL.sendKeys(imagepath); driver.findElement(By.xpath("//*[@id='externalUrlDialogOkButton']")).click(); Thread.sleep(2000); driver.findElement(By.xpath("(//*[text()=' Start conversion '])[1]")).click(); Thread.sleep(6000); System.out.println("outside checkbox"); driver.findElement(By.xpath("//*[text()='Download']")).click(); System.out.println("outside download"); //Search File in DIR File dir = new File("C:\\Users\\admin\\Downloads"); FilenameFilter filter = new FilenameFilter() { public boolean accept (File dir, String name) { return name.startsWith("IYR242926"); } }; String[] children = dir.list(filter); if (children == null) { System.out.println("Either dir does not exist or is not a directory"); } else { for (int i = 0; i< children.length; i++) { String filename = children[i]; System.out.println(filename); } } /////////////////////////////////////////////////////////////////////////////////////// String fileName1 = null; File dir1 = new File("C:\\Users\\admin\\Downloads"); FilenameFilter filter1 = new FilenameFilter() { public boolean accept (File dir, String name) { return name.startsWith("IYR242926"); } }; String[] children1 = dir1.list(filter1); if (children1 == null) { System.out.println("Either dir does not exist or is not a directory"); } else { for (int i = 0; i< children1.length; i++) { fileName1 = children1[i]; System.out.println(fileName1); } } System.out.println("Extracted successfully- total no of length :"+children1.length); BufferedImage imgA = null; BufferedImage imgB = null; System.out.println("After buff Image"); try { File fileA = new File("D:\\Growup\\LOGO\\Test.jpg"); File fileB = new File("C:\\Users\\admin\\Downloads\\"+children1[1]); System.out.println("file created"); imgA = ImageIO.read(fileA); imgB = ImageIO.read(fileB); System.out.println("successfully try block passed"); } catch (IOException e) { System.out.println(e); System.out.println("inside catch "); } int width1 = imgA.getWidth(); int width2 = imgB.getWidth(); int height1 = imgA.getHeight(); int height2 = imgB.getHeight(); if ((width1 != width2) || (height1 != height2)) System.err.println("Error: Images dimensions"+" mismatch"); else { long difference = 0; for (int y = 0; y < height1; y++) { for (int x = 0; x < width1; x++) { int rgbA = imgA.getRGB(x, y); int rgbB = imgB.getRGB(x, y); int redA = (rgbA >> 16) & 0xff; int greenA = (rgbA >> 8) & 0xff; int blueA = (rgbA) & 0xff; int redB = (rgbB >> 16) & 0xff; int greenB = (rgbB >> 8) & 0xff; int blueB = (rgbB) & 0xff; difference += Math.abs(redA - redB); difference += Math.abs(greenA - greenB); difference += Math.abs(blueA - blueB); } } // Total number of red pixels = width * height // Total number of blue pixels = width * height // Total number of green pixels = width * height // So total number of pixels = width * height * 3 double total_pixels = width1 * height1 * 3; // Normalizing the value of different pixels // for accuracy(average pixels per color // component) double avg_different_pixels = difference / total_pixels; // There are 255 values of pixels in total double percentage = (avg_different_pixels / 255) * 100; System.out.println("Difference Percentage-->" +percentage); if (percentage==0) { System.out.println(" Same image is repeated"); repeatFlag=true; }else { System.out.println("Not repeated "); } } Thread.sleep(5000); //////////////Delete List of files////////////////////////// File directory = new File("E:\\ImagesToCompare"); // Get all files in directory File[] files = directory.listFiles(); for (File file : files) { // Delete each file System.out.println("deleted"); if (!file.delete()) { // Failed to delete file System.out.println("Failed to delete "+file); } } Thread.sleep(2000); driver.close(); driver.switchTo().window(parent); Thread.sleep(2000); } }
/* * 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 View; import java.util.Date; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; /** * * @author hvomm */ public class MainFrame extends javax.swing.JFrame { private String username; private String password; private double balance; private Date dateCreated; private String securityQuestion; private String securityAnswer; private String email; /** * Creates new form MainFrame */ public MainFrame() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jDesktopPane1 = new javax.swing.JDesktopPane(); jLabel1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); textField1 = new java.awt.TextField(); jButton1 = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jLabel9 = new javax.swing.JLabel(); textField2 = new java.awt.TextField(); textField3 = new java.awt.TextField(); textField4 = new java.awt.TextField(); textField5 = new java.awt.TextField(); textField6 = new java.awt.TextField(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setFocusableWindowState(false); addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { formKeyPressed(evt); } }); jLabel1.setFont(new java.awt.Font("Century Gothic", 0, 48)); // NOI18N jLabel1.setForeground(new java.awt.Color(0, 255, 177)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("BUDGET HELPER"); jLabel1.setToolTipText(""); jPanel1.setForeground(new java.awt.Color(0, 204, 255)); jPanel1.setFont(new java.awt.Font("Century Gothic", 0, 16)); // NOI18N textField1.setText("textField1"); textField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField1ActionPerformed(evt); } }); jButton1.setFont(new java.awt.Font("Century Gothic", 0, 14)); // NOI18N jButton1.setText("Enter"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel2.setBackground(new java.awt.Color(102, 255, 153)); jPanel2.setForeground(new java.awt.Color(102, 255, 153)); jLabel2.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Enter your balance: "); jLabel3.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel3.setText("Enter a password: "); jLabel4.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel4.setText("Enter a username: "); jLabel5.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel5.setText("Enter your balance: "); jLabel6.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel6.setText("Enter a security question: "); jLabel7.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel7.setText("Enter the security answer: "); jLabel9.setFont(new java.awt.Font("Century Gothic", 0, 24)); // NOI18N jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel7) .addComponent(jLabel4) .addComponent(jLabel3) .addComponent(jLabel2)) .addGap(37, 37, 37)) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel9) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(68, 68, 68) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel7, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(69, 69, 69)) ); textField2.setText("textField1"); textField2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField2ActionPerformed(evt); } }); textField3.setText("textField1"); textField3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField3ActionPerformed(evt); } }); textField4.setText("textField1"); textField4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField4ActionPerformed(evt); } }); textField5.setText("textField1"); textField5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField5ActionPerformed(evt); } }); textField6.setText("textField1"); textField6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { textField6ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(59, 59, 59) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField3, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField6, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField4, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField5, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 65, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 128, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(74, 74, 74)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(70, 70, 70) .addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textField2, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textField3, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(textField4, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textField6, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(textField5, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jDesktopPane1.setLayer(jLabel1, javax.swing.JLayeredPane.DEFAULT_LAYER); jDesktopPane1.setLayer(jPanel1, javax.swing.JLayeredPane.DEFAULT_LAYER); javax.swing.GroupLayout jDesktopPane1Layout = new javax.swing.GroupLayout(jDesktopPane1); jDesktopPane1.setLayout(jDesktopPane1Layout); jDesktopPane1Layout.setHorizontalGroup( jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPane1Layout.createSequentialGroup() .addGap(163, 163, 163) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(164, 164, 164)) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jDesktopPane1Layout.setVerticalGroup( jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jDesktopPane1Layout.createSequentialGroup() .addGap(47, 47, 47) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(39, 39, 39) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(406, 406, 406) .addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(181, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void textField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textField1ActionPerformed username = textField1.getText(); }//GEN-LAST:event_textField1ActionPerformed private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed // TODO add your handling code here: }//GEN-LAST:event_formKeyPressed private void textField2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textField2ActionPerformed //password = textField2.getText(); }//GEN-LAST:event_textField2ActionPerformed private void textField3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textField3ActionPerformed balance = Double.parseDouble(textField3.getText()); }//GEN-LAST:event_textField3ActionPerformed private void textField4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textField4ActionPerformed securityQuestion = textField4.getText(); }//GEN-LAST:event_textField4ActionPerformed private void textField5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textField5ActionPerformed securityAnswer = textField5.getText(); }//GEN-LAST:event_textField5ActionPerformed private void textField6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textField6ActionPerformed email = textField6.getText(); }//GEN-LAST:event_textField6ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new MainFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JDesktopPane jDesktopPane1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private java.awt.TextField textField1; private java.awt.TextField textField2; private java.awt.TextField textField3; private java.awt.TextField textField4; private java.awt.TextField textField5; private java.awt.TextField textField6; // End of variables declaration//GEN-END:variables }
package com.tianwotian.mytaobao.bean; /** * Created by user on 2016/9/2. */ public class CheckMobile { String error; public String getError(){ return error; } }
package com.esrinea.dotGeo.tracking.model.component.alertLiveFeed.dao; import com.esrinea.dotGeo.tracking.model.common.dao.GenericDAO; import com.esrinea.dotGeo.tracking.model.component.alertLiveFeed.entity.AlertLiveFeed; public interface AlertLiveFeedDAO extends GenericDAO<AlertLiveFeed> { AlertLiveFeed findByAlert(int alertId); }
package com.duanc.model.dto; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import org.springframework.stereotype.Component; import com.duanc.utils.Pagination; @Component("phoneDTO") public class PhoneDTO implements Serializable{ private static final long serialVersionUID = 1L; /**手机编号*/ private Integer id; private Integer brandId; /**品牌名称**/ private String brandName; private Integer modelId; /**机型名称**/ private String modelName; /**手机版本**/ private String version; /**价格**/ private BigDecimal price; /**cpu**/ private String cpu; /**cpu核心数**/ private String cpuCores; /**cpu频率**/ private Double cpuHz; private BigDecimal cpuhz; /**上市日期**/ private Date listingDate; /**主屏尺寸**/ private Double screenSize; private BigDecimal screensize; /**网络类型**/ private String netType; /**操作系统**/ private String os; /**运行内存**/ private String ram; /**手机内存**/ private String rom; /**电池容量**/ private Integer batteryCapacity; private Short battery; /**展示图片路径**/ private String picUrl; private Pagination pagination; public BigDecimal getCpuhz() { return cpuhz; } public void setCpuhz(BigDecimal cpuhz) { this.cpuhz = cpuhz; } public BigDecimal getScreensize() { return screensize; } public void setScreensize(BigDecimal screensize) { this.screensize = screensize; } public Short getBattery() { return battery; } public void setBattery(Short battery) { this.battery = battery; } public Pagination getPagination() { return pagination; } public void setPagination(Pagination pagination) { this.pagination = pagination; } public Integer getBrandId() { return brandId; } public void setBrandId(Integer brandId) { this.brandId = brandId; } public Integer getModelId() { return modelId; } public void setModelId(Integer modelId) { this.modelId = modelId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public String getModelName() { return modelName; } public void setModelName(String modelName) { this.modelName = modelName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public String getCpu() { return cpu; } public void setCpu(String cpu) { this.cpu = cpu; } public String getCpuCores() { return cpuCores; } public void setCpuCores(String cpuCores) { this.cpuCores = cpuCores; } public Double getCpuHz() { return cpuHz; } public void setCpuHz(Double cpuHz) { this.cpuHz = cpuHz; } public Date getListingDate() { return listingDate; } public void setListingDate(Date listingDate) { this.listingDate = listingDate; } public Double getScreenSize() { return screenSize; } public void setScreenSize(Double screenSize) { this.screenSize = screenSize; } public String getNetType() { return netType; } public void setNetType(String netType) { this.netType = netType; } public String getOs() { return os; } public void setOs(String os) { this.os = os; } public String getRam() { return ram; } public void setRam(String ram) { this.ram = ram; } public String getRom() { return rom; } public void setRom(String rom) { this.rom = rom; } public Integer getBatteryCapacity() { return batteryCapacity; } public void setBatteryCapacity(Integer batteryCapacity) { this.batteryCapacity = batteryCapacity; } public String getPicUrl() { return picUrl; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } }
/** * Created by Александр on 03.11.2016. */ public class Application { public static void main(String[] args) { System.out.println("Hello World !!!"); } }
package greedy; import java.util.Arrays; /** * Created by gouthamvidyapradhan on 28/06/2017. * <p> * There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it's horizontal, y-coordinates don't matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons. * <p> * An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons. * <p> * Example: * <p> * Input: * [[10,16], [2,8], [1,6], [7,12]] * <p> * Output: * 2 * <p> * Explanation: * One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x */ public class BurstBalloons { /** * Main method * * @param args * @throws Exception */ public static void main(String[] args) throws Exception { int[][] baloons = {{10, 16}, {2, 8}, {1, 6}, {7, 12}}; System.out.println(new BurstBalloons().findMinArrowShots(baloons)); } public int findMinArrowShots(int[][] points) { if (points.length == 0) return 0; Arrays.sort(points, ((o1, o2) -> o1[1] - o2[1])); int count = 0; int leftMost = points[0][1]; for (int i = 1; i < points.length; i++) { if (leftMost < points[i][0]) { count++; leftMost = points[i][1]; } } return count + 1; } }
package DemoRest.WebApp.repository; import DemoRest.WebApp.model.Bill; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import java.util.List; @Service public interface BillRepository extends JpaRepository<Bill, Integer> { public Bill findBillById(String Id); public List<Bill> findBillsByOwnerId(String owner_id); }
package com.yf.bigdata.kafka.hollysys.factory; import com.yf.bigdata.kafka.hollysys.listener.KafkaProducerMessageListener; import org.apache.commons.lang3.StringUtils; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.serialization.StringSerializer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.support.ProducerListener; import java.util.Map; import java.util.concurrent.Executors; /** * @author: YangFei * @description: * @create:2020-12-03 15:38 */ public class KafkaProducerFactory extends AbstractKafkaFactory { private static final Logger logger = LoggerFactory.getLogger(KafkaProducerFactory.class); private String acks; private int retries = 2147483647; private int batchSize = 1048576;//1*1024*1024=1M; private int linger = 100; private int requestSize = 1048576;//1*1024*1024=1M; private long maxBlock = 9223372036854775807L; private int memory = 33554432;//32*1024*1024=32M private boolean autoFlush = false; private KafkaProducerMessageListener listener; private DefaultKafkaProducerFactory<String, String> factory; private ProducerListener<String, String> callback; public void setAcks(String acks) { this.acks = acks; } public void setBatchSize(int batchSize) { this.batchSize = batchSize; } public void setRequestSize(int requestSize) { this.requestSize = requestSize; } public void setRetries(int retries) { this.retries = retries; } public void setLinger(int linger) { this.linger = linger; } public void setMaxBlock(long maxBlock) { this.maxBlock = maxBlock; } public void setMemory(int memory) { this.memory = memory; } public void setAutoFlush(boolean autoFlush) { this.autoFlush = autoFlush; } public DefaultKafkaProducerFactory<String, String> getFactory() { return factory; } public void setFactory(DefaultKafkaProducerFactory<String, String> factory) { this.factory = factory; } public KafkaProducerMessageListener getListener() { return listener; } public ProducerListener<String, String> getCallback() { return callback; } public void setListener(KafkaProducerMessageListener listener) { this.listener = listener; } public void setCallback(ProducerListener<String, String> callback) { this.callback = callback; } /** * @decription 初始化配置 * @author yi.zhang * @time 2017年6月2日 下午2:15:57 */ private void init() { try { Map<String, Object> config = deafultConfig(); config.put(ProducerConfig.ACKS_CONFIG, acks); config.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize); config.put(ProducerConfig.MAX_REQUEST_SIZE_CONFIG, requestSize); // 默认立即发送,这里这是延时毫秒数 config.put(ProducerConfig.LINGER_MS_CONFIG, linger); config.put(ProducerConfig.RETRIES_CONFIG, retries); config.put(ProducerConfig.MAX_BLOCK_MS_CONFIG, maxBlock); // 生产者缓冲大小,当缓冲区耗尽后,额外的发送调用将被阻塞。时间超过max.block.ms将抛出TimeoutException config.put(ProducerConfig.BUFFER_MEMORY_CONFIG, memory); if (StringUtils.isNotBlank(encoding)) { // 编码 config.put("serializer.encoding", encoding); } config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName()); // 创建kafka的生产者类 factory = new DefaultKafkaProducerFactory<>(config); if (callback == null) { callback = new ProducerListener<String, String>() { @Override public void onSuccess(String topic, Integer partition, String key, String value, RecordMetadata recordMetadata) { if (false || logger.isDebugEnabled()) { logger.info("--[Kafka producer({})] send success,data:{}", topic, value); } } @Override public void onError(String topic, Integer partition, String key, String value, Exception e) { logger.error("--[Kafka producer(" + topic + ")] send error,data:" + value + "!", e); } @Override public boolean isInterestedInSuccess() { return true; } }; } KafkaTemplate<String, String> template = new KafkaTemplate<>(factory, autoFlush); template.setProducerListener(callback); String defaultTopic = KAFKA_DEFAULT_TOPIC; if (topics != null && topics.length > 0) { defaultTopic = topics[0]; } template.setDefaultTopic(defaultTopic); listener.setTemplate(template); success = true; logger.info("--Kafka Producer Config({}) init success...", servers); } catch (Exception e) { success = false; logger.error("-----Kafka Producer Config init Error-----", e); } } @Override public void start() { init(); Executors.newSingleThreadExecutor().execute(() -> { while (running) { try { // if (factory == null || !success || !ping(servers)) { // reconnect(); // } Thread.sleep(1000l); } catch (InterruptedException e) { logger.error("--Kafka Interrupted...", e); Thread.currentThread().interrupt(); } catch (Exception e) { logger.error("--Kafka Exception...", e); } } }); } @Override public boolean delay() { return false; } @Override public void reconnect() { close(); init(); } /** * 关闭服务 */ @Override public void close() { if (factory != null) { try { factory.destroy(); } catch (Exception e) { logger.error("-----Kafka close Error-----", e); } } } }
package cttd.cryptography.demo; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import cttd.cryptography.util.CommonUtils; public class ShaHashing { public static String hash(String input) { byte[] dataInput = CommonUtils.convertStringToBytes(input); return hash(dataInput); } public static String hash(byte[] dataInput) { try { MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(dataInput); byte[] hashedData = md.digest(); return CommonUtils.convertByteToHex(hashedData); } catch (NoSuchAlgorithmException e) { return null; } } }
package com.android.myvirtualnutritionist.ui.diary.nutrition; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import com.android.myvirtualnutritionist.R; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.data.PieEntry; import com.github.mikephil.charting.utils.ColorTemplate; import java.util.ArrayList; public class CaloriesFragment extends Fragment { private CaloriesViewModel caloriesViewModel; // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private String mParam1; private String mParam2; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { caloriesViewModel = new ViewModelProvider(this).get(CaloriesViewModel.class); View view = inflater.inflate(R.layout.fragment_calories, container, false); PieChart pieChart = view.findViewById(R.id.pieChart); ArrayList<PieEntry> pieCalories = new ArrayList<>(); pieCalories.add(new PieEntry(350, "Breakfast")); pieCalories.add(new PieEntry(450, "Lunch")); pieCalories.add(new PieEntry(250, "Dinner")); pieCalories.add(new PieEntry(100, "Others")); PieDataSet pieDataSet = new PieDataSet(pieCalories, "Calories"); pieDataSet.setColors(ColorTemplate.COLORFUL_COLORS); pieDataSet.setValueTextColor(Color.BLACK); pieDataSet.setValueTextSize(25f); PieData pieData = new PieData(pieDataSet); pieChart.setData(pieData); pieChart.getDescription().setEnabled(false); pieChart.setCenterText("Calories"); pieChart.animate(); final TextView totalCalorieCalc = view.findViewById(R.id.text_Nutrition_totalCaloriesCalc); final TextView netCalorieCalc = view.findViewById(R.id.text_Nutrition_netCaloriesCalc); final TextView calorieGoal = view.findViewById(R.id.text_Nutrition_goalCalc); caloriesViewModel.getTotalCalories().observe(getViewLifecycleOwner(), new Observer<String>() { @Override public void onChanged(String s) { totalCalorieCalc.setText(s); } }); caloriesViewModel.getNetCalories().observe(getViewLifecycleOwner(), new Observer<String>() { @Override public void onChanged(String s) { netCalorieCalc.setText(s); } }); caloriesViewModel.getGoal().observe(getViewLifecycleOwner(), new Observer<String>() { @Override public void onChanged(String s) { calorieGoal.setText(s); } }); return view; } public CaloriesFragment(){ // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment datafragment. */ public static CaloriesFragment newInstance(String param1, String param2) { CaloriesFragment fragment = new CaloriesFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } }
package com.ism.projects.th; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import com.ism.common.util.Utility; public class THISCardStatementQuery extends EKLStatementQueryService{ protected String startDate = null; protected String endDate = null; // protected static final String CARD_QUERY_PERSONAL_DETAILS ="SELECT BLBFCD NOAKAUN, BLYKCI NOKP,BLBFTX ALMT1,BLBGTX ALMT2,BLBHTX ALMT3,BLFBCD POSKOD,AKBXTX NEGERI , RIGHT(BLJ5CJ,16) NOKAD, BLEVTW NAMA " + // "FROM DPBLCPP " + // "LEFT OUTER JOIN RFAKREP ON BLBKCD = AKBKCD " + // "WHERE BLBFCD = ? " + // "AND BLJACJ = '04'"; // Changed on 16072014 protected static final String CARD_QUERY_PERSONAL_DETAILS ="SELECT BLBFCD NOAKAUN, AGA7CD NOKP, AGBFTX ALMT1, AGBGTX ALMT2, AGBHTX ALMT3, AGFBCD POSKOD, AKBXTX NEGERI, RIGHT(BLJ5CJ,16) NOKAD, AGBETX NAMA " + "FROM DPBLCPP " + "LEFT OUTER JOIN DPAOCPP ON AOBFCD = BLBFCD " + "LEFT OUTER JOIN RFAKREP ON BLBKCD = AKBKCD " + "LEFT OUTER JOIN DPAGREP ON AOA5CD = AGA5CD " + "LEFT OUTER JOIN RFB4REP ON AGFBCD = B4FBCD " + "WHERE BLBFCD = ?"; protected static final String QUERY_CARD_VALIDITY = "SELECT BLBFCD FROM DPBLCPP WHERE BLBFCD = ?"; protected static final String QUERY_CARD_STATEMENT = "SELECT ROW_NUMBER() OVER (ORDER BY BNI0DY ASC) thseq,BNI0DY txdate, BNABDT postdate, " + "CASE WHEN (A9E6TW = 'RTL' OR A9E6TW = 'CSH') THEN RTRIM(A9XZTY)||' - '||LTRIM(RTRIM(BNE3TW)) " + "WHEN A9E6TW = 'CHR' THEN RTRIM(A9XZTY) ELSE '' END description, " + "CASE WHEN BNE5TW = '1' THEN BNF6VC ELSE 0 END txkeluar,CASE WHEN BNE5TW = '2' THEN BNF6VC ELSE 0 END txmasuk " + "FROM DPBNCPP " + "LEFT OUTER JOIN DPBLCPP ON BLBFCD = BNJGCJ AND BLJ5CJ = BNJFCJ " + "LEFT OUTER JOIN RFAKREP ON BLBKCD = AKBKCD " + "LEFT OUTER JOIN THA9REP ON BNE0TW = A9GCCI AND A9GBCI = 'BKRMMYKL' " + "WHERE BNJGCJ = ? " + //--NOAKAUN "AND BNABDT BETWEEN ? AND ? " + //start date, end date "AND BLJACJ = '04' " + //--sts apply = collected "ORDER BY 1"; private static final String MYTAHA_INVALID_ACCOUNT_ERROR = "9000"; private static final String MYTAHA_CARD_NOT_EXIST = "9400"; @Override public byte[] executeService(byte[] in) { exception = null; String result = EKL_UNKNOWN_ERROR; logN("Doing initializeVariables in THISCardStatementQuery"); acctNo = new String(ai.getData()[0][0]).trim(); icNo = new String(ai.getData()[0][1]).trim(); startDate = new String(ai.getData()[0][2]).trim(); endDate = new String(ai.getData()[0][3]).trim(); header = new String(ai.getData()[0][4]).trim(); header = header.substring(7); logN("HEADER = "+header); String eKLTRXIDStampYear = header.substring(0,4); String eKLTRXIDStampMonth = header.substring(4,6); String eKLTRXIDStampDay = header.substring(6,8); String eKLTRXIDStampHH = header.substring(8,10); String eKLTRXIDStampmm = header.substring(10,12); String eKLTRXIDStampss = header.substring(12,14); String eKLTRXIDStampms = header.substring(14); String eklTimeStamp = eKLTRXIDStampYear +"-"+eKLTRXIDStampMonth+"-"+eKLTRXIDStampDay+" "+eKLTRXIDStampHH+":"+eKLTRXIDStampmm+":"+eKLTRXIDStampss+"."+eKLTRXIDStampms; String eklTimeDate = eKLTRXIDStampYear +"-"+eKLTRXIDStampMonth+"-"+eKLTRXIDStampDay; logN("CARD Statement Enquiry for accNo [" + acctNo + "] "); // exception initialize.. exception = null; try { Double AOAOVA = getBalanceDouble(acctNo); if(AOAOVA == null) { if(exception == null) { errorHandle("get balance failed. acct[" + acctNo + "]"); } return appendBytes(MYTAHA_INVALID_ACCOUNT_ERROR.getBytes(), "000".getBytes()); } return queryPersonalDetails(acctNo); } catch (Exception e) { errorHandle("commit failed.[" + e.getMessage(), e); return appendBytes(EKL_UNKNOWN_ERROR.getBytes(), "000".getBytes()); } } @Override protected byte[] queryPersonalDetails(String accountID){ byte[] rtnValue = null; String method = "queryPersonalDetails"; String result = EKL_UNKNOWN_ERROR; String query = CARD_QUERY_PERSONAL_DETAILS; PreparedStatement pstmt = null; ResultSet rs = null; StmtMaster master = new StmtMaster(); try { logV(method + " : query - " + query); pstmt = target.createPreparedStatement(query); Object[] params = { accountID, }; if(!setParameters(target, pstmt, params)) { if(exception == null) { errorHandle(method + " parameter setting failed. acct[" + accountID + "]", target.getException()); } throw exception; } rs = pstmt.executeQuery(); if(rs.next()) { master.thAcct = rs.getString(1); master.thICNo = rs.getString(2); master.thAddress1 = rs.getString(3); master.thAddress2 = rs.getString(4); master.thAddress3 = rs.getString(5); master.thPoskod = rs.getString(6); master.thState = rs.getString(7); master.thCardNo = rs.getString(8); master.thName = rs.getString(9); master.thStmtStartDate = startDate; master.thStmtEndDate = endDate; List<StmtDetail> detail = new ArrayList<StmtDetail>(); // exist record result = queryCardStatement(accountID, detail); if(!result.equals(EKL_SUCCESS)) { if(exception == null) { errorHandle("account statement get failed.[" + accountID + "]"); } result = EKL_UNKNOWN_ERROR; } else { int repeatCount = detail.size(); rtnValue = master.getBytes(); for(int i=0; i<detail.size(); i++) { rtnValue = appendBytes(rtnValue, detail.get(i).getBytes()); } rtnValue = appendBytes(Utility.createLengthAsByte(repeatCount, 3), rtnValue); rtnValue = appendBytes("0000".getBytes(), rtnValue); logN(method + " return [" + new String(rtnValue) + "]"); return rtnValue; } } else { errorHandle(method + " select count is 0. acct[" + accountID + "]"); result = EKL_INVALID_ACCOUNT_NUMBER; } } catch (Exception e) { if(exception == null) { errorHandle(method + " failed to communicate with TH core[" + e.getMessage() + "]", e); } result = EKL_UNKNOWN_ERROR; } finally { close(pstmt, rs); } rtnValue = appendBytes(result.getBytes(), "000".getBytes()); return rtnValue; } private String queryCardStatement(String accountID, List<StmtDetail> list) { String method = "queryCardStatement"; String result = EKL_UNKNOWN_ERROR; String query = QUERY_CARD_STATEMENT; PreparedStatement pstmt = null; ResultSet rs = null; String newStartDate = startDate.substring(0,4)+"-"+startDate.substring(4,6)+"-"+startDate.substring(6,8); String newEndDate = endDate.substring(0,4)+"-"+endDate.substring(4,6)+"-"+endDate.substring(6,8); try { logV(method + " : query - " + query); pstmt = target.createPreparedStatement(query); Object[] params = { accountID, newStartDate, newEndDate, }; if(!setParameters(target, pstmt, params)) { if(exception == null) { errorHandle(method + " parameter setting failed. acct[" + accountID + "]", target.getException()); } throw exception; } rs = pstmt.executeQuery(); int count = 0; while(rs.next()) { // exist record result = EKL_SUCCESS; StmtDetail detail = new StmtDetail(); detail.thSequence = rs.getString(1); Timestamp tsTxDate = rs.getTimestamp(2); detail.txDate = Utility.getFormattedDate("yyyyMMdd", tsTxDate); Timestamp postDate = rs.getTimestamp(3); detail.txPostingDate = Utility.getFormattedDate("yyyyMMdd", postDate); detail.description = rs.getString(4); detail.thTxKeluar = rs.getString(5); detail.thTxMasuk = rs.getString(6); logN("SEQUENCE = "+detail.thSequence); logN("TXDATE = "+detail.txDate); logN("POSTDATE = "+detail.txPostingDate); logN("DESC = "+detail.description); logN("KELUAR = "+detail.thTxKeluar); logN("MASUK = "+detail.thTxMasuk); list.add(detail); count ++; } } catch (Exception e) { if(exception == null) { errorHandle(method + " failed to communicate with TH core[" + e.getMessage() + "]", e); } result = EKL_UNKNOWN_ERROR; } finally { close(pstmt, rs); } return result; } class StmtMaster { String thStmtStartDate = null; String thStmtEndDate = null; String thAcct = null; String thCardNo = null; String thICNo = null; String thName = null; String thAddress1 = null; String thAddress2 = null; String thAddress3 = null; String thPoskod = null; String thState = null; public byte[] getBytes() { byte[] rtn = new byte[8 + 8 + 16 + 19 + 16 + 80 + 80 + 80 + 80 + 80 + 80 ]; int index = 0; System.arraycopy(Utility.fillBlank(thStmtStartDate == null ? new byte[0] : thStmtStartDate.getBytes(), 8).getBytes(), 0, rtn, index, 8); index += 8; System.arraycopy(Utility.fillBlank( thStmtEndDate == null ? new byte[0] : thStmtEndDate.getBytes(), 8).getBytes(), 0, rtn, index, 8); index += 8; System.arraycopy(Utility.fillBlank( thAcct == null ? new byte[0] : thAcct.getBytes(), 16).getBytes(), 0, rtn, index, 16); index += 16; System.arraycopy(Utility.fillBlank( thCardNo == null ? new byte[0] : thCardNo.getBytes(), 19).getBytes(), 0, rtn, index, 19); index += 19; System.arraycopy(Utility.fillBlank( thICNo == null ? new byte[0] : thICNo.getBytes(), 16).getBytes(), 0, rtn, index, 16); index += 16; System.arraycopy(Utility.fillBlank( thName == null ? new byte[0] : thName.getBytes(), 80).getBytes(), 0, rtn, index, 80); index += 80; System.arraycopy(Utility.fillBlank( thAddress1 == null ? new byte[0] : thAddress1.getBytes(), 80).getBytes(), 0, rtn, index, 80); index += 80; System.arraycopy(Utility.fillBlank( thAddress2 == null ? new byte[0] : thAddress2.getBytes(), 80).getBytes(), 0, rtn, index, 80); index += 80; System.arraycopy(Utility.fillBlank( thAddress3 == null ? new byte[0] : thAddress3.getBytes(), 80).getBytes(), 0, rtn, index, 80); index += 80; System.arraycopy(Utility.fillBlank( thPoskod == null ? new byte[0] : thPoskod.getBytes(), 80).getBytes(), 0, rtn, index, 80); index += 80; System.arraycopy(Utility.fillBlank( thState == null ? new byte[0] : thState.getBytes(), 80).getBytes(), 0, rtn, index, 80); index += 80; return rtn; } } /** * Statement detail data class. */ class StmtDetail { String thSequence = null; String txDate = null; String txPostingDate= null; String description = null; String thTxKeluar = null; String thTxMasuk = null; public byte[] getBytes() { byte[] rtn = new byte[5 + 8 + 8 + 80 + 15 + 15 ]; int index = 0; System.arraycopy(Utility.fillBlank( thSequence == null ? new byte[0] : thSequence.getBytes(), 5).getBytes(), 0, rtn, index, 5); index += 5; System.arraycopy(Utility.fillBlank( txDate == null ? new byte[0] : txDate.getBytes(), 8).getBytes(), 0, rtn, index, 8); index += 8; System.arraycopy(Utility.fillBlank(txPostingDate == null ? new byte[0] : txPostingDate.getBytes(), 8).getBytes(), 0, rtn, index, 8); index += 8; System.arraycopy(Utility.fillBlank( description == null ? new byte[0] : description.getBytes(), 80).getBytes(), 0, rtn, index, 80); index += 80; System.arraycopy(Utility.fillBlank( thTxKeluar == null ? new byte[0] : thTxKeluar.getBytes(), 15).getBytes(), 0, rtn, index, 15); index += 15; System.arraycopy(Utility.fillBlank( thTxMasuk == null ? new byte[0] : thTxMasuk.getBytes(), 15).getBytes(), 0, rtn, index, 15); index += 15; return rtn; } } }
package org.digdata.swustoj.hibernate.entiy; /** * UserAuth entity. @author MyEclipse Persistence Tools */ public class UserAuth implements java.io.Serializable { // Fields private Integer id; private String url; private String description; // Constructors /** default constructor */ public UserAuth() { } /** full constructor */ public UserAuth(String url, String description) { this.url = url; this.description = description; } // Property accessors public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getUrl() { return this.url; } public void setUrl(String url) { this.url = url; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } }
import java.io.*; import java.net.Socket; public class SocketInstance extends Socket implements Runnable{ public Socket socket; private BufferedReader bufferedReader; SocketInstance(Socket sk){ this.socket = sk; } @Override public void run() { Boolean connectFlag = true; while(connectFlag) { try { if (bufferedReader == null) { bufferedReader = new BufferedReader(new InputStreamReader(this.socket.getInputStream())); } String msg = bufferedReader.readLine(); if(msg != null) { System.out.println(msg); } if(msg.indexOf("close") != -1){ connectFlag = false; } } catch (IOException e) { e.printStackTrace(); } } try { socket.close(); System.out.println("socket is shutdown"); } catch (IOException e) { e.printStackTrace(); } } }
package com.self.user.sharedpreferencesdemo; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ActivityB extends AppCompatActivity { private TextView tv_greet = null; private Button logoutBtn = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_b); // initialize views tv_greet = findViewById(R.id.tv_greeting); logoutBtn = findViewById(R.id.logout_button); String greetUser = tv_greet.getText().toString(); greetUser = greetUser + "\n" + AppSharedPreferences.getPreferences(getApplicationContext(), AppSharedPreferences.Pref_UserName); tv_greet.setText(greetUser); logoutBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { AppSharedPreferences.clearPreference(getApplicationContext()); startActivity(new Intent(ActivityB.this, ActivityA.class)); finish(); } }); } }
package L2_EstruturaDeDecisao; import java.util.Scanner; public class Exercicio_19 { public static void main(String[] args) { int num; int unidade = 0; int dezena = 0; int centena = 0; int minhar = 0; System.out.println("Digite um numero menor que 1000"); Scanner myObj = new Scanner(System.in); num = myObj.nextInt(); if (num >= 1000) { minhar = num / 1000; centena = (num / 100) % 10; } else { centena = num / 100; } dezena = (num % 100) / 10; unidade = (num % 100) % 10; if (num <= 0) { System.out.println("Algo de errado nao esta certo (1000 < num < 0)"); } if (num >= 1000){ System.out.println(minhar + " unidades de milhares"); } if (num >= 100){ System.out.println(centena + " centenas"); } System.out.println(dezena + " dezenas"); System.out.println(unidade + " unidades"); } }
package com.example.chat.service; import java.util.Optional; public interface ChatRoomService { Optional<String> getChatId(String senderId, String recipientId, boolean createIfNotExist); }
package 笔试题目.剑指offer.数组中前k小的数; import java.util.*; public class Solution { public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) { if (input == null || input.length < k){ return new ArrayList<>(); } buildMinHeap(input); int n = input.length; ArrayList<Integer> result = new ArrayList<>(); for (int i = 0; i < k; ++i){ result.add(input[0]); input[0] = input[--n]; adjustDown(input, 0, n); } return result; } public void buildMinHeap(int[] input){ int start = input.length / 2 - 1; for (int i = start; i >= 0; i--){ adjustDown(input, i, input.length); } } public void adjustDown(int[] input, int parent, int len){ int tmp = input[parent]; for (int child = 2*parent+1; child < len; child = 2*child+1){ if (child < len-1 && input[child] > input[child+1]){ child = child+1; } if (input[child] >= tmp){ break; }else{ int t = input[child]; input[child] = input[parent]; input[parent] = t; parent = child; } } input[parent] = tmp; } public static void main(String[] args){ Solution solution = new Solution(); int[] input = {4,5,1,6,2,7,3,8}; System.out.println(solution.GetLeastNumbers_Solution(input, 4)); } }
package com.example.demo.util; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.*; @ExtendWith(MockitoExtension.class) class MyutilTest { @Mock Myutil myutil; @BeforeEach void setup(){ MockitoAnnotations.initMocks(this); myutil = new Myutil(); } @DisplayName("입력한 날짜까지 앞으로 며칠 남았는가 ?") @Test void findXmaxEve() { System.out.println(myutil.findXmaxEve(LocalDate.now(), 12, 25)); } @Test void FullTime(){ System.out.println(myutil.usedTime("9","30","00","18","00","00")); } }
package com.springD.application.system.controller; import com.springD.application.system.entity.User; import com.springD.application.system.service.UserPermissionService; import com.springD.framework.shiro.ShiroUser; import com.springD.framework.utils.Identities; import com.springD.framework.utils.UserUtils; import com.springD.framework.web.BaseController; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.util.HashMap; import java.util.Map; @Controller public class LoginController extends BaseController{ @Autowired private UserPermissionService userPermissionService; /** * 系统管理员 * @param request * @param response * @return * @throws Exception */ @RequestMapping(value="/system/login",method=RequestMethod.GET) public String systemLogin(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception{ //如果已经登录,跳转 Boolean isCaptchaRequired = UserUtils.isCaptchaRequired(session); request.setAttribute("isCaptchaRequired", isCaptchaRequired); return "login/systemLogin"; } @RequestMapping(value="/system/login",method=RequestMethod.POST) public String sysLoginPost(User crtUser,HttpSession session, HttpServletRequest request, Model model) throws Exception{ return null; } /** */ @RequestMapping(value="/system/admin/changePwd",method=RequestMethod.GET) public String changePwd(HttpSession session,HttpServletRequest request, HttpServletResponse response,Model model){ return "system/admin/changepwd"; } /** */ @RequestMapping(value="/system/admin/changePwd",method=RequestMethod.POST) public String changePwdPost(HttpSession session ,HttpServletRequest request, HttpServletResponse response,Model model, RedirectAttributes redirectAttributes){ String newInputPassword = request.getParameter("hpassword"); String oldInputPassword = request.getParameter("hopassword"); // 用户信息 ShiroUser user =UserUtils.getShiroUser(); String uid = user.getId(); Map param = new HashMap(); param.put("uid", uid); User userTmp = userPermissionService.getOneByMap(param); // 数据库保存的旧密码 String oldPassword = userTmp.getPassword(); String oldSalt = userTmp.getSalt(); if (oldInputPassword == null || !oldPassword.equals(Identities.md5Password(oldSalt, oldInputPassword))) { model.addAttribute("message", "修改失败,旧密码错误"); return "system/changepwd"; } // 生成新密码并更新 String salt = Identities.randomBase62(8); String password = Identities.md5Password(salt, newInputPassword); Map map = new HashMap(); map.put("uid", uid); map.put("password", password); map.put("salt", salt); userPermissionService.updateUserByUid(map); // 添加提示信息 addMessage(redirectAttributes, "修改成功!"); return "redirect:/system/admin"; } /** * 退出登陆 * @return * @throws Exception */ @RequestMapping(value="/logout") public String logout(HttpSession session) throws Exception{ Subject subject = SecurityUtils.getSubject(); if (subject != null) { subject.logout(); } //销毁session session.invalidate(); return "login/login"; } /** * @Description: 无权限提示页面 * @return * @throws Exception */ @RequestMapping(value="/login/unauth") public String unauth(HttpServletRequest request ,Model model) throws Exception{ String url = ""; // 取用户权限 ShiroUser user =UserUtils.getShiroUser(); if (user != null && user.getRoleId() != null) { Integer roleId = Integer.parseInt(user.getRoleId()); // 客服 url="http://www.baidu.com"; } else { url="http://www.baidu.com"; } model.addAttribute("url", url); return "exception/unauth"; } }
package com.evature.evasdk.appinterface; import com.evature.evasdk.EvaChatApi; /** * Created by iftah on 22/02/2016. */ public interface EvaLifeCycleListener { void onPause(); void onResume(EvaChatApi chatScreen); }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.dao.annotation; import java.lang.annotation.Annotation; import org.springframework.aop.framework.autoproxy.AbstractBeanFactoryAwareAdvisingPostProcessor; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.stereotype.Repository; import org.springframework.util.Assert; /** * Bean post-processor that automatically applies persistence exception translation to any * bean marked with Spring's @{@link org.springframework.stereotype.Repository Repository} * annotation, adding a corresponding {@link PersistenceExceptionTranslationAdvisor} to * the exposed proxy (either an existing AOP proxy or a newly generated proxy that * implements all of the target's interfaces). * * <p>Translates native resource exceptions to Spring's * {@link org.springframework.dao.DataAccessException DataAccessException} hierarchy. * Autodetects beans that implement the * {@link org.springframework.dao.support.PersistenceExceptionTranslator * PersistenceExceptionTranslator} interface, which are subsequently asked to translate * candidate exceptions. * * <p>All of Spring's applicable resource factories (e.g. * {@link org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean}) * implement the {@code PersistenceExceptionTranslator} interface out of the box. * As a consequence, all that is usually needed to enable automatic exception * translation is marking all affected beans (such as Repositories or DAOs) * with the {@code @Repository} annotation, along with defining this post-processor * as a bean in the application context. * * <p>As of 5.3, {@code PersistenceExceptionTranslator} beans will be sorted according * to Spring's dependency ordering rules: see {@link org.springframework.core.Ordered} * and {@link org.springframework.core.annotation.Order}. Note that such beans will * get retrieved from any scope, not just singleton scope, as of this 5.3 revision. * * @author Rod Johnson * @author Juergen Hoeller * @since 2.0 * @see PersistenceExceptionTranslationAdvisor * @see org.springframework.stereotype.Repository * @see org.springframework.dao.DataAccessException * @see org.springframework.dao.support.PersistenceExceptionTranslator */ @SuppressWarnings("serial") public class PersistenceExceptionTranslationPostProcessor extends AbstractBeanFactoryAwareAdvisingPostProcessor { private Class<? extends Annotation> repositoryAnnotationType = Repository.class; /** * Set the 'repository' annotation type. * The default repository annotation type is the {@link Repository} annotation. * <p>This setter property exists so that developers can provide their own * (non-Spring-specific) annotation type to indicate that a class has a * repository role. * @param repositoryAnnotationType the desired annotation type */ public void setRepositoryAnnotationType(Class<? extends Annotation> repositoryAnnotationType) { Assert.notNull(repositoryAnnotationType, "'repositoryAnnotationType' must not be null"); this.repositoryAnnotationType = repositoryAnnotationType; } @Override public void setBeanFactory(BeanFactory beanFactory) { super.setBeanFactory(beanFactory); if (!(beanFactory instanceof ListableBeanFactory lbf)) { throw new IllegalArgumentException( "Cannot use PersistenceExceptionTranslator autodetection without ListableBeanFactory"); } this.advisor = new PersistenceExceptionTranslationAdvisor(lbf, this.repositoryAnnotationType); } }
package com.b.test.common; import org.apache.commons.lang.math.RandomUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Random; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 字符串工具类 * * @author LiszAdmin */ public class StringUtils { /** * Logger for this class */ private static final Logger logger = LoggerFactory.getLogger(StringUtils.class); private static final String[] labelColor = {"226dd6", "eb6238", "009687", "fa8c8c", "ffd080"}; /** * 验证邮箱 * * @param email * @return */ public static boolean checkEmail(String email) { boolean flag = false; try { String check = "^([a-z0-9A-Z]+[-|_|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$"; Pattern regex = Pattern.compile(check); Matcher matcher = regex.matcher(email); flag = matcher.matches(); } catch (Exception e) { flag = false; } return flag; } /** * 检查是不是都是数字 * * @param number * @return */ public static boolean checkNumber(String number) { boolean flag; try { Pattern regex = Pattern.compile("^[0-9]*$"); Matcher matcher = regex.matcher(number); flag = matcher.matches(); } catch (Exception e) { e.printStackTrace(); flag = false; } return flag; } /** * 验证手机号 * @param phone * @return */ public static boolean checkPhone(String phone) { boolean flag; try { Pattern regex = Pattern.compile("^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$"); Matcher matcher = regex.matcher(phone); flag = matcher.matches(); } catch (Exception e) { e.printStackTrace(); flag = false; } return flag; } /** * 验证身份证号 * @param idCard * @return */ public static boolean checkIdCard(String idCard) { boolean flag; try { Pattern regex = Pattern.compile("^\\d{6}(18|19|20)?\\d{2}(0[1-9]|1[012])(0[1-9]|[12]\\d|3[01])\\d{3}(\\d|[xX])$"); Matcher matcher = regex.matcher(idCard); flag = matcher.matches(); } catch (Exception e) { e.printStackTrace(); flag = false; } return flag; } /** * 比较两个用","分割的字符串,之间的内容是否一样 * * @param firstStr * @param secondStr * @return */ public static boolean compareStrSplitByComma(String firstStr, String secondStr) { if (firstStr == null || secondStr == null) { return false; } String[] firstArray = firstStr.split(","); String[] secondArray = secondStr.split(","); Map secondStrMap = new HashMap(); if (firstArray.length != secondArray.length) { return false; } for (int i = 0; i < secondArray.length; i++) { secondStrMap.put(secondArray[i], secondArray[i]); } for (int i = 0; i < firstArray.length; i++) { if (!secondStrMap.containsKey(firstArray[i])) { return false; } } return true; } /** * 将指定double类型转换为金钱格式字符 * * @param doubleValue * @return String */ public static String doubleToCurrency(double doubleValue) { Object[] args = {new Double(doubleValue)}; return MessageFormat.format("{0,number,¥,#,###,###,###,###,###,##0.00}", args); } /** * 将字符串对象按srcEncoding编码转换为destEncoding编码格 * * @param stringValue * @param srcEncoding * @param destEncoding * @return String */ public static String encodeString(String stringValue, String srcEncoding, String destEncoding) { // 如果参数为null,返回null if (stringValue == null || srcEncoding == null || destEncoding == null) { return null; } String value = null; try { value = new String(stringValue.getBytes(srcEncoding), destEncoding); } catch (UnsupportedEncodingException ex) { value = stringValue; } return value; } /** * 判断是否指定字符串为空字符串(null或者长度为0 * * @param stringValue * @return boolean */ public static boolean isEmptyString(String stringValue) { if (stringValue == null || stringValue.trim().length() < 1 || stringValue.trim().equalsIgnoreCase("null")) { return true; } else { return false; } } /** * 判断是否指定字符串为空字符串(null或者长度为0 * * @param stringValue * @return boolean */ public static boolean isEmpty(String stringValue) { if (stringValue == null || stringValue.trim().length() < 1 || stringValue.trim().equalsIgnoreCase("null")) { return true; } else { return false; } } /** * isEmpty:判断数组是否为空. <br/> * * @param stringArray * @return * @author Haibo * @since JDK 1.6 */ public static boolean isEmpty(String[] stringArray) { if (stringArray == null || stringArray.length == 0) { return true; } else { return false; } } /** * 判断是否指定字符串为空字符串(null或者长度为0 * * @param stringValue * @return boolean */ public static boolean isNotEmpty(String stringValue) { if (stringValue == null || stringValue.trim().length() < 1 || stringValue.trim().equalsIgnoreCase("null")) { return false; } else { return true; } } public static boolean isNumber(String str) { if (StringUtils.isEmptyString(str)) { return false; } for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (ch < '0' || ch > '9') { return false; } } return true; } public static boolean isDouble(String str) { try { Double.parseDouble(str); return true; } catch (NumberFormatException e) { return false; } } /** * 将十进制数字字符串转换为整型数字,如果转换失败返回- * * @param stringValue * @return int */ public static int stringToInt(String stringValue) { return stringToInt(stringValue, -1); } /** * 将十进制数字字符串转换为整型数字,如果转换失败返回默认 * * @param stringValue * @param defaultValue * @return int */ public static int stringToInt(String stringValue, int defaultValue) { int intValue = defaultValue; if (stringValue != null) { try { intValue = Integer.parseInt(stringValue); } catch (NumberFormatException ex) { intValue = defaultValue; } } return intValue; } /** * 将指定字符串对象默认编码IOS8859_1编码转为GBK编码的字符串对 * * @param stringValue * @return String */ public static String toGBKString(String stringValue) { return encodeString(stringValue, "ISO8859_1", "GBK"); } /** * 构造函数 */ public StringUtils() { } /** * 两个值是否相等 (参数如果是空则为false) * * @param string * @param value * @return */ public static boolean isEquals(Object string, Object value) { return string != null && value != null && string.toString().equals(value.toString()); } public static boolean isNotNull(String str) { if (str == null || str.equals("")) { return false; } return true; } public static boolean isNULL(Object o) { if (o == null) { return true; } if (o instanceof String) { return isEmpty((String) o); } return false; } public static boolean isNotNULL(Object o) { return !isNULL(o); } /** * 修改字符串加‘’ 比如:str=1,2,3 改成str='1','2','3' * * @param strs * @return * @author Haibo-W 2016年2月1日 下午6:00:03 */ public static String stradd(String strs) { StringBuffer stradd = new StringBuffer(); String[] str = strs.split(","); if (str.length > 0) { for (int i = 0; i < str.length; i++) { String strEnd = str[i].replace("&&**", ""); stradd.append("'" + strEnd + "',"); } String result = stradd.toString().substring(0, stradd.toString().length() - 1); return result; } return ""; } /** * 去掉左右空格 如果有值就去除空格 否則默认值 * * @param strs * @return */ public static String strRemoveNull(String strs) { String strNoNull = ""; if (StringUtils.isNotEmpty(strs)) { strNoNull = strs.trim(); } return strNoNull; } /** * strConvertInt:字符串转换成 * * @param str * @param defaultVal * @author yingmm * @since JDK 1.6 */ public static Integer strConvertInt(String str, Integer defaultVal) { Integer returnVal = 0; try { if (StringUtils.isNotEmpty(str)) { returnVal = Integer.valueOf(str); } } catch (Exception e) { return defaultVal = defaultVal != null ? defaultVal : returnVal; } return returnVal; } /** * 随机获取几位包含数字和英文的验证码 * * @return */ public static String getFourAuth(int lenght) { if (lenght < 1) { lenght = 4; } String str = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z"; String str2[] = str.split(","); Random rand = new Random(); int index = 0; String randStr = ""; randStr = ""; for (int i = 0; i < lenght; ++i) { index = rand.nextInt(str2.length - 1); randStr += str2[index]; } return randStr.toUpperCase(); } /** * splitStr: 字符串转 字符串数组 * * @author yingmm * @date:Mar 24, 2015 2:56:21 PM * @description */ public static String[] splitCovStr(String str) { if (StringUtils.isEmpty(str)) { return new String[]{}; } return str.split(","); } /** * strConvertInt:字符串数组转换成字符串 * * @param str * @author yuse * @since JDK 1.6 */ public static String strArrayConvertString(String[] str) { StringBuffer sb = new StringBuffer(); String s = ""; try { if (str.length > 0) { for (int i = 0; i < str.length; i++) { sb.append(str[i]); sb.append(","); } s = sb.substring(0, sb.length() - 1); } } catch (Exception e) { return ""; } return s; } public static boolean isValidDate(String str) { boolean convertSuccess = true; SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { format.setLenient(false); format.parse(str); } catch (Exception e) { convertSuccess = false; } return convertSuccess; } public static String UrlDecode(String value, String encode) { String returnValue = ""; try { returnValue = URLDecoder.decode(value, encode); } catch (Exception e) { logger.error("url解析错误" + e.getMessage(), e); } return returnValue; } /** * 获取请求的内网ip * * @param request * @return * @throws Exception */ public static String getIpAddr(HttpServletRequest request) throws Exception { String ip = request.getHeader("X-Real-IP"); if (!StringUtils.isEmptyString(ip) && !"unknown".equalsIgnoreCase(ip)) { return ip; } ip = request.getHeader("X-Forwarded-For"); if (!StringUtils.isEmptyString(ip) && !"unknown".equalsIgnoreCase(ip)) { // 多次反向代理后会有多个IP值,第一个为真实IP。 int index = ip.indexOf(','); if (index != -1) { return ip.substring(0, index); } else { return ip; } } else { return request.getRemoteAddr(); } } /** * 获取操作系统,浏览器及浏览器版本信息 * * @param request * @return */ public static String getOsAndBrowserInfo(HttpServletRequest request) { String browserDetails = request.getHeader("User-Agent"); String userAgent = browserDetails; if (isNotEmpty(userAgent)) { String user = userAgent.toLowerCase(); //获取操作系统 String os = ""; //获取浏览器 和版本信息 String browser = ""; //=================OS Info======================= if (userAgent.toLowerCase().indexOf("windows") >= 0) { os = "Windows"; } else if (userAgent.toLowerCase().indexOf("mac") >= 0) { os = "Mac"; } else if (userAgent.toLowerCase().indexOf("x11") >= 0) { os = "Unix"; } else if (userAgent.toLowerCase().indexOf("android") >= 0) { os = "Android"; } else if (userAgent.toLowerCase().indexOf("iphone") >= 0) { os = "IPhone"; } else { os = "UnKnown, More-Info: " + userAgent; } //===============Browser=========================== if (isNotEmpty(user)) { if (user.contains("edge")) { browser = (userAgent.substring(userAgent.indexOf("Edge")).split(" ")[0]).replace("/", "-"); } else if (user.contains("msie")) { String substring = userAgent.substring(userAgent.indexOf("MSIE")).split(";")[0]; browser = substring.split(" ")[0].replace("MSIE", "IE") + "-" + substring.split(" ")[1]; } else if (user.contains("safari") && user.contains("version")) { browser = (userAgent.substring(userAgent.indexOf("Safari")).split(" ")[0]).split("/")[0] + "-" + (userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1]; } else if (user.contains("opr") || user.contains("opera")) { if (user.contains("opera")) { browser = (userAgent.substring(userAgent.indexOf("Opera")).split(" ")[0]).split("/")[0] + "-" + (userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1]; } else if (user.contains("opr")) { browser = ((userAgent.substring(userAgent.indexOf("OPR")).split(" ")[0]).replace("/", "-")) .replace("OPR", "Opera"); } } else if (user.contains("chrome")) { browser = (userAgent.substring(userAgent.indexOf("Chrome")).split(" ")[0]).replace("/", "-"); } else if ((user.indexOf("mozilla/7.0") > -1) || (user.indexOf("netscape6") != -1) || (user.indexOf("mozilla/4.7") != -1) || (user.indexOf("mozilla/4.78") != -1) || (user.indexOf("mozilla/4.08") != -1) || (user.indexOf("mozilla/3") != -1)) { browser = "Netscape-?"; } else if (user.contains("firefox")) { browser = (userAgent.substring(userAgent.indexOf("Firefox")).split(" ")[0]).replace("/", "-"); } else if (user.contains("rv")) { String IEVersion = (userAgent.substring(userAgent.indexOf("rv")).split(" ")[0]).replace("rv:", "-"); browser = "IE" + IEVersion.substring(0, IEVersion.length() - 1); } else { browser = "UnKnown, More-Info: " + userAgent; } } return "" + browser; } return null; } /** * 随机生成产品号 * @return */ public static String randomOrderId() { SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmm"); int i = (int)(Math.random()*900+100); String s = "T"+sdf.format(new Date()) + i; return s; } /** * 随机生成邀请码 * @return */ public static String randomInvitationCode(){ int i = RandomUtils.nextInt(1000000); return i+""; } /** * 生成单号前面的日期 * @return */ public static String randomOrderCode(String px){ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS"); String s = px+sdf.format(new Date()); return s; } /** * 获取当前时间时分秒并返回字符串 * @return */ public static String getDateHms(){ Date date =new Date(); SimpleDateFormat sdf =new SimpleDateFormat("HHmmss"); String time=sdf.format(date); return time; } public static String randomLabelColor(){ int len = RandomUtils.nextInt(labelColor.length); return labelColor[len]; } }
// inherit class ExerciseI6 public class ExerciseI8 extends ExerciseI6 { // Euclidean algorithm without the use of modulo function public void calc() { while(this.getM() != this.getN()) { while(getM() > getN()) { setM(getM() - getN()); } while(getN() > getM()) { setN( getN() - getM()); } } setK(getM()); } }
package mc.kurunegala.bop.model; public class NeedDoc { private Integer idneeddoc; private Integer needdocPriority; private Integer applicationCatagoryIdapplicationCatagory; private Integer doccatIddoccat; public Integer getIdneeddoc() { return idneeddoc; } public void setIdneeddoc(Integer idneeddoc) { this.idneeddoc = idneeddoc; } public Integer getNeeddocPriority() { return needdocPriority; } public void setNeeddocPriority(Integer needdocPriority) { this.needdocPriority = needdocPriority; } public Integer getApplicationCatagoryIdapplicationCatagory() { return applicationCatagoryIdapplicationCatagory; } public void setApplicationCatagoryIdapplicationCatagory(Integer applicationCatagoryIdapplicationCatagory) { this.applicationCatagoryIdapplicationCatagory = applicationCatagoryIdapplicationCatagory; } public Integer getDoccatIddoccat() { return doccatIddoccat; } public void setDoccatIddoccat(Integer doccatIddoccat) { this.doccatIddoccat = doccatIddoccat; } public Doccat getDocCat() { return docCat; } public void setDocCat(Doccat docCat) { this.docCat = docCat; } private Doccat docCat; }
package me.libraryaddict.disguise; import java.util.Arrays; import java.util.List; import me.libraryaddict.disguise.disguisetypes.Disguise; import static me.libraryaddict.disguise.disguisetypes.DisguiseType.*; import me.libraryaddict.disguise.disguisetypes.DisguiseType; public class DisallowedDisguises { public static final List<DisguiseType> forbiddenDisguises = Arrays.asList(FISHING_HOOK, ITEM_FRAME, ENDER_DRAGON, PLAYER, GIANT, GHAST, MAGMA_CUBE, SLIME, DROPPED_ITEM, ENDER_CRYSTAL, AREA_EFFECT_CLOUD, WITHER); public static boolean disabled = false; public static boolean isAllowed(Disguise disguise) { return isAllowed(disguise.getType()); } public static boolean isAllowed(DisguiseType type) { if (forbiddenDisguises.contains(type)) { return false; } return true; } }
package se.kth.kthfsdashboard.util; import java.text.DecimalFormat; import junit.framework.TestCase; /** * * @author Hamidreza Afzali <afzali@kth.se> */ public class FormatterTest extends TestCase { Formatter f = new Formatter(); final Long K = 1024L; final Long M = K * K; final Long G = M * K; final Long T = G * K; public FormatterTest(String testName) { super(testName); } public void testParseDouble() throws Exception { assertEquals("1 TB", f.storage(T)); assertEquals("1.1 TB", f.storage(T + 99*G)); } }
package com.eme.aelegant.model.net; import com.eme.aelegant.model.net.api.ZhihuApi; import com.eme.aelegant.model.net.converter.FastJsonConverterFactory; import com.facebook.stetho.okhttp3.StethoInterceptor; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; /** * Created by dijiaoliang on 17/3/2. */ public class ApiClient { private static Retrofit retrofit; private static void checkInstance() { if(retrofit==null){ synchronized (ApiClient.class){ if(retrofit==null){ OkHttpClient.Builder builder = new OkHttpClient().newBuilder(); if (ApiConstant.DEBUG) { HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); builder.addInterceptor(httpLoggingInterceptor).addNetworkInterceptor(new StethoInterceptor()); } OkHttpClient client = builder.build(); retrofit = new Retrofit.Builder() .baseUrl(ApiConstant.API_HOST) .addConverterFactory(FastJsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(client) .build(); } } } } public static ZhihuApi getZhihuApi() { checkInstance(); return retrofit.create(ZhihuApi.class); } }
package com.madrapps.dagger.models; import dagger.multibindings.Multibinds; import javax.inject.Inject; import java.util.Map; public class Alley implements Road { public final Map<String, Vehicle> vehicleMap; public final Vehicle vehicle; @Inject Alley(Map<String, Vehicle> vehicleMap, Truck truck) { this.vehicleMap = vehicleMap; vehicle = truck; } }
package com.aisino.invoice.xtsz.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.aisino.invoice.xtjk.po.FwkpQyxx; import com.aisino.invoice.xtjk.po.FwkpXtjkSearch; /** * @ClassName: FwkpQyxxMapper * @Description: * @date 2017年5月22日 下午6:37:11 * @Copyright 2017 航天信息股份有限公司-版权所有 */ public interface FwkpQyxxMapper { //获取企业信息 public List<FwkpQyxx> GetAllQysb(FwkpXtjkSearch fwkpXtjkSearch); public List<String> GetQysb(@Param("user_id")String user_id); //更新企业信息 public void UpdateQyxx(FwkpQyxx fwkpQyxx); }
package com.scf.module.security.interceptor; import java.util.Arrays; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import com.scf.core.constant.CommonConstants; import com.scf.core.context.ContextHolder; import com.scf.core.context.Identity; import com.scf.core.context.IdentityContext; import com.scf.core.context.SwitchContext; import com.scf.module.security.matcher.RequestMatcher; import com.scf.module.security.meta.Permission; import com.scf.module.security.meta.support.PermissionMetaProvider; import com.scf.utils.JacksonObjectMapper; import com.scf.utils.StringUtilies; import com.scf.utils.WebUtilies; import com.scf.web.comp.ace.ResponseMessage; /** * 权限拦截器 * @author wubin * @date 2016年8月3日 上午9:47:49 * @version V1.1.0 */ public class AuthorityInterceptor extends HandlerInterceptorAdapter { private static final Logger logger = LoggerFactory.getLogger(AuthorityInterceptor.class); private PermissionMetaProvider permissionMetaProvider; // 公用请求路径,只需要登录即可访问 private List<String> baseUrl; @SuppressWarnings("unchecked") @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { IdentityContext identityContext = ContextHolder.getIdentityContext(); Identity userIdentity = identityContext.getIdentity(); // 会话中没有实体返回登录页面 if (userIdentity == null) { // 用户没有资源使用权限处理 logger.warn("会话超时============"); if (WebUtilies.isAjaxRequest(request)) { response.getWriter().write(JacksonObjectMapper.toJsonString(ResponseMessage.error("noLogin", "未登录"))); } else { response.sendRedirect(request.getContextPath()); } return false; } else { /** * 鉴权开关 */ if (SwitchContext.isOpen("switch_authorization")) { // 对模块权限进行判断.baseUrl放过 String moduleValue = getCurrentModuleValue(request); boolean isBaseUrl = checkBaseUrl(moduleValue); if (isBaseUrl) { return true; } //用户的权限集字符串,逗号隔开,登陆的时候保存user_modules到identity中 List<String> moduleList = (List<String>) userIdentity.getData(CommonConstants.IDENTITY_KEY_USER_MODULES); String modules = StringUtilies.listToString(moduleList); boolean hasModulePermission = verifier(modules, moduleValue, request); if (!hasModulePermission) { if (WebUtilies.isAjaxRequest(request)) { response.getWriter().write(JacksonObjectMapper.toJsonString(ResponseMessage.error("noPermission", "无权限,请联系管理员"))); return false; } else { response.sendRedirect(request.getContextPath() + "/errors/noPermission.html"); return false; } } } else { return true; } } return true; } /** * 判断是否基本url路径 * */ public boolean checkBaseUrl(String currentUrl) { if (CollectionUtils.isEmpty(baseUrl)) { return true; } if (baseUrl.contains(currentUrl)) { return true; } return false; } /** * 从请求中获取权限路径 * */ public static String getCurrentModuleValue(HttpServletRequest request) { String privilegeValue = request.getRequestURI(); String contextPath = request.getContextPath(); if (contextPath != null && contextPath.length() > 0) { privilegeValue = privilegeValue.substring(contextPath.length()); } return privilegeValue; } /** * 判断是否有模块权限,所有请求都拦截 * */ public boolean verifier(String modules, String moduleValue, HttpServletRequest request) { boolean hasThisPermission = false; /** * 获取请求对应的权限code */ String moduleCode = getModuleCode(moduleValue, request); /** * 没有找到请求url的配置,请提示无权限 */ if (StringUtils.isEmpty(moduleCode)) { return hasThisPermission; } if (!StringUtils.isEmpty(modules)) { String[] moduleArr = modules.split(","); List<String> moduleList = Arrays.asList(moduleArr); if (!CollectionUtils.isEmpty(moduleList)) { for (String module : moduleList) { if (module.equalsIgnoreCase(moduleCode)) { hasThisPermission = true; break; } } } } if (!hasThisPermission) { IdentityContext identityContext = ContextHolder.getIdentityContext(); Identity userIdentity = identityContext.getIdentity(); logger.warn("[system:{},userid:{}] doesn't have the request permission of \"{}\"", new Object[]{CommonConstants.CURRENT_SYSTEM,userIdentity.getId(), moduleValue}); } return hasThisPermission; } /** * 从全局配置中获取当前请求的权限key * * @param moduleValue * @return */ public String getModuleCode(String moduleValue, HttpServletRequest request) { String moduleCode = null; List<Permission> permission = permissionMetaProvider.getPermissionMeta(); if (CollectionUtils.isEmpty(permission)) { return null; } for (Permission permissionTemp : permission) { RequestMatcher requestMatcher = permissionTemp.getRequestMatcher(); boolean isMatch = requestMatcher.matches(request); if (isMatch) { moduleCode = permissionTemp.getCode(); break; } } return moduleCode; } /** * @return 返回 baseUrl */ public List<String> getBaseUrl() { return baseUrl; } /** * @param 对baseUrl进行赋值 */ public void setBaseUrl(List<String> baseUrl) { this.baseUrl = baseUrl; } /** * @return permissionMetaProvider */ public PermissionMetaProvider getPermissionMetaProvider() { return permissionMetaProvider; } /** * @param permissionMetaProvider 设置 permissionMetaProvider */ public void setPermissionMetaProvider(PermissionMetaProvider permissionMetaProvider) { this.permissionMetaProvider = permissionMetaProvider; } }
package com.cosplay.demo.mvp.model; /** * Created by zhiwei.wang on 2017/3/22. */ public interface UserModel { }
/* * 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 servlet.common.cookie; import java.io.IOException; import javax.servlet.http.Cookie; import servlet.login.GooglePojo; import servlet.login.GoogleUtils; /** * * @author dangminhtien */ public class GoogleAuthCookie extends CookieParseable { public static final String COOKIE_NAME = "GG_ACCESS_TOKEN"; private GooglePojo googlePojo; private String accessToken; public GoogleAuthCookie() { } public GoogleAuthCookie(String accessToken) throws IOException { this.accessToken = accessToken; googlePojo = GoogleUtils.getUserInfo(accessToken); } @Override public boolean parseFromCookie(Cookie cookie) { String cookieName = cookie.getName(); if (cookieName.equals(COOKIE_NAME)) { try { this.accessToken = cookie.getValue(); this.googlePojo = GoogleUtils.getUserInfo(accessToken); return true; } catch (IOException ex) { return false; } } return false; } public GooglePojo getGooglePojo() { return googlePojo; } public String getAccessToken() { return accessToken; } @Override public Cookie getCookie() { return new Cookie (COOKIE_NAME, this.accessToken); } }
package com.tretiakov.app; public class App { public static void main( String[] args ) { GameLogic gameLogic = new GameLogic(); gameLogic.gameGycle(); } }
package com.remote_interface; import java.rmi.Remote; import java.rmi.RemoteException; import java.util.ArrayList; import com.model.Commodity; import com.model.ImportBill; import com.model.PortBillItem; public interface IImportService extends Remote{ /** * 根据编号查找商品 * @param no * @return 不存在 null * @throws RemoteException */ public Commodity getCommodity(String no)throws RemoteException; /** * 进货单 自动生成no 成功dialog * @param customerNo * @param warehouse * @param operator * @param list geshi :no+","+quantity+","+inprice+","+total * @param total * @param desc * @throws RemoteException */ public void addImportBill(String customerNo,String warehouse,String operator,ArrayList<String> list,double total,String desc,String time)throws RemoteException; /** * 根据编号获得bill * @param no * @return 不存在null * @throws RemoteException */ public ImportBill getImportBill(String no)throws RemoteException; /** * 获得此单的商品项 * @param no * @return * @throws RemoteException */ public ArrayList<PortBillItem> getBillItem(String no)throws RemoteException; /** * 进货退货单 自动生成no 成功dialog * @param no 进货单的no * @param operator * @param desc */ public void addImportBackBill(String no,String operator,String desc,String time)throws RemoteException; }
package ir.madreseplus.data.model.res; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class TicketInfoRes { @SerializedName("cluster") @Expose public Integer cluster; @SerializedName("created_on") @Expose public String createdOn; @SerializedName("get_cluster_display") @Expose public String getClusterDisplay; @SerializedName("get_priority_display") @Expose public String getPriorityDisplay; @SerializedName("get_status_display") @Expose public String getStatusDisplay; @SerializedName("id") @Expose public Integer id; @SerializedName("priority") @Expose public Integer priority; @SerializedName("replies") @Expose public List<ReplyRes> replies = null; @SerializedName("status") @Expose public Integer status; @SerializedName("text") @Expose public String text; @SerializedName("title") @Expose public String title; public Integer getId() { return this.id; } public void setId(Integer num) { this.id = num; } public String getTitle() { return this.title; } public void setTitle(String str) { this.title = str; } public String getText() { return this.text; } public void setText(String str) { this.text = str; } public Integer getCluster() { return this.cluster; } public void setCluster(Integer num) { this.cluster = num; } public String getGetClusterDisplay() { return this.getClusterDisplay; } public void setGetClusterDisplay(String str) { this.getClusterDisplay = str; } public Integer getStatus() { return this.status; } public void setStatus(Integer num) { this.status = num; } public String getGetStatusDisplay() { return this.getStatusDisplay; } public void setGetStatusDisplay(String str) { this.getStatusDisplay = str; } public String getCreatedOn() { return this.createdOn; } public void setCreatedOn(String str) { this.createdOn = str; } public List<ReplyRes> getReplies() { return this.replies; } public void setReplies(List<ReplyRes> list) { this.replies = list; } public Integer getPriority() { return this.priority; } public void setPriority(Integer num) { this.priority = num; } public String getGetPriorityDisplay() { return this.getPriorityDisplay; } public void setGetPriorityDisplay(String str) { this.getPriorityDisplay = str; } }
import static io.restassured.RestAssured.given; import io.restassured.specification.RequestSpecification; public class ssss { @Test public static RequestSpecification setup() { RequestSpecification res = given().auth().basic("sk_test_Mk8ZqJJp6vy4jRm7pKiCA4vt", ""); return res; } }
package structural.decorator.my.htmldemo.decorators; import structural.decorator.my.htmldemo.htmlnodes.HtmlNode; // 附加 <underline> 标签 public class UnderlineDecorator extends Decorator{ public UnderlineDecorator(HtmlNode node) { super(node); } @Override public String getText() { return "<underline>" + super.getText() + "</underline>"; } }
package ca.oneroof.oneroof.ui; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.databinding.DataBindingUtil; import java.util.function.Consumer; import ca.oneroof.oneroof.R; import ca.oneroof.oneroof.api.Debt; import ca.oneroof.oneroof.databinding.ItemDebtBinding; import ca.oneroof.oneroof.ui.common.ClickCallback; import ca.oneroof.oneroof.ui.common.DataBoundListAdapter; public class DebtListAdapter extends DataBoundListAdapter<Debt, ItemDebtBinding> { private final Consumer<Debt> callback; public DebtListAdapter(Consumer<Debt> callback) { this.callback = callback; } @Override protected ItemDebtBinding createBinding(ViewGroup parent) { return DataBindingUtil .inflate(LayoutInflater.from(parent.getContext()), R.layout.item_debt, parent, false); } @Override protected void bind(ItemDebtBinding binding, Debt item) { binding.setDebt(item); binding.setCallback(new ClickCallback() { @Override public void click(View v) { callback.accept(item); } }); } }
//даны элементы, вывести элементы со сдвигом на n. package different; import java.util.Scanner; import java.util.Arrays; public class diff_11 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); //"11 34 3 45 23 5 67"; int[] array = Arrays.stream(str.split(" ")).mapToInt(Integer::parseInt).toArray(); //Это для перевода строки String в Int массив int len = array.length; int n = scanner.nextInt(); if (n > len){ n = n % len; } int [] array2 = new int[len]; for(int j = 0; j < n; j++){ array2[j] = array[len - n + j]; System.out.print(array2[j] + " "); } for(int i = n; i < len; i++){ array2[i] = array[i - n]; System.out.print(array2[i] + " "); } //System.out.println(Arrays.toString(array2)); } }
package framework; /** * Created by kilo on 2018/8/14. * 继承了java.lang.Cloneable接口,可以调用Object.clone()方法自动复制实例 */ public interface Product extends Cloneable { void use(String s); /** * 调用clone方法自动复制实例 * * @return */ Product createClone(); }
package com.travel.lodge.userservice.dto; import lombok.Data; @Data public class UpdateUserRequest { private String firstName; private String lastName; private String contactNo; private String location; private String activityStatus; }
package com.spring.minjun.user.model; import java.util.Date; public class UserVO { private String account; private String password; private String name; private Integer checkId; private String sessionId; private Date limitTime; //자동로그인 체크 여부 private boolean autoLogin; public String getSessionId() { return sessionId; } public void setSessionId(String sessionId) { this.sessionId = sessionId; } public Date getLimitTime() { return limitTime; } public void setLimitTime(Date limitTime) { this.limitTime = limitTime; } public boolean isAutoLogin() { return autoLogin; } public void setAutoLogin(boolean autoLogin) { this.autoLogin = autoLogin; } public Integer getCheckId() { return checkId; } public void setCheckId(Integer checkId) { this.checkId = checkId; } public String getAccount() { return account; } public void setAccount(String account) { this.account = account; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.gxtc.huchuan.ui.deal.deal; import android.content.Intent; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.gxtc.commlibrary.base.BaseRecyclerAdapter; import com.gxtc.commlibrary.base.BaseTitleFragment; import com.gxtc.commlibrary.recyclerview.RecyclerView; import com.gxtc.commlibrary.recyclerview.wrapper.LoadMoreWrapper; import com.gxtc.commlibrary.utils.EventBusUtil; import com.gxtc.commlibrary.utils.GotoUtil; import com.gxtc.commlibrary.utils.ToastUtil; import com.gxtc.huchuan.Constant; import com.gxtc.huchuan.R; import com.gxtc.huchuan.adapter.Deal1LevelAdapter; import com.gxtc.huchuan.bean.DealData; import com.gxtc.huchuan.bean.NewsAdsBean; import com.gxtc.huchuan.bean.event.EventScorllTopBean; import com.gxtc.huchuan.data.UserManager; import com.gxtc.huchuan.im.ui.ConversationListActivity; import com.gxtc.huchuan.ui.common.CommonWebViewActivity; import com.gxtc.huchuan.ui.deal.deal.goodsDetailed.GoodsDetailedActivity; import com.gxtc.huchuan.ui.live.search.NewSearchActivity; import com.gxtc.huchuan.ui.mine.deal.issueDeal.IssueDealActivity; import com.gxtc.huchuan.ui.mine.deal.issueList.IssueListActivity; import com.gxtc.huchuan.ui.mine.deal.orderList.PurchaseListActivity; import com.gxtc.huchuan.utils.TextLineUtile; import com.gxtc.huchuan.widget.DealFragmentHeadView; import org.greenrobot.eventbus.Subscribe; import java.util.List; import butterknife.BindView; import static android.app.Activity.RESULT_OK; /** * 交易 * Created by Steven on 17/2/13. */ public class DealFragment extends BaseTitleFragment implements DealContract.View, View.OnClickListener { @BindView(R.id.swipe_deal) SwipeRefreshLayout swipeLayout; @BindView(R.id.re_deal) RecyclerView mRecyclerView; private DealData data; public static final String STRING_INSTANT_STATUS = "4"; private Deal1LevelAdapter listAdapter; private DealContract.Presenter mPresenter; private DealFragmentHeadView mDealFragmentHeadView; private int correntPosition = -1; private Bundle bundle; private View header; @Override public View initView(LayoutInflater inflater, ViewGroup container) { View view = inflater.inflate(R.layout.fragment_deal, container, false); Drawable d = getResources().getDrawable(R.drawable.deal_home_icon_fatie); d.setBounds(0, 0, d.getMinimumWidth(), d.getMinimumHeight()); int showbar = getArguments().getInt("showBar", 0); if(showbar == 0) { getBaseHeadView().showTitle("交易"); getBaseHeadView().showHeadRightButton("发帖", this); getBaseHeadView().getHeadRightButton().setCompoundDrawables(d, null, null, null); header = getLayoutInflater().inflate(R.layout.search_head_view, getBaseHeadView().getParentView(), false); RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) header.getLayoutParams(); params.addRule(RelativeLayout.RIGHT_OF, R.id.headBackButton); params.addRule(RelativeLayout.LEFT_OF, R.id.headRightLinearLayout); getBaseHeadView().getParentView().addView(header); header.findViewById(R.id.search_layout).setBackground(getResources().getDrawable(R.drawable.shape_search_btn)); header.findViewById(R.id.et_input_search).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { NewSearchActivity.jumpToSearch(getActivity(), NewSearchActivity.TYPE_DEAL); } }); } return view; } @Override public void initListener() { swipeLayout.setColorSchemeResources(Constant.REFRESH_COLOR); swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mPresenter.getHomeData(); } }); if(header != null) { // if (bundle != null) { // getBaseHeadView().showCancelBackButton("帮助", new View.OnClickListener() { // @Override // public void onClick(View v) { // CommonWebViewActivity.startActivity(getActivity(), Constant.ABOUTLINK + "2", "帮助"); // } // }); // } else { getBaseHeadView().showBackButton(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().finish(); } }); // } header.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) header.getLayoutParams(); params.topMargin = (int) ((getResources().getDimension(R.dimen.actionBar_height) - header.getHeight()) / 2); header.setLayoutParams(params); header.getViewTreeObserver().removeOnGlobalLayoutListener(this); } }); } } @Override public void onClick(View v) { switch (v.getId()){ case R.id.headRightButton: if(!UserManager.getInstance().isLogin(getActivity())){ return; } GotoUtil.goToActivity(this, IssueDealActivity.class); break; } } @Override public void initData() { EventBusUtil.register(this); new DealPresenter(this); initHeadView(); mPresenter.getHomeData(); } private void initHeadView() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false); mRecyclerView.setLayoutManager(linearLayoutManager); mDealFragmentHeadView = new DealFragmentHeadView(getActivity(), mRecyclerView); mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayout.VERTICAL, false)); mRecyclerView.setLoadMoreView(R.layout.model_footview_loadmore); mRecyclerView.addHeadView(mDealFragmentHeadView); mRecyclerView.setOnLoadMoreListener(new LoadMoreWrapper.OnLoadMoreListener() { @Override public void onLoadMoreRequested() { mPresenter.loadmore(listAdapter.getItemCount()); } }); mDealFragmentHeadView.setDealHeadListener(new DealFragmentHeadView.DealHeadListener() { //发布帖子 @Override public void onFBTZ() { gotoIssue(); } //我的帖子 @Override public void onWDTZ() { gotoIssueList(); } //交易管理 @Override public void onJYGL() { gotoOrderList(); } //交易会话 @Override public void onYJHH() { gotoMsgList(); } @Override public void onCheckAll() { mPresenter.changeShowType(""); } @Override public void onCheckBuy() { mPresenter.changeShowType("1"); } @Override public void onCheckSell() { mPresenter.changeShowType("0"); } }); } private void gotoMsgList() { if(UserManager.getInstance().isLogin(getActivity())){ GotoUtil.goToActivity(getActivity(),ConversationListActivity.class); } } private void gotoOrderList() { if(UserManager.getInstance().isLogin(getActivity())){ GotoUtil.goToActivity(getActivity(), PurchaseListActivity.class); } } private void gotoIssueList(){ if(UserManager.getInstance().isLogin(getActivity())){ GotoUtil.goToActivity(getActivity(), IssueListActivity.class); } } private void gotoIssue(){ if(UserManager.getInstance().isLogin(getActivity())){ GotoUtil.goToActivity(getActivity(), IssueDealActivity.class); } } @Override public void showData(DealData data) { if (data == null) { showEmpty(); return; } this.data = data; getBaseEmptyView().hideEmptyView(); mDealFragmentHeadView.setHeadDealTab(data); if (listAdapter == null) { listAdapter = new Deal1LevelAdapter(getContext(), data.getInfos(), R.layout.deal_list_home_page); listAdapter.setOnReItemOnClickListener( new BaseRecyclerAdapter.OnReItemOnClickListener() { @Override public void onItemClick(View v, int position) { if(listAdapter.getList().get(position).getIsRecommendEntry() == null || "0".equals(listAdapter.getList().get(position).getIsRecommendEntry())){ correntPosition = position; Intent intent = new Intent(getActivity(), GoodsDetailedActivity.class); intent.putExtra(Constant.INTENT_DATA, listAdapter.getList().get(position).getId()); startActivityForResult(intent,101); }else { Intent intent = new Intent(getActivity(), DealRecomendActivity.class); startActivityForResult(intent,101); } } }); mRecyclerView.setAdapter(listAdapter); } else { mRecyclerView.notifyChangeData(data.getInfos(),listAdapter); } } @Override public void showAdvertise(List<NewsAdsBean> data) { if (mDealFragmentHeadView != null) { mDealFragmentHeadView.setCbDealBanner(data); } } @Override public void showloadmore(DealData data) { if (mRecyclerView != null && listAdapter != null) { mRecyclerView.changeData(data.getInfos(), listAdapter); } } @Override public void showReloadmre(DealData data) { showData(data); } @Override public void showLoadMoreFinish() { mRecyclerView.loadFinish(); } @Override public void showLoad() { if(listAdapter == null){ getBaseLoadingView().showLoading(); } } @Override public void showLoadFinish() { swipeLayout.setRefreshing(false); getBaseLoadingView().hideLoading(); } @Override public void showEmpty() { getBaseEmptyView().showEmptyContent(getString(R.string.empty_no_data)); } @Override public void showReLoad() { mRecyclerView.reLoadFinish(); } @Override public void showError(String info) { ToastUtil.showShort(getContext(),info); } @Override public void showNetError() { getBaseEmptyView().showNetWorkView(new View.OnClickListener() { @Override public void onClick(View v) { getBaseEmptyView().hideEmptyView(); mPresenter.getHomeData(); } }); } @Override public void setPresenter(DealContract.Presenter presenter) { mPresenter = presenter; } @Subscribe public void onEvent(EventScorllTopBean bean){ if(bean.position == 3 && listAdapter != null && mRecyclerView != null){ mRecyclerView.scrollToPosition(0); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode != RESULT_OK) return; if(requestCode == 101){ if(data != null){ int commentCount = data.getIntExtra("commentCount",-1); int readCount = data.getIntExtra("readCount",-1); if(correntPosition != -1){ if(commentCount != -1){ listAdapter.getList().get(correntPosition).setLiuYan(commentCount+""); } if(readCount != -1){ listAdapter.getList().get(correntPosition).setRead(readCount+""); } mRecyclerView.notifyItemChanged(correntPosition); } } } } @Override public void onDestroy() { EventBusUtil.unregister(this); TextLineUtile.clearTextLineCache(); mPresenter.destroy(); super.onDestroy(); } @Override protected void onGetBundle(Bundle bundle) { super.onGetBundle(bundle); this.bundle = bundle; } }
package com.corejava.operators; public class ArithmeticOperator { public static void main(String[] args) { int x, y = 10, z = 5; x = y + z; //10+5=15 System.out.println("+ operator resulted in " + x);//15 x = y - z; //10-5=5 System.out.println("- operator resulted in " + x);//5 x = y * z; //10*5=50 System.out.println("* operator resulted in " + x);//50 x = y / z;//10/5=2 System.out.println("/ operator resulted in " + x);//2 x = y % z; //10%5=0 System.out.println("% operator resulted in " + x); //0 x = y++; // System.out.println("Postfix ++ operator resulted in " + x); //10 x = ++z; System.out.println("Prefix ++ operator resulted in " + x); //6 System.out.println("y:"+y); //y:11 x = -y; System.out.println("Unary operator resulted in " + x); // Some examples of special Cases int tooBig = Integer.MAX_VALUE + 1; // -2147483648 which is // Integer.MIN_VALUE. int tooSmall = Integer.MIN_VALUE - 1; // 2147483647 which is // Integer.MAX_VALUE. System.out.println("tooBig becomes " + tooBig); System.out.println("tooSmall becomes " + tooSmall);System.out.println(4.0 / 0.0); // Prints: Infinity System.out.println(-4.0 / 0.0); // Prints: -Infinity System.out.println(0.0 / 0.0); // Prints: NaN double d1 = 12 / 8; // result: 1 by integer division. d1 gets the value // 1.0. double d2 = 12.0F / 8; // result: 1.5 System.out.println("d1 is " + d1); System.out.println("d2 iss " + d2); } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.context; import org.springframework.context.ApplicationContext; /** * Strategy for components that process failures related to application contexts * within the <em>Spring TestContext Framework</em>. * * <p>Implementations must be registered via the * {@link org.springframework.core.io.support.SpringFactoriesLoader SpringFactoriesLoader} * mechanism. * * @author Sam Brannen * @since 6.0 * @see ContextLoadException */ public interface ApplicationContextFailureProcessor { /** * Invoked when a failure was encountered while attempting to load an * {@link ApplicationContext}. * <p>Implementations of this method must not throw any exceptions. Consequently, * any exception thrown by an implementation of this method will be ignored, though * potentially logged. * @param context the application context that did not load successfully * @param exception the exception thrown while loading the application context */ void processLoadFailure(ApplicationContext context, Throwable exception); }
package com.example.yui.games; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.os.Environment; import android.util.Log; public class Database extends SQLiteOpenHelper{ // The Android's default system path of your application database. //data/data/ and /databases remain the same always. The one that must be changed is com.example which represents //the MAIN package of your project private static String DB_PATH = "/data/data/com.example.yui.games/databases/"; // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "mydatabase"; // Table Name private static final String TABLE_NAME = "Result"; private static Database sInstance = null; private static SQLiteDatabase mDataBase; // Config File private static final String CONFIG_FILE = "Config.txt"; public Database() { super(ApplicationContextProvider.getContext(), DATABASE_NAME, null, DATABASE_VERSION); try { createDataBase(); openDataBase(); } catch (IOException e) { e.printStackTrace(); } } /** * Singleton for DataBase * @return singleton instance */ public static Database instance() { if (sInstance == null) { sInstance = new Database(); } return sInstance; } /** * Creates a empty database on the system and rewrites it with your own database. * @throws java.io.IOException io exception */ private void createDataBase() throws IOException { boolean dbExist = checkDataBase(); if (dbExist) { // do nothing - database already exist Log.d("DATABASE","Database Exit Already."); } else { // Create Folder String newFolder = "/games"; String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); File myNewFolder = new File(extStorageDirectory + newFolder); myNewFolder.mkdir(); // Create Folder // newFolder = "/FishRisk/Game"; // extStorageDirectory = Environment.getExternalStorageDirectory().toString(); // myNewFolder = new File(extStorageDirectory + newFolder); // myNewFolder.mkdir(); // Create Folder newFolder = "/games/Report"; extStorageDirectory = Environment.getExternalStorageDirectory().toString(); myNewFolder = new File(extStorageDirectory + newFolder); myNewFolder.mkdir(); // Create Folder newFolder = "/games/Config"; extStorageDirectory = Environment.getExternalStorageDirectory().toString(); myNewFolder = new File(extStorageDirectory + newFolder); myNewFolder.mkdir(); //copyConfigFile(); // By calling this method an empty database will be created into // the default system path // of your application so we are gonna be able to overwrite that // database with our database. this.getReadableDatabase(); try { copyDataBase(); copyConfigFile(); } catch (IOException e) { throw new Error("Error copying database"); } } } /** * Check if the database already exist to avoid re-copying the file each * time you open the application. * @return true if it exists, false if it doesn't */ private boolean checkDataBase() { SQLiteDatabase checkDB = null; try { String myPath = DB_PATH + DATABASE_NAME; checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY); } catch (SQLiteException e) { // database doesn't exist yet. Log.d("DATABASE","Database doesn't exist yet."); } if (checkDB != null) { checkDB.close(); } return checkDB != null; } /** * Copies your database from your local assets-folder to the just created * empty database in the system folder, from where it can be accessed and * handled. This is done by transfering bytestream. * @throws java.io.IOException io exception */ public void copyDataBase() throws IOException { // Open your local db as the input stream InputStream myInput = ApplicationContextProvider.getContext().getAssets().open(DATABASE_NAME); // Path to the just created empty db String outFileName = DB_PATH + DATABASE_NAME; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } public void copyConfigFile() throws IOException { // Open your local db as the input stream InputStream myInput = ApplicationContextProvider.getContext().getAssets().open(CONFIG_FILE); // Path to the just created empty db //String outFileName = DB_PATH + DATABASE_NAME; String outFileName = "/sdcard/games/Config/ConfigA.txt"; // Open the empty db as the output stream OutputStream myOutput = new FileOutputStream(outFileName); // transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[1024]; int length; while ((length = myInput.read(buffer)) > 0) { myOutput.write(buffer, 0, length); } // Close the streams myOutput.flush(); myOutput.close(); myInput.close(); } private void openDataBase() throws SQLException { // Open the database String myPath = DB_PATH + DATABASE_NAME; mDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); } /** * Select method * @param query select query * @return - Cursor with the results * @throws android.database.SQLException sql exception */ public Cursor select(String query) throws SQLException { return mDataBase.rawQuery(query, null); } /** * Insert method * @param table - name of the table * @param values values to insert * @throws android.database.SQLException sql exception */ public void insert(String table, ContentValues values) throws SQLException { mDataBase.insert(table, null, values); } /** * Delete method * @param table - table name * @param where WHERE clause, if pass null, all the rows will be deleted * @throws android.database.SQLException sql exception */ public void delete(String table, String where) throws SQLException { mDataBase.delete(table, where, null); } /** * Update method * @param table - table name * @param values - values to update * @param where - WHERE clause, if pass null, all rows will be updated */ public void update(String table, ContentValues values, String where) { mDataBase.update(table, values, where, null); } /** * Let you make a raw query * @param command - the sql comand you want to run */ public void sqlCommand(String command) { mDataBase.execSQL(command); } @Override public synchronized void close() { if (mDataBase != null) mDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { // db.execSQL("CREATE TABLE members " + // "(MemberID INTEGER PRIMARY KEY," + // " Name TEXT(100)," + // " Tel TEXT(100));"); //Log.d("CREATE TABLE","Create Table Successfully."); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public List<sMembers> SelectId(String Id) { try { List<sMembers> MemberList = new ArrayList<sMembers>(); SQLiteDatabase db; db = this.getReadableDatabase(); // Read Data String strSQL = "SELECT * FROM " + TABLE_NAME + " WHERE PlayerID = '"+Id+"'"; Cursor cursor = db.rawQuery(strSQL, null); if(cursor != null){ if (cursor.moveToFirst()) { do { sMembers cMember = new sMembers(); cMember.sPlayerID(cursor.getString(0)); cMember.sSession(cursor.getString(1)); cMember.sDate(cursor.getString(2)); cMember.sTime(cursor.getString(3)); cMember.sGame(cursor.getString(4)); cMember.sCrop(cursor.getString(5)); cMember.sDensity(cursor.getString(6)); cMember.sFlood(cursor.getString(7)); cMember.sPaid(cursor.getString(8)); cMember.sQuestion(cursor.getString(9)); cMember.sGameID(cursor.getString(10)); MemberList.add(cMember); } while (cursor.moveToNext()); } } cursor.close();db.close(); return MemberList; } catch (Exception e) { return null;} } // Select Data public String[] SelectData(String strID) { try { String arrData[] = null; SQLiteDatabase db; db = this.getReadableDatabase(); // Read Data Cursor cursor = db.query(TABLE_NAME, new String[] { "*" }, "PlayerID=?", new String[] { String.valueOf(strID) }, null, null, null, null); if(cursor != null){ if (cursor.moveToFirst()) { arrData = new String[cursor.getColumnCount()]; arrData[0] = cursor.getString(0); arrData[1] = cursor.getString(1); arrData[2] = cursor.getString(2); arrData[3] = cursor.getString(3); arrData[4] = cursor.getString(4); arrData[5] = cursor.getString(5); } } cursor.close(); db.close(); return arrData; } catch (Exception e) { return null; } } //SelectData // Select All Data public class sMembers { String _PlayerID,_Session,_Date,_Time,_Game,_Crop, _Density, _Flood, _Paid,_Question,_GameID; // Set Value public void sPlayerID(String vPlayerID){ this._PlayerID = vPlayerID; } public void sSession(String vSession){ this._Session = vSession; } public void sDate(String vDate){ this._Date = vDate; } public void sTime(String vTime){ this._Time = vTime; } public void sGame(String vGame){ this._Game = vGame; } public void sCrop(String vCrop){ this._Crop = vCrop; } public void sDensity(String vDensity){ this._Density = vDensity; } public void sFlood(String vFlood){ this._Flood = vFlood; } public void sPaid(String vPaid){ this._Paid = vPaid; } public void sQuestion(String vQuestion){ this._Question = vQuestion; } public void sGameID(String vGameID){ this._GameID = vGameID; } // Get Value public String gPlayerID(){return _PlayerID;} public String gSession(){return _Session;} public String gDate(){return _Date;} public String gTime(){return _Time;} public String gGame(){return _Game;} public String gCrop(){return _Crop;} public String gDensity(){return _Density;} public String gFlood(){return _Flood;} public String gPaid(){return _Paid;} public String gQestion(){return _Question;} public String gGameID(){return _GameID;} } public List<sMembers> SelectAllData() { try { List<sMembers> MemberList = new ArrayList<sMembers>(); SQLiteDatabase db; db = this.getReadableDatabase(); // Read Data String strSQL = "SELECT * FROM " + "Result ORDER BY _Id DESC"; Cursor cursor = db.rawQuery(strSQL, null); if(cursor != null){ if (cursor.moveToFirst()) { do { sMembers cMember = new sMembers(); cMember.sPlayerID(cursor.getString(0)); cMember.sSession(cursor.getString(1)); cMember.sDate(cursor.getString(2)); cMember.sTime(cursor.getString(3)); cMember.sGame(cursor.getString(4)); cMember.sCrop(cursor.getString(5)); cMember.sDensity(cursor.getString(6)); cMember.sFlood(cursor.getString(7)); cMember.sPaid(cursor.getString(8)); cMember.sQuestion(cursor.getString(9)); cMember.sGameID(cursor.getString(10)); MemberList.add(cMember); } while (cursor.moveToNext()); } } cursor.close(); db.close(); return MemberList; } catch (Exception e) { return null;} } // Insert Data public long InsertData(String strID, String strSession,String strDate, String strTime, String strGame, String strCrop,String strDensity,String strFlood, String strPaid,String strQuestion,String strGameID) { try { SQLiteDatabase db; db = this.getWritableDatabase(); // Write Data ContentValues Val = new ContentValues(); Val.put("PlayerID", strID); Val.put("Session", strSession); Val.put("Date", strDate); Val.put("Time", strTime); Val.put("GameTotal", strGame); Val.put("CropTotal", strCrop); Val.put("Density", strDensity); Val.put("Flood", strFlood); Val.put("PayOff", strPaid); Val.put("Question", strQuestion); Val.put("GameID", strGameID); long rows = db.insert(TABLE_NAME, null, Val); db.close(); return rows; // return rows inserted. } catch (Exception e) {return -1;} } }
package jdk8; @FunctionalInterface public interface A { //只有一个抽象方法。 int a1(String input); //Ojbect类的方法不算。。。。 @Override String toString(); default void foo(){ System.out.println("Calling A.foo()"); } public static void test(){ } }
package uz.zako.example.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import uz.zako.example.model.JwtAuthEntryPoint; import uz.zako.example.model.JwtTokenFilter; import uz.zako.example.service.AuthService; @EnableGlobalMethodSecurity( securedEnabled = true, prePostEnabled = true) @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired AuthService userService; @Autowired private JwtAuthEntryPoint unauthorizedHandler; @Bean public JwtTokenFilter authenticationJwtTokenFilter() { return new JwtTokenFilter(); } @Override public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception { authenticationManagerBuilder .userDetailsService(userService) .passwordEncoder(passwordEncoder()); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and().csrf().disable(). authorizeRequests() // .antMatchers("/**").permitAll() .antMatchers("/api/auth/**").permitAll() .antMatchers("/api/client/**").permitAll() .antMatchers("/v2/api-docs", "/swagger-resources/configuration/ui", "/swagger-resources", "/swagger-resources/configuration/security", "/swagger-ui.html", "/webjars/**").permitAll() .antMatchers("/api/admin/**").access("hasRole('ADMIN')") .anyRequest().authenticated() .and() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class); } }
package com.ifeng.recom.mixrecall.core.cache.feedback; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheStats; import com.google.common.cache.LoadingCache; import com.ifeng.recom.mixrecall.common.dao.redis.jedisPool.ItemcfJedisUtil; import com.ifeng.recom.mixrecall.common.model.item.CdmlVideoItem; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; /** * Created by liligeng on 2019/5/22. */ public class CdmlVideoCache { private final static Logger logger = LoggerFactory.getLogger(CdmlVideoCache.class); //cdml文章缓存 private static Cache<String, List<CdmlVideoItem>> cdmlVideoCache; //cdml文章查询为空缓存,十分钟之内不再查 private static Cache<String, Boolean> cdmlVideoAbsentCache; private static CdmlVideoItem.CdmlVideoItemComparator cdmlComparator = new CdmlVideoItem.CdmlVideoItemComparator(); private static final int dbNum = 6; static { initCdmlCache(); } private static void initCdmlCache() { cdmlVideoCache = CacheBuilder .newBuilder() .concurrencyLevel(15) .recordStats() .expireAfterWrite(180, TimeUnit.MINUTES) .initialCapacity(1000000) .maximumSize(1000000).build(); cdmlVideoAbsentCache = CacheBuilder .newBuilder() .concurrencyLevel(15) .recordStats() .expireAfterWrite(10, TimeUnit.MINUTES) .initialCapacity(200000) .maximumSize(200000).build(); } public static List<CdmlVideoItem> getFromCache(String guid) { List<CdmlVideoItem> cdmlVideoItemList = cdmlVideoCache.getIfPresent(guid); return cdmlVideoItemList; } /** * @param guid * @param result * @return */ public static Boolean checkCacheNeedUpdate(String guid, List<CdmlVideoItem> result) { List<CdmlVideoItem> cacheItem = cdmlVideoCache.getIfPresent(guid); if (cacheItem != null && !cacheItem.isEmpty()) { result.addAll(cacheItem); return false; } Boolean exist = cdmlVideoAbsentCache.getIfPresent(guid); if (exist != null) { return false; } return true; } public static Map<String, List<CdmlVideoItem>> batchQueryCdmlItem(List<String> id2Query, Map<String, String> guidSimIdMapping){ Map<String, List<CdmlVideoItem>> result = new HashMap<>(); for(String guid : id2Query){ List<CdmlVideoItem> idQueryResult = new ArrayList<>(); Boolean needUpdate = checkCacheNeedUpdate(guid, idQueryResult); if(needUpdate){ idQueryResult = queryAndUpdateCache(guid); } String simId = guidSimIdMapping.get(guid); result.put(simId, idQueryResult); } return result; } /** * @param guid * @return */ public static List<CdmlVideoItem> queryAndUpdateCache(String guid) { String cdmlStr = ItemcfJedisUtil.get(dbNum, guid); if (StringUtils.isBlank(cdmlStr)) { return new ArrayList<>(); } List<CdmlVideoItem> result = new ArrayList<>(); String[] cdmlArr = cdmlStr.split(","); for (String cdmlPair : cdmlArr) { String[] pairArr = cdmlPair.split("#"); if (pairArr != null && pairArr.length > 2) { String simId = pairArr[0]; String reGuid = pairArr[1]; Double score = Double.valueOf(pairArr[2]); CdmlVideoItem item = new CdmlVideoItem(simId, reGuid, score); result.add(item); } } return result; } public static void checkStatus() { status(cdmlVideoCache, "video"); } public static void checkStatusAb() { status(cdmlVideoAbsentCache,"absent"); } private static void status(Cache cache,String str) { CacheStats stats = cache.stats(); logger.debug("hit_count:{} hit_rate:{} load_count:{} cache_size:{}, {}", stats.hitCount(), stats.hitRate(), stats.loadCount(), cache.size(), str); } }
package com.wirelesscar.dynafleet.api.types; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Api_DTMStoreDTMAlarmSettingTO complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Api_DTMStoreDTMAlarmSettingTO"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="alarmOn" type="{http://wirelesscar.com/dynafleet/api/types}Api_Boolean"/> * &lt;element name="sessionId" type="{http://wirelesscar.com/dynafleet/api/types}Api_SessionId"/> * &lt;element name="vehicleId" type="{http://wirelesscar.com/dynafleet/api/types}Api_VehicleId"/> * &lt;element name="warningOn" type="{http://wirelesscar.com/dynafleet/api/types}Api_Boolean"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Api_DTMStoreDTMAlarmSettingTO", propOrder = { "alarmOn", "sessionId", "vehicleId", "warningOn" }) public class ApiDTMStoreDTMAlarmSettingTO { @XmlElement(required = true) protected ApiBoolean alarmOn; @XmlElement(required = true) protected ApiSessionId sessionId; @XmlElement(required = true) protected ApiVehicleId vehicleId; @XmlElement(required = true) protected ApiBoolean warningOn; /** * Gets the value of the alarmOn property. * * @return * possible object is * {@link ApiBoolean } * */ public ApiBoolean getAlarmOn() { return alarmOn; } /** * Sets the value of the alarmOn property. * * @param value * allowed object is * {@link ApiBoolean } * */ public void setAlarmOn(ApiBoolean value) { this.alarmOn = value; } /** * Gets the value of the sessionId property. * * @return * possible object is * {@link ApiSessionId } * */ public ApiSessionId getSessionId() { return sessionId; } /** * Sets the value of the sessionId property. * * @param value * allowed object is * {@link ApiSessionId } * */ public void setSessionId(ApiSessionId value) { this.sessionId = value; } /** * Gets the value of the vehicleId property. * * @return * possible object is * {@link ApiVehicleId } * */ public ApiVehicleId getVehicleId() { return vehicleId; } /** * Sets the value of the vehicleId property. * * @param value * allowed object is * {@link ApiVehicleId } * */ public void setVehicleId(ApiVehicleId value) { this.vehicleId = value; } /** * Gets the value of the warningOn property. * * @return * possible object is * {@link ApiBoolean } * */ public ApiBoolean getWarningOn() { return warningOn; } /** * Sets the value of the warningOn property. * * @param value * allowed object is * {@link ApiBoolean } * */ public void setWarningOn(ApiBoolean value) { this.warningOn = value; } }