blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 332 | content_id stringlengths 40 40 | detected_licenses listlengths 0 50 | license_type stringclasses 2
values | repo_name stringlengths 7 115 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 557
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 77.7k | fork_events_count int64 0 48k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 82
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 7 5.41M | extension stringclasses 11
values | content stringlengths 7 5.41M | authors listlengths 1 1 | author stringlengths 0 161 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f2997df60fdadf8e1dffd704eb8a3ba4c0dc535c | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/20/20_b9922d9386944e5e4bf291b2d90724ea8e94d9d0/CurvedConnectionEditPart/20_b9922d9386944e5e4bf291b2d90724ea8e94d9d0_CurvedConnectionEditPart_t.java | 28fdf22c913a22cbdabb8c301aea411f0e522f95 | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 6,473 | java | /*******************************************************************************
* <copyright>
*
* Copyright (c) 2011, 2011 SAP AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* mwenz Bug 352119 - initial API, implementation and documentation contributed by Benjamin Schmeling
*
* </copyright>
*
*******************************************************************************/
package org.eclipse.graphiti.ui.internal.parts;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.draw2d.AbstractRouter;
import org.eclipse.draw2d.Connection;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.PointList;
import org.eclipse.graphiti.mm.algorithms.styles.PrecisionPoint;
import org.eclipse.graphiti.mm.pictograms.CurvedConnection;
import org.eclipse.graphiti.ui.internal.config.IConfigurationProvider;
public class CurvedConnectionEditPart extends ConnectionEditPart {
public CurvedConnectionEditPart(IConfigurationProvider configurationProvider, CurvedConnection connection) {
super(configurationProvider, connection);
}
private CurvedConnection getCurvedConnection() {
return (CurvedConnection) super.getConnection();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.gef.editparts.AbstractGraphicalEditPart#createFigure()
*/
@Override
protected IFigure createFigure() {
IFigure ret = super.createFigure();
if (ret instanceof org.eclipse.draw2d.Connection) {
org.eclipse.draw2d.Connection draw2dConnection = (org.eclipse.draw2d.Connection) ret;
List<PrecisionPoint> controllPoints = new ArrayList<PrecisionPoint>();
controllPoints.addAll(getCurvedConnection().getControlPoints());
draw2dConnection.setConnectionRouter(new BezierRouter(controllPoints));
}
return ret;
}
@Override
protected void refreshVisuals() {
super.refreshVisuals();
refreshControlPoints();
}
private void refreshControlPoints() {
IFigure figure = getFigure();
if (figure instanceof org.eclipse.draw2d.Connection) {
org.eclipse.draw2d.Connection draw2dConnection = (org.eclipse.draw2d.Connection) figure;
draw2dConnection.getConnectionRouter().invalidate(draw2dConnection);
}
}
private class BezierRouter extends AbstractRouter {
private List<PrecisionPoint> bezierPoints;
private Map<org.eclipse.draw2d.Connection, Object> constraints = new HashMap<org.eclipse.draw2d.Connection, Object>(
11);
public BezierRouter(List<PrecisionPoint> bezierPoints) {
this.bezierPoints = bezierPoints;
}
@Override
public void invalidate(Connection connection) {
super.invalidate(connection);
bezierPoints.clear();
bezierPoints.addAll(getCurvedConnection().getControlPoints());
}
public void route(org.eclipse.draw2d.Connection connection) {
List<org.eclipse.draw2d.geometry.PrecisionPoint> controllPoints = new ArrayList<org.eclipse.draw2d.geometry.PrecisionPoint>();
PointList points = connection.getPoints();
points.removeAllPoints();
Point ref1 = connection.getTargetAnchor().getReferencePoint();
Point ref2 = connection.getSourceAnchor().getReferencePoint();
org.eclipse.draw2d.geometry.PrecisionPoint start = new org.eclipse.draw2d.geometry.PrecisionPoint();
org.eclipse.draw2d.geometry.PrecisionPoint end = new org.eclipse.draw2d.geometry.PrecisionPoint();
start.setLocation(connection.getSourceAnchor().getLocation(ref1));
connection.translateToRelative(start);
end.setLocation(connection.getTargetAnchor().getLocation(ref2));
connection.translateToRelative(end);
controllPoints.add(start);
double gradient = (end.preciseY() - start.preciseY()) / (-end.preciseX() + start.preciseX());
double ortho_gradient = -Math.pow(gradient, -1);
double orthovector_x = 1;
double orthovector_y = ortho_gradient;
double factor_to_length = 1 / Math.sqrt((Math.pow(orthovector_y, 2) + Math.pow(orthovector_x, 2)));
for (PrecisionPoint precisionPoint : this.bezierPoints) {
double orthovector_x_cp = factor_to_length * orthovector_x * precisionPoint.getY();
double orthovector_y_cp = factor_to_length * orthovector_y * precisionPoint.getY();
if (Double.isNaN(orthovector_x_cp)) {
orthovector_x_cp = 0;
}
if (Double.isNaN(orthovector_y_cp)) {
orthovector_y_cp = 1 * precisionPoint.getY();
}
org.eclipse.draw2d.geometry.PrecisionPoint anchor = new org.eclipse.draw2d.geometry.PrecisionPoint(
(start.x + (end.x - start.x) * precisionPoint.getX() - orthovector_x_cp),
(start.y - (start.y - end.y) * precisionPoint.getX()) + orthovector_y_cp);
controllPoints.add(anchor);
}
controllPoints.add(end);
int precision = 10;
double factor = 1.0d / precision;
points.addPoint(start);
for (int i = 1; i < precision; i++) {
int j = 0;
double sum_x = 0;
double sum_y = 0;
for (Point point : controllPoints) {
sum_x += (bezier(j, controllPoints.size() - 1, i * factor) * point.preciseX());
sum_y += (bezier(j, controllPoints.size() - 1, i * factor) * point.preciseY());
j++;
}
org.eclipse.draw2d.geometry.PrecisionPoint bezierPoint = new org.eclipse.draw2d.geometry.PrecisionPoint(
sum_x, sum_y);
points.addPoint(bezierPoint);
}
points.addPoint(end);
connection.setPoints(points);
}
private double bezier(int i, int n, double t) {
return binomialCoefficients(n, i) * Math.pow(t, i) * Math.pow((1 - t), (n - i));
}
private long binomialCoefficients(int n, int k) {
long coeff = 1;
for (int i = n - k + 1; i <= n; i++) {
coeff *= i;
}
for (int i = 1; i <= k; i++) {
coeff /= i;
}
return coeff;
}
@Override
public void setConstraint(org.eclipse.draw2d.Connection connection, Object constraint) {
constraints.put(connection, constraint);
}
@Override
public void remove(org.eclipse.draw2d.Connection connection) {
constraints.remove(connection);
}
@Override
public Object getConstraint(org.eclipse.draw2d.Connection connection) {
return constraints.get(connection);
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
af53966a6bea211d0c544e5c9eb2e7c95ea49e5e | 0d24d2e743dff20dde9fb32481289a623bd1378f | /mps/mps-core/src/main/java/com/me/mps/dto/ProductDTO.java | c9ab78d46f15e513a79cdd344d2f9f678e006bbc | [] | no_license | Me-Yan/mps | 13a52b917f107e3a685d097596904f720cc47504 | 7ee8cfd242c6f048c901fac8349ab5cb70f5d1a3 | refs/heads/master | 2021-05-15T14:29:48.173642 | 2018-03-25T09:42:04 | 2018-03-25T09:42:04 | 107,210,370 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,108 | java | package com.me.mps.dto;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.File;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* Created by Me on 2017/12/9.
*/
public class ProductDTO implements Serializable {
private static final long serialVersionUID = 8585571928359103619L;
private Integer productId;
private Integer categoryId;
private Integer categorySecondId;
private String nameX;
private Integer countN;
private Double priceN;
private String imagePathX;
private String activeC;
private String crtByM;
private Date crtOnDt;
private String updByM;
private Date updOnDt;
private List<ImageDTO> imageDTOList;
// for operation
private MultipartFile imageFile;
private List<MultipartFile> imageList;
private String showFlag;
private String detailFlag;
// for view
private Integer serialNumber;
private String createDate;
public String getShowFlag() {
return showFlag;
}
public void setShowFlag(String showFlag) {
this.showFlag = showFlag;
}
public String getDetailFlag() {
return detailFlag;
}
public void setDetailFlag(String detailFlag) {
this.detailFlag = detailFlag;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public Integer getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(Integer serialNumber) {
this.serialNumber = serialNumber;
}
public List<ImageDTO> getImageDTOList() {
return imageDTOList;
}
public void setImageDTOList(List<ImageDTO> imageDTOList) {
this.imageDTOList = imageDTOList;
}
public List<MultipartFile> getImageList() {
return imageList;
}
public void setImageList(List<MultipartFile> imageList) {
this.imageList = imageList;
}
public MultipartFile getImageFile() {
return imageFile;
}
public void setImageFile(MultipartFile imageFile) {
this.imageFile = imageFile;
}
public Integer getProductId() {
return productId;
}
public void setProductId(Integer productId) {
this.productId = productId;
}
public String getNameX() {
return nameX;
}
public void setNameX(String nameX) {
this.nameX = nameX;
}
public Integer getCountN() {
return countN;
}
public void setCountN(Integer countN) {
this.countN = countN;
}
public Double getPriceN() {
return priceN;
}
public void setPriceN(Double priceN) {
this.priceN = priceN;
}
public String getImagePathX() {
return imagePathX;
}
public void setImagePathX(String imagePathX) {
this.imagePathX = imagePathX;
}
public Integer getCategoryId() {
return categoryId;
}
public void setCategoryId(Integer categoryId) {
this.categoryId = categoryId;
}
public Integer getCategorySecondId() {
return categorySecondId;
}
public void setCategorySecondId(Integer categorySecondId) {
this.categorySecondId = categorySecondId;
}
public String getActiveC() {
return activeC;
}
public void setActiveC(String activeC) {
this.activeC = activeC;
}
public String getCrtByM() {
return crtByM;
}
public void setCrtByM(String crtByM) {
this.crtByM = crtByM;
}
public Date getCrtOnDt() {
return crtOnDt;
}
public void setCrtOnDt(Date crtOnDt) {
this.crtOnDt = crtOnDt;
}
public String getUpdByM() {
return updByM;
}
public void setUpdByM(String updByM) {
this.updByM = updByM;
}
public Date getUpdOnDt() {
return updOnDt;
}
public void setUpdOnDt(Date updOnDt) {
this.updOnDt = updOnDt;
}
}
| [
"yanyanghong_work@163.com"
] | yanyanghong_work@163.com |
76221a568d34b83830295aa3ce6fc62304f7c0ca | fa91450deb625cda070e82d5c31770be5ca1dec6 | /Diff-Raw-Data/2/2_185ae6357640d23ecffed2fdf83afce3eb7a0e11/LoginActivity/2_185ae6357640d23ecffed2fdf83afce3eb7a0e11_LoginActivity_t.java | 7feb713d8bf31b12e2681462b19272250dd2ae0d | [] | no_license | zhongxingyu/Seer | 48e7e5197624d7afa94d23f849f8ea2075bcaec0 | c11a3109fdfca9be337e509ecb2c085b60076213 | refs/heads/master | 2023-07-06T12:48:55.516692 | 2023-06-22T07:55:56 | 2023-06-22T07:55:56 | 259,613,157 | 6 | 2 | null | 2023-06-22T07:55:57 | 2020-04-28T11:07:49 | null | UTF-8 | Java | false | false | 10,349 | java | package android.ubication;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
//import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
/**
*
* @author Flavio Corpa Ros
*
*/
public class LoginActivity extends Activity {
/**
* The default email to populate the email field with.
*/
public static final String EXTRA_EMAIL = "com.example.android.authenticatordemo.extra.EMAIL";
/**
* Keep track of the login task to ensure we can cancel it if requested.
*/
private UserLoginTask mAuthTask = null;
// Values for email and password at the time of the login attempt.
private String mEmail;
private String mPassword;
// UI references.
private EditText mEmailView;
private EditText mPasswordView;
private View mLoginFormView;
private View mLoginStatusView;
private TextView mLoginStatusMessageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Set up the login form.
mEmail = getIntent().getStringExtra(EXTRA_EMAIL);
mEmailView = (EditText) findViewById(R.id.email);
mEmailView.setText(mEmail);
mPasswordView = (EditText) findViewById(R.id.password);
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int id,
KeyEvent keyEvent) {
if (id == R.id.login || id == EditorInfo.IME_NULL) {
attemptLogin();
return true;
}
return false;
}
});
mLoginFormView = findViewById(R.id.login_form);
mLoginStatusView = findViewById(R.id.login_status);
mLoginStatusMessageView = (TextView) findViewById(R.id.login_status_message);
findViewById(R.id.sign_in_button).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
attemptLogin();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
//getMenuInflater().inflate(R.menu.activity_login, menu);
return true;
}
/*@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (item.getItemId() == R.id.menu_forgot_password)
{
//Formulario para recuperar la contrasea
return true;
}
else if (item.getItemId() == R.id.menu_registrarse)
{
//Forulario para REGISTRARSE
Intent i = new Intent(this, Registrarse.class);
startActivity(i);
return true;
}
else
return super.onMenuItemSelected(featureId, item);
}*/
/**
* Attempts to sign in or register the account specified by the login form.
* If there are form errors (invalid email, missing fields, etc.), the
* errors are presented and no actual login attempt is made.
*/
public void attemptLogin()
{
if (mAuthTask != null) {
return;
}
// Reset errors.
mEmailView.setError(null);
mPasswordView.setError(null);
// Store values at the time of the login attempt.
mEmail = mEmailView.getText().toString();
mPassword = mPasswordView.getText().toString();
boolean cancel = false;
View focusView = null;
// Check for a valid password.
if (TextUtils.isEmpty(mPassword)) {
mPasswordView.setError(getString(R.string.error_field_required));
focusView = mPasswordView;
cancel = true;
} else if (mPassword.length() < 4) {
mPasswordView.setError(getString(R.string.error_invalid_password));
focusView = mPasswordView;
cancel = true;
}
// Check for a valid email address.
if (TextUtils.isEmpty(mEmail)) {
mEmailView.setError(getString(R.string.error_field_required));
focusView = mEmailView;
cancel = true;
} else if (!mEmail.contains("@")) {
mEmailView.setError(getString(R.string.error_invalid_email));
focusView = mEmailView;
cancel = true;
}
if (cancel) {
// There was an error; don't attempt login and focus the first
// form field with an error.
focusView.requestFocus();
} else {
// Show a progress spinner, and kick off a background task to
// perform the user login attempt.
mLoginStatusMessageView.setText(R.string.login_progress_signing_in);
showProgress(true);
mAuthTask = new UserLoginTask();
mAuthTask.execute((Void) null);
}
}
/**
* Shows the progress UI and hides the login form.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
private void showProgress(final boolean show) {
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
// for very easy animations. If available, use these APIs to fade-in
// the progress spinner.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
int shortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
mLoginStatusView.setVisibility(View.VISIBLE);
mLoginStatusView.animate().setDuration(shortAnimTime)
.alpha(show ? 1 : 0)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginStatusView.setVisibility(show ? View.VISIBLE
: View.GONE);
}
});
mLoginFormView.setVisibility(View.VISIBLE);
mLoginFormView.animate().setDuration(shortAnimTime)
.alpha(show ? 0 : 1)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mLoginFormView.setVisibility(show ? View.GONE
: View.VISIBLE);
}
});
} else {
// The ViewPropertyAnimator APIs are not available, so simply show
// and hide the relevant UI components.
mLoginStatusView.setVisibility(show ? View.VISIBLE : View.GONE);
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
}
}
/**
* Represents an asynchronous login/registration task used to authenticate
* the user.
*/
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
//URL del Servidor.
String url = "http://www.energysistem.com/ubication/index.php";
//Creamos un nuevo objeto HttpClient que ser el encargado de realizar la
//comunicacin HTTP con el servidor a partir de los datos que le damos.
HttpClient comunicacion = new DefaultHttpClient();
//Creamos una peticion POST indicando la URL de llamada al servicio.
HttpPost peticion = new HttpPost(url);
//Objeto JSON con los datos del Login.
// JSONObject object = new JSONObject();
// try
// {
// object.put("action", "login");
// object.put("id", System.currentTimeMillis()); //Tiempo del Sistema en milisecs.
// object.put("email", mEmail);
// object.put("password", mPassword);
//
// } catch (Exception ex) {
// Log.e("Error", "Error al crear objeto JSON.", ex);
// }
try
{
String idEnviado = String.valueOf(System.currentTimeMillis());
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("action", "login"));
nameValuePairs.add(new BasicNameValuePair("id", idEnviado));
nameValuePairs.add(new BasicNameValuePair("email", mEmail));
nameValuePairs.add(new BasicNameValuePair("password", mPassword));
peticion.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Modificamos mediante setHeader el atributo http content-type para indicar
//que el formato de los datos que utilizaremos en la comunicacin ser JSON.
peticion.setHeader("Accept", "application/json");
//Ejecutamos la peticin y obtenemos la respuesta en forma de cadena
HttpResponse respuesta = comunicacion.execute(peticion);
String respuestaString = EntityUtils.toString(respuesta.getEntity());
//Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
JSONObject respuestaJSON = new JSONObject(respuestaString);
//Si la respuesta del servidor es true
if (respuestaJSON.get("result").equals("true") && respuestaJSON.get("ack").equals(idEnviado))
{ //El Login es correcto
Log.e("LogDebug", "true");
return true;
//Arrancamos el Service
//startService(new Intent(this, UbicationService.class));
}
else
{
Log.e("LogDebug", "false");
return false;
}
} catch(Exception e) {
Log.e("Error", "Error al recibir respuesta del Servidor.", e);
}
return false;
}
@Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
finish();
} else {
mEmailView.setError(getString(R.string.error_incorrect_password));
mPasswordView.setError(getString(R.string.error_incorrect_password));
mPasswordView.requestFocus();
}
}
@Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}
}
| [
"yuzhongxing88@gmail.com"
] | yuzhongxing88@gmail.com |
94920485c0e13359832ee2a8119f7188e980f5d4 | bc2560cb9dcb82f2f752cbed26f5ba7270afe6bb | /app/src/main/java/com/xwj/xwjnote3/utils/CommonUtils.java | b295427fbb0426b03bce0165cbd7d9384c7cca28 | [] | no_license | xwjsdhr/XwjNote3 | 6c3f5d8544d91ebae52a9b4b8710745f87363c23 | 49978acb10f8f5e393bdfc857c87fa1693b55ce6 | refs/heads/master | 2021-01-10T01:22:23.312986 | 2015-12-22T09:39:44 | 2015-12-22T09:39:44 | 48,422,511 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 629 | java | package com.xwj.xwjnote3.utils;
import android.content.Context;
import android.text.format.DateUtils;
import java.util.Date;
import java.util.UUID;
/**
* 常用工具类
* Created by xwjsd on 2015/12/4.
*/
public class CommonUtils {
public static String getGuid() {
return UUID.randomUUID().toString();
}
public static String getDate(Context context, Date date) {
return DateUtils.getRelativeDateTimeString(context, date.getTime()
, DateUtils.MINUTE_IN_MILLIS
, DateUtils.DAY_IN_MILLIS
, DateUtils.FORMAT_ABBREV_ALL
).toString();
}
}
| [
"xwjsdhr.love@163.com"
] | xwjsdhr.love@163.com |
f3aa0dd0b8fc60e71ed611ac813372b4268092bc | 33ea826c6279a3dff493f06f92dcc2696ad83758 | /app/src/main/java/com/kitchee/app/helpeo/utils/ToastUtil.java | 8bf230f2fb6127e21252226d0d223ddc9e0bb57b | [] | no_license | kitcheehong/HelpEO | 2c53527f5f421cf64d0d93c72324b2754c52fe11 | e2318f363b5546fa08e3843dd72e8868d5bb3dcf | refs/heads/master | 2021-06-25T08:51:48.273629 | 2018-08-29T01:48:43 | 2018-08-29T01:48:43 | 136,166,306 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 675 | java | package com.kitchee.app.helpeo.utils;
import android.widget.Toast;
import com.kitchee.app.helpeo.appCommon.HelpEOApplication;
/**
* Created by kitchee on 2018/8/28.
* desc:
*/
public class ToastUtil {
private static Toast mToast = Toast.makeText(HelpEOApplication.helpEOApplication.getApplicationContext(),"",Toast.LENGTH_LONG);
public static void showLongToast(String message){
mToast.setText(message);
mToast.setDuration(Toast.LENGTH_LONG);
mToast.show();
}
public static void showShortToast(String message){
mToast.setText(message);
mToast.setDuration(Toast.LENGTH_SHORT);
mToast.show();
}
}
| [
"2321455051@qq.com"
] | 2321455051@qq.com |
85c7ac5872ae680c7ad225634f8af6e0cf151fe7 | f37e90775a158ea0ae644e334eac5bba341f4989 | /Java+/Libs+/Guice+/Guice/src/guice/binding/install_modules/title/TitleService.java | 6c6303f91d7eee82a98e1070b8211b611dd3dcf7 | [] | no_license | Aleks-Ya/yaal_examples | 0087bbaf314ca5127051c93b89c8fc2dcd14c1e3 | ec282968abf1b86e54fc2116c39f2d657b51baac | refs/heads/master | 2023-09-01T07:40:44.404550 | 2023-08-27T15:24:34 | 2023-08-29T22:01:46 | 14,327,752 | 4 | 2 | null | 2021-06-16T20:39:19 | 2013-11-12T09:26:08 | Java | UTF-8 | Java | false | false | 103 | java | package guice.binding.install_modules.title;
public interface TitleService {
String getTitle();
}
| [
"ya_al@bk.ru"
] | ya_al@bk.ru |
1d66d98b9490a3b8f0f705012329634a02100802 | 2deb74d5bf569bdbe637846d93fac47c01b278a4 | /android/content/SyncAdapterType.java | 6624f3c53ca39b5ff91018c5d035e12a812b823f | [] | no_license | isabella232/android-sdk-sources-for-api-level-11 | 8aefeff38cbc0bbe7cfbbd04a940f8c4aa319772 | d772b816a1e388a5f8022d4bc47adc9016195600 | refs/heads/master | 2023-03-16T14:08:07.661845 | 2015-07-03T11:17:32 | 2015-07-03T11:17:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,815 | java | /* */ package android.content;
/* */
/* */ import android.os.Parcel;
/* */ import android.os.Parcelable;
/* */ import android.os.Parcelable.Creator;
/* */
/* */ public class SyncAdapterType
/* */ implements Parcelable
/* */ {
/* */ public final String authority;
/* */ public final String accountType;
/* */ public final boolean isKey;
/* 21 */ public static final Parcelable.Creator<SyncAdapterType> CREATOR = null;
/* */
/* */ public SyncAdapterType(String authority, String accountType, boolean userVisible, boolean supportsUploading)
/* */ {
/* 5 */ throw new RuntimeException("Stub!"); }
/* 6 */ public SyncAdapterType(Parcel source) { throw new RuntimeException("Stub!"); }
/* 7 */ public boolean supportsUploading() { throw new RuntimeException("Stub!"); }
/* 8 */ public boolean isUserVisible() { throw new RuntimeException("Stub!"); }
/* 9 */ public boolean allowParallelSyncs() { throw new RuntimeException("Stub!"); }
/* 10 */ public boolean isAlwaysSyncable() { throw new RuntimeException("Stub!"); }
/* 11 */ public static SyncAdapterType newKey(String authority, String accountType) { throw new RuntimeException("Stub!"); }
/* 12 */ public boolean equals(Object o) { throw new RuntimeException("Stub!"); }
/* 13 */ public int hashCode() { throw new RuntimeException("Stub!"); }
/* 14 */ public String toString() { throw new RuntimeException("Stub!"); }
/* 15 */ public int describeContents() { throw new RuntimeException("Stub!"); }
/* 16 */ public void writeToParcel(Parcel dest, int flags) { throw new RuntimeException("Stub!");
/* */ }
/* */ }
/* Location: D:\xyh\Android_3.0\android.jar
* Qualified Name: android.content.SyncAdapterType
* JD-Core Version: 0.6.0
*/ | [
"root@ifeegoo.com"
] | root@ifeegoo.com |
c604a7d315d26eea25a7526046c44269740f7d19 | cb0e86216b07a69e5454ff95dfb9c6bfb9e4c279 | /src/main/java/com/kvana/config/MetricsConfiguration.java | 03454ecad163968482c607f63731c1394aaf4464 | [] | no_license | purushotham9/sample-monolithic-app | be32b3de98760ba4b411dd773f8eb407e84b1ded | 0d464026a329f30bdbe07f7f3105fd39aaea01a7 | refs/heads/master | 2020-04-08T14:52:44.937686 | 2018-11-28T05:49:40 | 2018-11-28T05:49:40 | 159,455,451 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,527 | java | package com.kvana.config;
import io.github.jhipster.config.JHipsterProperties;
import com.codahale.metrics.JmxReporter;
import com.codahale.metrics.JvmAttributeGaugeSet;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.codahale.metrics.jcache.JCacheGaugeSet;
import com.codahale.metrics.jvm.*;
import com.ryantenney.metrics.spring.config.annotation.EnableMetrics;
import com.ryantenney.metrics.spring.config.annotation.MetricsConfigurerAdapter;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.MarkerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.*;
import javax.annotation.PostConstruct;
import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableMetrics(proxyTargetClass = true)
public class MetricsConfiguration extends MetricsConfigurerAdapter {
private static final String PROP_METRIC_REG_JVM_MEMORY = "jvm.memory";
private static final String PROP_METRIC_REG_JVM_GARBAGE = "jvm.garbage";
private static final String PROP_METRIC_REG_JVM_THREADS = "jvm.threads";
private static final String PROP_METRIC_REG_JVM_FILES = "jvm.files";
private static final String PROP_METRIC_REG_JVM_BUFFERS = "jvm.buffers";
private static final String PROP_METRIC_REG_JVM_ATTRIBUTE_SET = "jvm.attributes";
private static final String PROP_METRIC_REG_JCACHE_STATISTICS = "jcache.statistics";
private final Logger log = LoggerFactory.getLogger(MetricsConfiguration.class);
private MetricRegistry metricRegistry = new MetricRegistry();
private HealthCheckRegistry healthCheckRegistry = new HealthCheckRegistry();
private final JHipsterProperties jHipsterProperties;
private HikariDataSource hikariDataSource;
public MetricsConfiguration(JHipsterProperties jHipsterProperties) {
this.jHipsterProperties = jHipsterProperties;
}
@Autowired(required = false)
public void setHikariDataSource(HikariDataSource hikariDataSource) {
this.hikariDataSource = hikariDataSource;
}
@Override
@Bean
public MetricRegistry getMetricRegistry() {
return metricRegistry;
}
@Override
@Bean
public HealthCheckRegistry getHealthCheckRegistry() {
return healthCheckRegistry;
}
@PostConstruct
public void init() {
log.debug("Registering JVM gauges");
metricRegistry.register(PROP_METRIC_REG_JVM_MEMORY, new MemoryUsageGaugeSet());
metricRegistry.register(PROP_METRIC_REG_JVM_GARBAGE, new GarbageCollectorMetricSet());
metricRegistry.register(PROP_METRIC_REG_JVM_THREADS, new ThreadStatesGaugeSet());
metricRegistry.register(PROP_METRIC_REG_JVM_FILES, new FileDescriptorRatioGauge());
metricRegistry.register(PROP_METRIC_REG_JVM_BUFFERS, new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
metricRegistry.register(PROP_METRIC_REG_JVM_ATTRIBUTE_SET, new JvmAttributeGaugeSet());
metricRegistry.register(PROP_METRIC_REG_JCACHE_STATISTICS, new JCacheGaugeSet());
if (hikariDataSource != null) {
log.debug("Monitoring the datasource");
// remove the factory created by HikariDataSourceMetricsPostProcessor until JHipster migrate to Micrometer
hikariDataSource.setMetricsTrackerFactory(null);
hikariDataSource.setMetricRegistry(metricRegistry);
}
if (jHipsterProperties.getMetrics().getJmx().isEnabled()) {
log.debug("Initializing Metrics JMX reporting");
JmxReporter jmxReporter = JmxReporter.forRegistry(metricRegistry).build();
jmxReporter.start();
}
if (jHipsterProperties.getMetrics().getLogs().isEnabled()) {
log.info("Initializing Metrics Log reporting");
Marker metricsMarker = MarkerFactory.getMarker("metrics");
final Slf4jReporter reporter = Slf4jReporter.forRegistry(metricRegistry)
.outputTo(LoggerFactory.getLogger("metrics"))
.markWith(metricsMarker)
.convertRatesTo(TimeUnit.SECONDS)
.convertDurationsTo(TimeUnit.MILLISECONDS)
.build();
reporter.start(jHipsterProperties.getMetrics().getLogs().getReportFrequency(), TimeUnit.SECONDS);
}
}
}
| [
"kvanaindia@kvanaIndias-iMac.local"
] | kvanaindia@kvanaIndias-iMac.local |
3a8df8aa24d61552c1895b9dfdd6835b2e0f1fdc | adb45b9c77351fbbcf1458f3c80fdfa9024c35c9 | /src/androidTest/java/br/com/fragmentos2/ExampleInstrumentedTest.java | 4e2d493011686675a6e49bdffa6a06fdef80aedd | [] | no_license | mbegnini/AulaFragmentos | c281ac6788179917dfdd75691568e7e7a0839632 | f1515c8717cfcb61f7a58c38e9659d82283f6286 | refs/heads/master | 2020-05-03T00:11:32.363132 | 2019-03-29T00:28:06 | 2019-03-29T00:28:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 720 | java | package br.com.fragmentos2;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("br.com.fragmentos2", appContext.getPackageName());
}
}
| [
"mauricio1989@gmail.com"
] | mauricio1989@gmail.com |
ffcec8bfed386ee371e0464b340c06caf36792e0 | b8f487de1c3071351739887291db153c3199ec0e | /src/main/java/com/broadcom/apdk/objects/PromptSetDialog.java | 5ba632a418a630bd61d045ecbf79a44e344ff460 | [
"MIT"
] | permissive | wody/action-pack-sdk | eaed5aa95eab9230f6713594eaec5fea6908849f | 5f4984f826f1a92bc95891ea8f5f6285144cc7ef | refs/heads/master | 2022-07-17T06:09:15.764506 | 2020-05-15T13:42:36 | 2020-05-15T13:42:36 | 264,159,859 | 0 | 0 | MIT | 2020-05-15T10:03:51 | 2020-05-15T10:03:50 | null | UTF-8 | Java | false | false | 4,073 | java | package com.broadcom.apdk.objects;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.eclipse.persistence.oxm.annotations.XmlMarshalNullRepresentation;
import org.eclipse.persistence.oxm.annotations.XmlNullPolicy;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement(name = "dialog")
@XmlType (propOrder={"properties", "prompts"})
class PromptSetDialog {
private final String ID = "PRPTS";
private final String ICON = "PRPT";
private String title;
private List<IPrompt<?>> prompts;
private Integer left;
private Integer top;
private Integer height;
private Integer width;
private String id;
private String icon;
private Map<String, PropertyValue> properties;
PromptSetDialog() {
initDialog(null);
}
PromptSetDialog(String title) {
initDialog(title);
}
PromptSetDialog(String title, List<IPrompt<?>> prompts) {
initDialog(title);
setPrompts(prompts);
}
void initDialog(String title) {
setTitle(title);
setId(ID);
setIcon(ICON);
setWidth(657);
setLeft(279);
setHeight(114);
setTop(4);
Map<String, PropertyValue> properties = new HashMap<String, PropertyValue>();
properties.put("text", new PropertyValue(title));
properties.put("modifiable", new PropertyValue("0"));
setProperties(properties);
}
void setTitle(String title) {
this.title = title;
}
@XmlPath("readpanel[@id='PRPTBOX']/@text")
@XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
String getTitle() {
return this.title;
}
void setPrompts(List<IPrompt<?>> prompts) {
this.prompts = prompts;
}
@XmlPath("readpanel[@id='PRPTBOX']")
@XmlAnyElement(lax = true)
@XmlJavaTypeAdapter(PromptAdapter.class)
List<IPrompt<?>> getPrompts() {
return this.prompts;
}
// Non-Public API
@XmlPath("readpanel[@id='PRPTBOX']/@nl")
String getNl() {
return "1";
}
@XmlPath("readpanel[@id='PRPTBOX']/@fill")
String getFill() {
return "b";
}
@XmlPath("readpanel[@id='PRPTBOX']/@scroll")
String getScroll() {
return "v";
}
@XmlAttribute
@XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
Integer getLeft() {
return left;
}
void setLeft(Integer left) {
this.left = left;
}
@XmlAttribute
@XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
Integer getTop() {
return top;
}
void setTop(Integer top) {
this.top = top;
}
@XmlAttribute
@XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
Integer getHeight() {
return height;
}
void setHeight(Integer height) {
this.height = height;
}
@XmlAttribute
@XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
Integer getWidth() {
return width;
}
void setWidth(Integer width) {
this.width = width;
}
@XmlAttribute
@XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
String getId() {
return id;
}
void setId(String id) {
this.id = id;
}
@XmlAttribute
@XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
String getIcon() {
return icon;
}
void setIcon(String icon) {
this.icon = icon;
}
@XmlPath("readpanel[@id='PRPTBOX']/properties/text()")
@XmlJavaTypeAdapter(PropertyAdapter.class)
@XmlNullPolicy(emptyNodeRepresentsNull = true, nullRepresentationForXml = XmlMarshalNullRepresentation.EMPTY_NODE)
Map<String, PropertyValue> getProperties() {
return properties;
}
void setProperties(Map<String, PropertyValue> properties) {
this.properties = properties;
}
}
| [
"mg685065@broadcom.net"
] | mg685065@broadcom.net |
914891757fdfa5a5b7d01605693bb146a55fe03c | 0652d4ba5427e4899b17eab121138c3520ab5954 | /app/src/main/java/com/lyy_wzw/comeacross/rong/server/response/LoginResponse.java | 7e62bbeded23b9e75dc5cc25a14258eed82140e5 | [] | no_license | wangzhanwen/ComeAcross | ae6321ed418fa49eba63e8808bc202b95b5c938e | da2c73409545e9c57eaaaba67e2b9267b1f457a3 | refs/heads/master | 2021-01-20T18:43:32.324811 | 2017-08-08T01:09:30 | 2017-08-08T01:09:30 | 90,927,682 | 4 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,215 | java | package com.lyy_wzw.comeacross.rong.server.response;
/**
* Created by AMing on 15/12/24.
* Company RongCloud
*/
public class LoginResponse {
/**
* code : 200
* result : {"id":"t1hWCOGvX","token":"B0DA/kKanJviD5xxUzhwsEFIJad0/86YwGxBwz1417WFQi/Vr2OJay26s5IFDffGZaUYRMAkvN0ikvOcTl7RN9JilKZlosfQ"}
*/
private int code;
/**
* id : t1hWCOGvX
* token : B0DA/kKanJviD5xxUzhwsEFIJad0/86YwGxBwz1417WFQi/Vr2OJay26s5IFDffGZaUYRMAkvN0ikvOcTl7RN9JilKZlosfQ
*/
private ResultEntity result;
public void setCode(int code) {
this.code = code;
}
public void setResult(ResultEntity result) {
this.result = result;
}
public int getCode() {
return code;
}
public ResultEntity getResult() {
return result;
}
public static class ResultEntity {
private String id;
private String token;
public void setId(String id) {
this.id = id;
}
public void setToken(String token) {
this.token = token;
}
public String getId() {
return id;
}
public String getToken() {
return token;
}
}
}
| [
"274596545@qq.com"
] | 274596545@qq.com |
77418ca79955c27c00684a28f7dce3559b2eef62 | 3d526c5cca24c3c5274c0092a93ca45e7fc9496a | /Source_Code/myinterpreter/BackEnd.java | 6702bb24a3662340a45df6a2248ea468b4f46642 | [
"MIT"
] | permissive | geekrypter/Mutation_Source_Code_Testing | b1fb556148f1c351ee9d0b5368f8377b07309360 | bca147f1257f71febb1f9acb567700f360ebd02c | refs/heads/master | 2020-05-21T21:36:11.098364 | 2019-05-11T16:54:10 | 2019-05-11T16:54:10 | 186,157,122 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,522 | java | package myinterpreter;
import java.lang.*;
import java.util.*;
//This class is used for providing the proper input to the OutputGenerator class
public class BackEnd
{
private OutputGenerator ogObject=new OutputGenerator();
//This method provides the proper input to the OutputGenerator class
public String processor(String givenString)
{
if(givenString.length()!=0)
{
try
{
boolean validation = inputValidation(givenString);
String inputWithoutSpaces=new String();
inputWithoutSpaces=inputWOSpaces(givenString);
return ogObject.splitString(inputWithoutSpaces);
}
catch(ICException E1)
{
return E1.Message();
}
catch(PException E1)
{
return E1.Message();
}
catch(NVException E1)
{
return E1.Message();
}
catch(DZException E1)
{
return E1.Message();
}
catch(CNTASGNException E1)
{
return E1.Message();
}
catch(IVSTException E1)
{
return E1.Message();
}
}
return givenString;
}
//This method checks whether the given user input is valid or not
public boolean inputValidation(String givenString) throws ICException,PException
{
Stack<Character> paranthesisHolder=new Stack<Character>();
for(int i=0;i<givenString.length();i++)
{
if(givenString.charAt(i)=='*'||givenString.charAt(i)=='%'||givenString.charAt(i)==' '||givenString.charAt(i)=='-'||givenString.charAt(i)=='('||givenString.charAt(i)==')'||givenString.charAt(i)=='+'||givenString.charAt(i)=='='||givenString.charAt(i)=='/'|| (givenString.charAt(i) <=57 && givenString.charAt(i)>=48)||(givenString.charAt(i)<=90&&givenString.charAt(i)>=65)||(givenString.charAt(i)<=122&&givenString.charAt(i)>=97))
{
if(givenString.charAt(i)=='(')
{
paranthesisHolder.push((Character)givenString.charAt(i));
}
else if(givenString.charAt(i)==')')
{
if(paranthesisHolder.size()!=0)
paranthesisHolder.pop();
else
throw new PException();
}
}
else
{
throw new ICException();
}
}
if(paranthesisHolder.size()!=0)
throw new PException();
return true;
}
//This method removes white spaces from the given user input
public String inputWOSpaces(String givenString)
{
String correctString="";
givenString=givenString.trim();
for(int i=0;i<givenString.length();i++)
{
if(givenString.charAt(i)!=' ')
{
correctString=correctString+givenString.charAt(i);
}
}
return correctString;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
a802e46d767de3c60e5e88eae419a05703919d91 | 30c492163042ed8e00f612e91f4b1ac17ea73046 | /src/main/java/com/kantora/testove/POs/BasePO.java | d4ec25f0dfa41be5c2d9676132bd0c246a37db85 | [] | no_license | byteofmydream/testove | 05b286b7929adaf2136df2f03c477929de14bdd0 | 5209309163f6481b9aa1ab4f1b7b8ac721b851ed | refs/heads/master | 2021-01-01T15:49:46.660794 | 2017-07-19T15:56:55 | 2017-07-19T15:56:55 | 97,711,957 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 669 | java | package com.kantora.testove.POs;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import static utils.DriverWraper.getDriver;
public abstract class BasePO {
private final By closePopup = By.xpath("//div[@class='notificationPanelCross']");
public BasePO closePopup() {
WebDriverWait wait = new WebDriverWait(getDriver(), 10, 1000);
wait.until(ExpectedConditions.elementToBeClickable(closePopup));
getDriver().findElement(closePopup).click();
return this;
}
public BasePO(String URL) {
getDriver().get(URL);
}
}
| [
"byteofmydream@gmail.com"
] | byteofmydream@gmail.com |
8983cf758293b003b47ad24aa98eaeedaa2d7d31 | 741bf4171aab53b201c210cc6e5779417d1e5853 | /MelySig/src/fr/melysig/main/Erreurs.java | 792d5ee9b2e7999c7f1d8630e57159577ebaf326 | [] | no_license | JigSawFr/MelySig | 32608c201b9e2debc83cde22c5e68e55861568e0 | a99dd4a1fb8cdf5b91d63d4e3d41d84ff5c7f0fa | refs/heads/master | 2021-01-17T17:18:00.259503 | 2014-02-10T08:10:04 | 2014-02-10T08:10:04 | 16,376,759 | 1 | 0 | null | 2016-01-04T17:42:41 | 2014-01-30T12:31:36 | Java | UTF-8 | Java | false | false | 2,698 | java | /*
* MelySig - Geolocalisation de points d'interets sur vos endroits favoris !
* MelySig est systeme d'information geographique qui animera vos decouvertes du monde :)
* Copyright 2014 - melysig.exia-nancy.com
* Auteurs : Pocecco Julien, Mougenel Gerold, Gaudenot Guillaume & Robert Sebastien.
*/
package fr.melysig.main;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Singleton de <b>traitement des erreurs</b> du programme
*
* @author Sébastien R.
* @since 0.3
* @version 0.1.1
*/
public class Erreurs {
/**
* Statut du mode d'affichage des erreurs
*/
private boolean erreurs;
/**
* Horodatage de l'erreur
*/
private Date horodatageErreur;
/**
* Formatage de l'horodatage
*/
private DateFormat horodatageFormatErreur;
/**
* Objet (Singleton) de gestion des erreurs
*/
private static Erreurs gestionErreurs = null;
/**
* Constructeur du Singleton
*/
private Erreurs() {
}
/**
* Affichage des erreurs en console
*
* @param type Type de l'erreur
* @param message Message d'erreur
* @param erreur Code d'erreur
*/
public void erreur(String type, String message, Exception erreur) {
if (this.erreurs == true) {
this.horodatageErreur = new Date();
this.horodatageFormatErreur = new SimpleDateFormat("dd/MM/YYYY 'à' HH'h' mm'min' ss's' SSS'ms'");
if (erreur != null) {
System.out.println("[" + this.horodatageFormatErreur.format(this.horodatageErreur) + "] ERREUR : (" + type + ") - " + message + " (" + erreur.getMessage() + ")");
// --> A voir plus tard.
// JOptionPane.showMessageDialog(null,"Oooops Petit problème\n"+e.getMessage(),"Warning",JOptionPane.OK_OPTION);
} else {
System.out.println("[" + this.horodatageFormatErreur.format(this.horodatageErreur) + "] ERREUR : (" + type + ") - " + message);
}
}
}
/**
* Renvoi de l'instance actuelle ou création d'une nouvelle
*
* @return instance de l'objet gérant les ereurs
*/
public static Erreurs obtenirGestionErreurs() {
if (gestionErreurs == null) {
gestionErreurs = new Erreurs();
}
return gestionErreurs;
}
/**
* Permet de définir l'affichage ou non des erreurs
*
* @param erreurs statut des erreurs de type <code>boolean</code>
*/
public void setErreurs(boolean erreurs) {
this.erreurs = erreurs;
}
}
| [
"sebastien.robert@viacesi.fr"
] | sebastien.robert@viacesi.fr |
12af62d188ca70e0b9ea176dd2c0d03fc4aca8d1 | 67240956299b9e659e4b5e2006574b60168dc43d | /src/main/java/Complex.java | 1a1f752ad6c4d9dd38e24d33bfa580f1ee7d1532 | [] | no_license | vagishttn/SpringPractice | a72fc7bd504ea52ee1651336f46510cb087a774b | 920138508863aeaf7d4b13218e9dc4f666d4a99c | refs/heads/master | 2020-04-28T08:37:46.720505 | 2019-03-12T04:36:50 | 2019-03-12T04:36:50 | 175,135,973 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 285 | java | import lombok.*;
import lombok.experimental.FieldDefaults;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Getter
@Setter
@ToString
@NoArgsConstructor
@FieldDefaults(level = AccessLevel.PRIVATE)
public class Complex {
List list;
Set set;
Map map;
}
| [
"vagish.dixit@tothenew.com"
] | vagish.dixit@tothenew.com |
40e806a12ba0c015983e92ac5597f957bb86d5d9 | 5289e40e25fe505c0bf483aca75080c0f3ae69b4 | /platform/platform-impl/src/com/intellij/ide/ui/search/SearchableOptionsRegistrarImpl.java | a28b082fd1d9c4cdf15e663aa0df1501a9820e7a | [
"Apache-2.0"
] | permissive | haarlemmer/Jvav-Studio-Community | 507e4fa1b4873cd1ede5442219d105757a91abbb | de80b70f5507f0110de89a95d72b8f902ca72b3e | refs/heads/main | 2023-06-30T10:09:28.470066 | 2021-08-04T08:39:35 | 2021-08-04T08:39:35 | 392,603,002 | 0 | 0 | Apache-2.0 | 2021-08-04T08:04:52 | 2021-08-04T08:04:51 | null | UTF-8 | Java | false | false | 18,470 | java | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.ui.search;
import com.intellij.ide.plugins.DynamicPluginListener;
import com.intellij.ide.plugins.IdeaPluginDescriptor;
import com.intellij.ide.plugins.PluginManagerCore;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.options.ConfigurableGroup;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.Strings;
import com.intellij.util.CollectConsumer;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.ResourceUtil;
import com.intellij.util.containers.ContainerUtil;
import kotlin.Pair;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.event.DocumentEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.regex.Pattern;
@SuppressWarnings("Duplicates")
public final class SearchableOptionsRegistrarImpl extends SearchableOptionsRegistrar {
private static final ExtensionPointName<SearchableOptionContributor> EP_NAME = new ExtensionPointName<>("com.intellij.search.optionContributor");
// option => array of packed OptionDescriptor
private volatile Map<CharSequence, long[]> storage = Collections.emptyMap();
private final Set<String> stopWords;
private volatile @NotNull Map<Pair<String, String>, Set<String>> highlightOptionToSynonym = Collections.emptyMap();
private final AtomicBoolean isInitialized = new AtomicBoolean();
private volatile IndexedCharsInterner identifierTable = new IndexedCharsInterner();
private static final Logger LOG = Logger.getInstance(SearchableOptionsRegistrarImpl.class);
@NonNls
private static final Pattern REG_EXP = Pattern.compile("[\\W&&[^-]]+");
public SearchableOptionsRegistrarImpl() {
Application app = ApplicationManager.getApplication();
if (app.isCommandLine() || app.isHeadlessEnvironment()) {
stopWords = Collections.emptySet();
return;
}
stopWords = loadStopWords();
app.getMessageBus().connect().subscribe(DynamicPluginListener.TOPIC, new DynamicPluginListener() {
@Override
public void pluginLoaded(@NotNull IdeaPluginDescriptor pluginDescriptor) {
dropStorage();
}
@Override
public void pluginUnloaded(@NotNull IdeaPluginDescriptor pluginDescriptor, boolean isUpdate) {
dropStorage();
}
});
}
private static @NotNull Set<String> loadStopWords() {
try {
// stop words
InputStream stream = ResourceUtil.getResourceAsStream(SearchableOptionsRegistrarImpl.class.getClassLoader(), "search", "ignore.txt");
if (stream == null) {
throw new IOException("Broken installation: IDE does not provide /search/ignore.txt");
}
Set<String> result = new HashSet<>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.isEmpty()) {
result.add(line);
}
}
}
return result;
}
catch (IOException e) {
LOG.error(e);
return Collections.emptySet();
}
}
private synchronized void dropStorage() {
storage = Collections.emptyMap();
isInitialized.set(false);
}
public boolean isInitialized() {
return isInitialized.get();
}
@ApiStatus.Internal
public void initialize() {
if (!isInitialized.compareAndSet(false, true)) {
return;
}
MySearchableOptionProcessor processor = new MySearchableOptionProcessor(stopWords);
EP_NAME.forEachExtensionSafe(contributor -> contributor.processOptions(processor));
// index
highlightOptionToSynonym = processor.computeHighlightOptionToSynonym();
storage = processor.getStorage();
identifierTable = processor.getIdentifierTable();
}
static void processSearchableOptions(@NotNull Predicate<? super String> fileNameFilter, @NotNull BiConsumer<? super String, ? super Element> consumer) {
Set<ClassLoader> visited = Collections.newSetFromMap(new IdentityHashMap<>());
MethodType methodType = MethodType.methodType(void.class, String.class, Predicate.class, BiConsumer.class);
MethodHandles.Lookup lookup = MethodHandles.lookup();
Map<Class<?>, MethodHandle> handleCache = new HashMap<>();
for (IdeaPluginDescriptor plugin : PluginManagerCore.getLoadedPlugins()) {
ClassLoader classLoader = plugin.getPluginClassLoader();
if (!visited.add(classLoader)) {
continue;
}
MethodHandle methodHandle;
Class<?> loaderClass = classLoader.getClass();
if (loaderClass.isAnonymousClass() || loaderClass.isMemberClass()) {
loaderClass = loaderClass.getSuperclass();
}
try {
methodHandle = handleCache.computeIfAbsent(loaderClass, aClass -> {
try {
return lookup.findVirtual(aClass, "processResources", methodType);
}
catch (NoSuchMethodException | IllegalAccessException e) {
throw new RuntimeException(e);
}
});
}
catch (RuntimeException e) {
if (e.getCause() instanceof NoSuchMethodException) {
LOG.error(loaderClass + " is not supported", e);
}
else {
LOG.error(e);
}
continue;
}
try {
methodHandle.invoke(classLoader, "search", fileNameFilter, (BiConsumer<String, InputStream>)(name, stream) -> {
try {
consumer.accept(name, JDOMUtil.load(stream));
}
catch (IOException | JDOMException e) {
throw new RuntimeException(e);
}
});
}
catch (Throwable throwable) {
ExceptionUtil.rethrow(throwable);
}
}
}
/**
* @return XYZT:64 bits where X:16 bits - id of the interned groupName
* Y:16 bits - id of the interned id
* Z:16 bits - id of the interned hit
* T:16 bits - id of the interned path
*/
@SuppressWarnings("SpellCheckingInspection")
static long pack(@NotNull String id, @Nullable String hit, @Nullable String path, @Nullable String groupName, @NotNull IndexedCharsInterner identifierTable) {
long _id = identifierTable.toId(id.trim());
long _hit = hit == null ? Short.MAX_VALUE : identifierTable.toId(hit.trim());
long _path = path == null ? Short.MAX_VALUE : identifierTable.toId(path.trim());
long _groupName = groupName == null ? Short.MAX_VALUE : identifierTable.toId(groupName.trim());
assert _id >= 0 && _id < Short.MAX_VALUE;
assert _hit >= 0 && _hit <= Short.MAX_VALUE;
assert _path >= 0 && _path <= Short.MAX_VALUE;
assert _groupName >= 0 && _groupName <= Short.MAX_VALUE;
return _groupName << 48 | _id << 32 | _hit << 16 | _path/* << 0*/;
}
private OptionDescription unpack(long data) {
int _groupName = (int)(data >> 48 & 0xffff);
int _id = (int)(data >> 32 & 0xffff);
int _hit = (int)(data >> 16 & 0xffff);
int _path = (int)(data & 0xffff);
assert /*_id >= 0 && */_id < Short.MAX_VALUE;
assert /*_hit >= 0 && */_hit <= Short.MAX_VALUE;
assert /*_path >= 0 && */_path <= Short.MAX_VALUE;
assert /*_groupName >= 0 && */_groupName <= Short.MAX_VALUE;
String groupName = _groupName == Short.MAX_VALUE ? null : identifierTable.fromId(_groupName).toString();
String configurableId = identifierTable.fromId(_id).toString();
String hit = _hit == Short.MAX_VALUE ? null : identifierTable.fromId(_hit).toString();
String path = _path == Short.MAX_VALUE ? null : identifierTable.fromId(_path).toString();
return new OptionDescription(null, configurableId, hit, path, groupName);
}
@Override
public @NotNull ConfigurableHit getConfigurables(@NotNull List<? extends ConfigurableGroup> groups,
DocumentEvent.EventType type,
@Nullable Set<? extends Configurable> configurables,
@NotNull String option,
@Nullable Project project) {
//noinspection unchecked
return findConfigurables(groups, type, (Collection<Configurable>)configurables, option, project);
}
private @NotNull ConfigurableHit findConfigurables(@NotNull List<? extends ConfigurableGroup> groups,
DocumentEvent.EventType type,
@Nullable Collection<Configurable> configurables,
@NotNull String option,
@Nullable Project project) {
if (ContainerUtil.isEmpty(configurables)) {
configurables = null;
}
Collection<Configurable> effectiveConfigurables;
if (configurables == null) {
effectiveConfigurables = new LinkedHashSet<>();
Consumer<Configurable> consumer = new CollectConsumer<>(effectiveConfigurables);
for (ConfigurableGroup group : groups) {
SearchUtil.processExpandedGroups(group, consumer);
}
}
else {
effectiveConfigurables = configurables;
}
String optionToCheck = StringUtil.toLowerCase(option.trim());
Set<String> options = getProcessedWordsWithoutStemming(optionToCheck);
Set<Configurable> nameHits = new LinkedHashSet<>();
Set<Configurable> nameFullHits = new LinkedHashSet<>();
for (Configurable each : effectiveConfigurables) {
if (each.getDisplayName() == null) continue;
final String displayName = StringUtil.toLowerCase(each.getDisplayName());
final List<String> allWords = StringUtil.getWordsIn(displayName);
if (displayName.contains(optionToCheck)) {
nameFullHits.add(each);
nameHits.add(each);
}
for (String eachWord : allWords) {
if (eachWord.startsWith(optionToCheck)) {
nameHits.add(each);
break;
}
}
if (options.isEmpty()) {
nameHits.add(each);
nameFullHits.add(each);
}
}
Set<Configurable> currentConfigurables = type == DocumentEvent.EventType.CHANGE ? new HashSet<>(effectiveConfigurables) : null;
// operate with substring
if (options.isEmpty()) {
String[] components = REG_EXP.split(optionToCheck);
if (components.length > 0) {
Collections.addAll(options, components);
}
else {
options.add(option);
}
}
Set<Configurable> contentHits;
if (configurables == null) {
contentHits = (Set<Configurable>)effectiveConfigurables;
}
else {
contentHits = new LinkedHashSet<>(effectiveConfigurables);
}
Set<String> helpIds = null;
for (String opt : options) {
final Set<OptionDescription> optionIds = getAcceptableDescriptions(opt);
if (optionIds == null) {
contentHits.clear();
return new ConfigurableHit(nameHits, nameFullHits, contentHits);
}
final Set<String> ids = new HashSet<>();
for (OptionDescription id : optionIds) {
ids.add(id.getConfigurableId());
}
if (helpIds == null) {
helpIds = ids;
}
helpIds.retainAll(ids);
}
if (helpIds != null) {
for (Iterator<Configurable> it = contentHits.iterator(); it.hasNext();) {
Configurable configurable = it.next();
boolean needToRemove = true;
if (configurable instanceof SearchableConfigurable && helpIds.contains(((SearchableConfigurable)configurable).getId())) {
needToRemove = false;
}
if (configurable instanceof SearchableConfigurable.Merged) {
final List<Configurable> mergedConfigurables = ((SearchableConfigurable.Merged)configurable).getMergedConfigurables();
for (Configurable mergedConfigurable : mergedConfigurables) {
if (mergedConfigurable instanceof SearchableConfigurable &&
helpIds.contains(((SearchableConfigurable)mergedConfigurable).getId())) {
needToRemove = false;
break;
}
}
}
if (needToRemove) {
it.remove();
}
}
}
if (type == DocumentEvent.EventType.CHANGE && configurables != null && currentConfigurables.equals(contentHits)) {
return getConfigurables(groups, DocumentEvent.EventType.CHANGE, null, option, project);
}
return new ConfigurableHit(nameHits, nameFullHits, contentHits);
}
public synchronized @Nullable Set<OptionDescription> getAcceptableDescriptions(@Nullable String prefix) {
if (prefix == null) {
return null;
}
final String stemmedPrefix = PorterStemmerUtil.stem(prefix);
if (StringUtil.isEmptyOrSpaces(stemmedPrefix)) {
return null;
}
initialize();
Set<OptionDescription> result = null;
for (Map.Entry<CharSequence, long[]> entry : storage.entrySet()) {
final long[] descriptions = entry.getValue();
final CharSequence option = entry.getKey();
if (!StringUtil.startsWith(option, prefix) && !StringUtil.startsWith(option, stemmedPrefix)) {
final String stemmedOption = PorterStemmerUtil.stem(option.toString());
if (stemmedOption != null && !stemmedOption.startsWith(prefix) && !stemmedOption.startsWith(stemmedPrefix)) {
continue;
}
}
if (result == null) {
result = new HashSet<>();
}
for (long description : descriptions) {
OptionDescription desc = unpack(description);
result.add(desc);
}
}
return result;
}
private @Nullable Set<OptionDescription> getOptionDescriptionsByWords(SearchableConfigurable configurable, Set<String> words) {
Set<OptionDescription> path = null;
for (String word : words) {
Set<OptionDescription> configs = getAcceptableDescriptions(word);
if (configs == null) return null;
final Set<OptionDescription> paths = new HashSet<>();
for (OptionDescription config : configs) {
if (Comparing.strEqual(config.getConfigurableId(), configurable.getId())) {
paths.add(config);
}
}
if (path == null) {
path = paths;
}
path.retainAll(paths);
}
return path;
}
@Override
public @NotNull Set<String> getInnerPaths(SearchableConfigurable configurable, String option) {
initialize();
final Set<String> words = getProcessedWordsWithoutStemming(option);
final Set<OptionDescription> path = getOptionDescriptionsByWords(configurable, words);
Set<String> resultSet = new HashSet<>();
if (path != null && !path.isEmpty()) {
OptionDescription theOnlyResult = null;
for (OptionDescription description : path) {
final String hit = description.getHit();
if (hit != null) {
boolean theBest = true;
for (String word : words) {
if (!StringUtil.containsIgnoreCase(hit, word)) {
theBest = false;
break;
}
}
if (theBest) {
resultSet.add(description.getPath());
}
}
theOnlyResult = description;
}
if (resultSet.isEmpty())
resultSet.add(theOnlyResult.getPath());
}
return resultSet;
}
@Override
public boolean isStopWord(String word) {
return stopWords.contains(word);
}
@Override
public @NotNull Set<String> getProcessedWordsWithoutStemming(@NotNull String text) {
Set<String> result = new HashSet<>();
collectProcessedWordsWithoutStemming(text, result, stopWords);
return result;
}
@ApiStatus.Internal
public static void collectProcessedWordsWithoutStemming(@NotNull String text, @NotNull Set<? super String> result, @NotNull Set<String> stopWords) {
for (String opt : REG_EXP.split(Strings.toLowerCase(text))) {
if (stopWords.contains(opt)) {
continue;
}
String processed = PorterStemmerUtil.stem(opt);
if (stopWords.contains(processed)) {
continue;
}
result.add(opt);
}
}
@Override
public Set<String> getProcessedWords(@NotNull String text) {
Set<String> result = new HashSet<>();
collectProcessedWords(text, result, stopWords);
return result;
}
static void collectProcessedWords(@NotNull String text, @NotNull Set<? super String> result, @NotNull Set<String> stopWords) {
String toLowerCase = StringUtil.toLowerCase(text);
final String[] options = REG_EXP.split(toLowerCase);
for (String opt : options) {
if (stopWords.contains(opt)) {
continue;
}
opt = PorterStemmerUtil.stem(opt);
if (opt == null) {
continue;
}
result.add(opt);
}
}
@Override
public @NotNull Set<String> replaceSynonyms(@NotNull Set<String> options, @NotNull SearchableConfigurable configurable) {
if (highlightOptionToSynonym.isEmpty()) {
return options;
}
Set<String> result = new HashSet<>(options);
initialize();
for (String option : options) {
Set<String> synonyms = highlightOptionToSynonym.get(new Pair<>(option, configurable.getId()));
if (synonyms != null) {
result.addAll(synonyms);
}
else {
result.add(option);
}
}
return result;
}
}
| [
"luckystar5408@github.com"
] | luckystar5408@github.com |
1b399e2a0af1d88f94beb09735d1985f82c4d371 | f767b5f5bb09fbe6368711b5d5f8986f40d0da0a | /src/main/java/oop/Run.java | 6d984d58f63195c4d9fc88e1483f99872e266bad | [] | no_license | MikiKru/tarr5_java_adv | 10c3f0f6564bf6e0261cb2c579e10e210cb66ce6 | 822f7638c9e0312eff59f01b794eead25e426435 | refs/heads/master | 2022-11-21T16:45:46.643420 | 2020-07-19T10:00:23 | 2020-07-19T10:00:23 | 277,061,053 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 6,359 | java | package oop;
import oop.controller.InputOutputController;
import oop.controller.UserController;
import oop.controller.UserControllerTempl;
import oop.model.User;
import oop.model.enums.Gender;
import oop.model.enums.Role;
import java.util.*;
import java.util.regex.Pattern;
public class Run extends InputOutputController {
public static void main(String[] args) {
// 1. Wywołanie obiektu klasy UserController
UserController uc = new UserController();
Scanner scanner = new Scanner(System.in);
Run run = new Run();
// pobieranie danych z pliku
run.readUsersFromFile();
// -------------------------
while(true) {
System.out.println("Co chcesz zrobic? \n1.Rejestracja \n2.Lista użytkowników \n3.Logowanie \n4.Zmień hasło " +
"\n5.Usuń użytkownika \n6.Wypisz posortowanych użytkowników \n7.Przypisz role \nQ.Wyjście");
String choice = scanner.nextLine().toUpperCase();
if(choice.equals("1")){
System.out.println("Podaj imię:");
String name = scanner.nextLine();
System.out.println("Podaj nazwisko:");
String lastName = scanner.nextLine();
System.out.println("Podaj email:");
String email = scanner.nextLine();
//---
String emailPattern = "^\\S{1,}[@]\\S{1,}$"; // \S - any non-whitespace character
if(!Pattern.matches(emailPattern, email)){
System.out.println("Błędny adres e-mail");
continue;
}
//---
System.out.println("Podaj hasło:");
String password = scanner.nextLine();
System.out.println("Podaj płeć (M/K):");
String genderInput = scanner.nextLine().toUpperCase();
//---
String genderPattern = "^[MK]{1}$";
if(!Pattern.matches(genderPattern,genderInput)){
System.out.println("Błędnie wprowadzona płeć");
continue;
}
//---
Gender gender = genderInput.equals("M") ? Gender.MAN : Gender.WOMAN;
System.out.println("Podaj telefon (000-000-000):");
String phone = scanner.nextLine();
//---
String phonePattern = "^[0-9]{3}(-[0-9]{3}){2}$";
if(!Pattern.matches(phonePattern, phone)){
System.out.println("Błędny numer telefonu!");
continue;
}
//---
uc.registerUser(new User(name, lastName, email, password, phone, gender));
} else if(choice.equals("2")) {
uc.findAllUsers().forEach(user -> System.out.println(user));
} else if (choice.equals("3")) {
System.out.println("Podaj email:");
String email = scanner.nextLine();
System.out.println("Podaj hasło:");
String password = scanner.nextLine();
uc.loginUser(email, password);
} else if (choice.equals("4")) {
try {
System.out.println("Podaj id:");
int userId = Integer.valueOf(scanner.nextLine());
System.out.println("Podaj nowe hasło:");
String newPassword = scanner.nextLine();
uc.updateUserPassword(userId, newPassword);
} catch (InputMismatchException e) {
System.out.println("Błędny id");
}
} else if (choice.equals("5")){
try {
System.out.println("Podaj id użytkownika, którego chcesz usunąć");
int userId = Integer.valueOf(scanner.nextLine());
uc.deleteUserById(userId);
} catch (InputMismatchException e){
System.out.println("Błędny id");
}
} else if (choice.equals("6")){
System.out.println("Wybierz typ sortowania ASC - rosnąco, DESC - malejąco");
boolean asc = true;
String decision = scanner.nextLine();
if(decision.toUpperCase().equals("DESC")){
asc = false;
}
uc.findAllUsersOrderByEmail(asc).forEach(user -> System.out.println(user));
} else if(choice.equals("7")){
try {
System.out.println("Podaj id użytkownika");
int userId = Integer.valueOf(scanner.nextLine());
Set<Role> roles = new HashSet<>();
if(uc.findUserById(userId) == null){
continue; // powrót do główengo menu
}
// wybór ról
while(true){
System.out.println("Wybierz rolę (Q-kończę wybór):");
Arrays.stream(Role.values()).forEach(role -> System.out.println(role.ordinal() + ". " + role));
String decision = scanner.nextLine();
if(decision.equals("0")){
roles.add(Role.ROLE_USER);
} else if(decision.equals("1")){
roles.add(Role.ROLE_ADMIN);
} else if (decision.equals("2")){
roles.add(Role.ROLE_VIEWER);
} else if (decision.toUpperCase().equals("Q")){
System.out.println("Zaktualizowano zbiór ról: " + roles);
break;
} else {
System.out.println("Błędny wybór");
}
}
uc.updateRole(userId, roles);
} catch (InputMismatchException e){
System.out.println("Błędny id");
}
} else if (choice.equals("Q")) {
run.saveUsersToFile();
System.out.println("Wyjście");
break;
} else {
System.out.println("Błędny wybór");
}
}
}
}
| [
"michal_kruczkowski@o2.pl"
] | michal_kruczkowski@o2.pl |
c4917715d4e1f7daf902bbfc2b9f7245e7d8c203 | bc2565f07acd001ddbe00ee1ce276e6a0e433138 | /64_Almacen_DAO_MVC/src/idao/iProductoDAO.java | caa7cfbb300b12d099df39e80325440f2ba451d8 | [] | no_license | BEITXUELA/curso2020 | 6b329089f8017f8c7c84d25dfea6c6004c5ecaa0 | 45debb93cfc828536ca62f734855728436c91d2d | refs/heads/main | 2023-03-10T21:15:22.134200 | 2021-02-25T09:11:43 | 2021-02-25T09:11:43 | 342,018,564 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 367 | java | package idao;
import java.util.ArrayList;
import model.Producto;
public interface iProductoDAO {
public boolean insertarProducto(Producto producto);//Create
public ArrayList<Producto> leerProductos();//Read
public boolean modificarProducto(Producto producto);//Update
public boolean borrarProducto(Producto producto);//Delete
}
| [
"noreply@github.com"
] | noreply@github.com |
2b975178d9b5758d69b47175794bdfce676240a7 | 2970bc2c42815c36c867692ee06dfa5d236e56b8 | /src/main/java/com/springboot/student/service/IDepartmentService.java | 2a15f78476714fdcd116c6e81ac5f81986714f01 | [] | no_license | parthdave24/student-app | 3a7184ea3cae665d6fe7f0a0198e04ccdd6106a1 | 34ea3905b3a448def04ba38dc55d8b508cd27f38 | refs/heads/master | 2020-03-17T20:10:45.894260 | 2018-05-18T02:48:43 | 2018-05-18T02:48:43 | 133,891,157 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 430 | java | package com.springboot.student.service;
import java.util.List;
import com.springboot.student.dao.Department;
public interface IDepartmentService {
public List<Department> getAllDepartments();
public Department getDepartment(int departmentId);
public void addDepartment(Department department);
public void updateDepartment(int departmentId, Department department);
public void deleteDepartment(int departmentId);
}
| [
"pdave@iBASEt.com"
] | pdave@iBASEt.com |
ca451ada305983e75d8c8caaf0478a56025a5e30 | c341654d60648f27610115866e08094d9b0c9fa2 | /src/main/java/dad/javafx/geometria/shapes/Triangle.java | 194dca2a24d87bc1a410573244bd196fd99fa8b1 | [] | no_license | Bukitei/Geometria2 | 529482c6cefc78d8a0367eabbd3eb39527752bc2 | b66022d5d645eb7447493c33c077b3288cf41573 | refs/heads/master | 2020-08-20T12:31:46.582772 | 2019-10-18T13:03:05 | 2019-10-18T13:03:05 | 216,023,476 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,287 | java | package dad.javafx.geometria.shapes;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.scene.shape.Polygon;
public class Triangle extends Polygon {
private DoubleProperty base = new SimpleDoubleProperty();
private DoubleProperty height = new SimpleDoubleProperty();
public Triangle(double base, double height) {
super();
this.base.set(base);
this.height.set(height);
createPoints();
this.base.addListener((o, ov, nv) -> createPoints());
this.height.addListener((o, ov, nv) -> createPoints());
}
public Triangle() {
this(0.0, 0.0);
}
private void createPoints() {
getPoints().clear();
getPoints().addAll(base.get() / 2.0, 0.0);
getPoints().addAll(base.get(), height.get());
getPoints().addAll(0.0, height.get());
}
public final DoubleProperty baseProperty() {
return this.base;
}
public final double getBase() {
return this.baseProperty().get();
}
public final void setBase(final double base) {
this.baseProperty().set(base);
}
public final DoubleProperty heightProperty() {
return this.height;
}
public final double getHeight() {
return this.heightProperty().get();
}
public final void setHeight(final double height) {
this.heightProperty().set(height);
}
}
| [
"borjagomezb@gmail.com"
] | borjagomezb@gmail.com |
9b8a33fd0141f4f00906c6c2ef067675c6a7dd05 | 69394a234ea8d7041342716c0f836bdf1eb96fc6 | /app/src/main/java/com/example/linked/ChatScreenActivity.java | 236530c04f37328b97c587d785954f54d09bc347 | [] | no_license | jagmeet-singh2091051/linked | 25eca95c681c3ff9fdde6be15ac64b95d5ac32f9 | 6a71405e1273a758a1502819230b6f52265dc230 | refs/heads/master | 2023-02-16T15:51:43.759536 | 2021-01-16T10:44:47 | 2021-01-16T10:44:47 | 305,863,801 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,809 | java | package com.example.linked;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.QueryDocumentSnapshot;
import com.google.firebase.firestore.QuerySnapshot;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
public class ChatScreenActivity extends AppCompatActivity {
UserModel userInstance = UserModel.getInstance();
List<MessageModel> messageList = new ArrayList<MessageModel>();
FirebaseFirestore db = FirebaseFirestore.getInstance();
TextView usernameTV;
TextView initialsTV;
ImageButton sendBtn;
EditText messageET;
RecyclerView messagesRecyclerview;
MessageAdapter messageAdapter;
private String contactUserId;
private String contactUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_screen);
messageET = findViewById(R.id.text_send);
sendBtn = findViewById(R.id.send_button);
usernameTV = findViewById(R.id.username);
initialsTV = findViewById(R.id.profile_image);
Intent intentThatStartedThisActivity = getIntent();
if(intentThatStartedThisActivity.hasExtra("CONTACT_USER_ID")){
contactUserId = intentThatStartedThisActivity.getStringExtra("CONTACT_USER_ID");
}
if(intentThatStartedThisActivity.hasExtra("CONTACT_USER_NAME")){
contactUsername = intentThatStartedThisActivity.getStringExtra("CONTACT_USER_NAME");
}
initialsTV.setText(String.valueOf(contactUsername.toUpperCase().charAt(0)));
usernameTV.setText(contactUsername);
messagesRecyclerview = findViewById(R.id.chatScreenRecycleView);
messagesRecyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
db.collection(HomeScreenActivity.USERS_COLLECTION_PATH)
.document(userInstance.getUserId())
.collection(HomeScreenActivity.CONTACTS_COLLECTION_PATH)
.document(contactUserId)
.collection(HomeScreenActivity.MESSAGES_COLLECTION_PATH)
.orderBy("timestamp")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
if (error != null) {
Log.e( "Listen failed: ", error.toString());
return;
}
else{
messageList.clear();
}
for(QueryDocumentSnapshot doc : value){
if(doc.get("message") != null){
MessageModel msg = new MessageModel(doc.getString("message"), doc.getString("timeSent"),
doc.getString("timeReceived"), doc.getBoolean("sent"), doc.getTimestamp("timestamp"));
messageList.add(msg);
}
}
}
});
messageAdapter = new MessageAdapter(messageList);
messagesRecyclerview.setAdapter(messageAdapter);
sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!messageET.getText().toString().equals("")){
DateFormat df = new SimpleDateFormat("h:mm a", Locale.getDefault());
String date = df.format(Calendar.getInstance().getTime());
MessageModel newSentMsg = new MessageModel(messageET.getText().toString(), date, date, true, Timestamp.now());
MessageModel newReceivedMsg = new MessageModel(messageET.getText().toString(), date, date, false, Timestamp.now());
messageList.add(newSentMsg);
messageAdapter.notifyDataSetChanged();
//Send message to our db
db.collection(HomeScreenActivity.USERS_COLLECTION_PATH)
.document(userInstance.getUserId())
.collection(HomeScreenActivity.CONTACTS_COLLECTION_PATH)
.document(contactUserId)
.collection(HomeScreenActivity.MESSAGES_COLLECTION_PATH)
.add(newSentMsg)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
//messageAdapter.notifyDataSetChanged();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("Message not sent: ", e.toString());
}
});
//Send message to contact's db
db.collection(HomeScreenActivity.USERS_COLLECTION_PATH)
.document(contactUserId)
.collection(HomeScreenActivity.CONTACTS_COLLECTION_PATH)
.document(userInstance.getUserId())
.collection(HomeScreenActivity.MESSAGES_COLLECTION_PATH)
.add(newReceivedMsg)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
//messageAdapter.notifyDataSetChanged();
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("Message not sent: ", e.toString());
}
});
}
//update last msg
if (!messageList.isEmpty()) {
db.collection(HomeScreenActivity.USERS_COLLECTION_PATH)
.document(userInstance.getUserId())
.collection(HomeScreenActivity.CONTACTS_COLLECTION_PATH)
.document(contactUserId)
.update(HomeScreenActivity.LAST_MSG_PATH, messageList.get(messageList.size() - 1).getMessage()
, HomeScreenActivity.LAST_MSG_TIME_PATH, messageList.get(messageList.size() - 1).getTimeSent())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.e("LastMsgUpdate Success", messageList.get(messageList.size() - 1).getMessage());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e("LastMsgUpdate Failed", e.toString());
}
});
}
messageET.setText("");
}
});
}
/*@Override
protected void onDestroy() {
super.onDestroy();
if (!messageList.isEmpty()) {
db.collection(HomeScreenActivity.USERS_COLLECTION_PATH)
.document(userInstance.getUserId())
.collection(HomeScreenActivity.CONTACTS_COLLECTION_PATH)
.document(contactUserId)
.update(HomeScreenActivity.LAST_MSG_PATH, messageList.get(messageList.size() - 1).getMessage()
, HomeScreenActivity.LAST_MSG_TIME_PATH, messageList.get(messageList.size() - 1).getTimeSent())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
}
}*/
}
| [
"36414846+AmanGujral@users.noreply.github.com"
] | 36414846+AmanGujral@users.noreply.github.com |
d797645854de3ce72b74f9d7e63e19dbb533feeb | 5c7d6bfd9e1cac3ada518a41bf9d0a02eb6988a7 | /ProjetoCrud/.svn/pristine/12/1262d36eef9c30593cf245409d7ac4fd1c0824e1.svn-base | d8e715db213e97318f034f86b88b3b4d8b112096 | [] | no_license | carlodrs/Projetos-2.0 | 16e5fd0dedf869cbc6facf792ba709591fc253f1 | 96fa2f88a71d19d8f59717a0fd5c3c70b3be19bc | refs/heads/master | 2021-01-23T22:10:21.283328 | 2014-11-22T00:37:49 | 2014-11-22T00:37:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 317 | package com.projetocrud.enums;
public enum Country {
BRASIL ("Brasil"),
ARGENTINA ("Argentina"),
EUA ("Estados Unidos");
private String name;
Country(String name){
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name){
this.name = name;
}
}
| [
"carlosrenato.s@gmail.com"
] | carlosrenato.s@gmail.com | |
24d9cc147af042e46259f4c621841885fa57623f | 12b14b30fcaf3da3f6e9dc3cb3e717346a35870a | /examples/commons-math3/mutations/mutants-TriangularDistribution/18/org/apache/commons/math3/distribution/TriangularDistribution.java | 5ccfaaedaa0be1684940156240583d00b43c81df | [
"BSD-3-Clause",
"Minpack",
"Apache-2.0"
] | permissive | SmartTests/smartTest | b1de326998857e715dcd5075ee322482e4b34fb6 | b30e8ec7d571e83e9f38cd003476a6842c06ef39 | refs/heads/main | 2023-01-03T01:27:05.262904 | 2020-10-27T20:24:48 | 2020-10-27T20:24:48 | 305,502,060 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,696 | java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.distribution;
import org.apache.commons.math3.exception.NumberIsTooLargeException;
import org.apache.commons.math3.exception.NumberIsTooSmallException;
import org.apache.commons.math3.exception.OutOfRangeException;
import org.apache.commons.math3.exception.util.LocalizedFormats;
import org.apache.commons.math3.util.FastMath;
import org.apache.commons.math3.random.RandomGenerator;
import org.apache.commons.math3.random.Well19937c;
/**
* Implementation of the triangular real distribution.
*
* @see <a href="http://en.wikipedia.org/wiki/Triangular_distribution">
* Triangular distribution (Wikipedia)</a>
*
* @version $Id$
* @since 3.0
*/
public class TriangularDistribution extends AbstractRealDistribution {
/** Serializable version identifier. */
private static final long serialVersionUID = 20120112L;
/** Lower limit of this distribution (inclusive). */
private final double a;
/** Upper limit of this distribution (inclusive). */
private final double b;
/** Mode of this distribution. */
private final double c;
/** Inverse cumulative probability accuracy. */
private final double solverAbsoluteAccuracy;
/**
* Creates a triangular real distribution using the given lower limit,
* upper limit, and mode.
*
* @param a Lower limit of this distribution (inclusive).
* @param b Upper limit of this distribution (inclusive).
* @param c Mode of this distribution.
* @throws NumberIsTooLargeException if {@code a >= b} or if {@code c > b}.
* @throws NumberIsTooSmallException if {@code c < a}.
*/
public TriangularDistribution(double a, double c, double b)
throws NumberIsTooLargeException, NumberIsTooSmallException {
this(new Well19937c(), a, c, b);
}
/**
* Creates a triangular distribution.
*
* @param rng Random number generator.
* @param a Lower limit of this distribution (inclusive).
* @param b Upper limit of this distribution (inclusive).
* @param c Mode of this distribution.
* @throws NumberIsTooLargeException if {@code a >= b} or if {@code c > b}.
* @throws NumberIsTooSmallException if {@code c < a}.
* @since 3.1
*/
public TriangularDistribution(RandomGenerator rng,
double a,
double c,
double b)
throws NumberIsTooLargeException, NumberIsTooSmallException {
super(rng);
if (a >= b) {
throw new NumberIsTooLargeException(
LocalizedFormats.LOWER_BOUND_NOT_BELOW_UPPER_BOUND,
a, b, false);
}
if (c < a) {
throw new NumberIsTooSmallException(
LocalizedFormats.NUMBER_TOO_SMALL, c, a, true);
}
if (c > b) {
throw new NumberIsTooLargeException(
LocalizedFormats.NUMBER_TOO_LARGE, c, b, true);
}
this.a = a;
this.c = c;
this.b = b;
solverAbsoluteAccuracy = FastMath.max(FastMath.ulp(a), FastMath.ulp(b));
}
/**
* Returns the mode {@code c} of this distribution.
*
* @return the mode {@code c} of this distribution
*/
public double getMode() {
return c;
}
/**
* {@inheritDoc}
*
* <p>
* For this distribution, the returned value is not really meaningful,
* since exact formulas are implemented for the computation of the
* {@link #inverseCumulativeProbability(double)} (no solver is invoked).
* </p>
* <p>
* For lower limit {@code a} and upper limit {@code b}, the current
* implementation returns {@code max(ulp(a), ulp(b)}.
* </p>
*/
@Override
protected double getSolverAbsoluteAccuracy() {
return 0.0;
}
/**
* {@inheritDoc}
*
* For lower limit {@code a}, upper limit {@code b} and mode {@code c}, the
* PDF is given by
* <ul>
* <li>{@code 2 * (x - a) / [(b - a) * (c - a)]} if {@code a <= x < c},</li>
* <li>{@code 2 / (b - a)} if {@code x = c},</li>
* <li>{@code 2 * (b - x) / [(b - a) * (b - c)]} if {@code c < x <= b},</li>
* <li>{@code 0} otherwise.
* </ul>
*/
public double density(double x) {
if (x < a) {
return 0;
}
if (a <= x && x < c) {
double divident = 2 * (x - a);
double divisor = (b - a) * (c - a);
return divident / divisor;
}
if (x == c) {
return 2 / (b - a);
}
if (c < x && x <= b) {
double divident = 2 * (b - x);
double divisor = (b - a) * (b - c);
return divident / divisor;
}
return 0;
}
/**
* {@inheritDoc}
*
* For lower limit {@code a}, upper limit {@code b} and mode {@code c}, the
* CDF is given by
* <ul>
* <li>{@code 0} if {@code x < a},</li>
* <li>{@code (x - a)^2 / [(b - a) * (c - a)]} if {@code a <= x < c},</li>
* <li>{@code (c - a) / (b - a)} if {@code x = c},</li>
* <li>{@code 1 - (b - x)^2 / [(b - a) * (b - c)]} if {@code c < x <= b},</li>
* <li>{@code 1} if {@code x > b}.</li>
* </ul>
*/
public double cumulativeProbability(double x) {
if (x < a) {
return 0;
}
if (a <= x && x < c) {
double divident = (x - a) * (x - a);
double divisor = (b - a) * (c - a);
return divident / divisor;
}
if (x == c) {
return (c - a) / (b - a);
}
if (c < x && x <= b) {
double divident = (b - x) * (b - x);
double divisor = (b - a) * (b - c);
return 1 - (divident / divisor);
}
return 1;
}
/**
* {@inheritDoc}
*
* For lower limit {@code a}, upper limit {@code b}, and mode {@code c},
* the mean is {@code (a + b + c) / 3}.
*/
public double getNumericalMean() {
return (a + b + c) / 3;
}
/**
* {@inheritDoc}
*
* For lower limit {@code a}, upper limit {@code b}, and mode {@code c},
* the variance is {@code (a^2 + b^2 + c^2 - a * b - a * c - b * c) / 18}.
*/
public double getNumericalVariance() {
return (a * a + b * b + c * c - a * b - a * c - b * c) / 18;
}
/**
* {@inheritDoc}
*
* The lower bound of the support is equal to the lower limit parameter
* {@code a} of the distribution.
*
* @return lower bound of the support
*/
public double getSupportLowerBound() {
return a;
}
/**
* {@inheritDoc}
*
* The upper bound of the support is equal to the upper limit parameter
* {@code b} of the distribution.
*
* @return upper bound of the support
*/
public double getSupportUpperBound() {
return b;
}
/** {@inheritDoc} */
public boolean isSupportLowerBoundInclusive() {
return true;
}
/** {@inheritDoc} */
public boolean isSupportUpperBoundInclusive() {
return true;
}
/**
* {@inheritDoc}
*
* The support of this distribution is connected.
*
* @return {@code true}
*/
public boolean isSupportConnected() {
return true;
}
@Override
public double inverseCumulativeProbability(double p)
throws OutOfRangeException {
if (p < 0 || p > 1) {
throw new OutOfRangeException(p, 0, 1);
}
if (p == 0) {
return a;
}
if (p == 1) {
return b;
}
if (p < (c - a) / (b - a)) {
return a + FastMath.sqrt(p * (b - a) * (c - a));
}
return b - FastMath.sqrt((1 - p) * (b - a) * (b - c));
}
}
| [
"kesina@Kesinas-MBP.lan"
] | kesina@Kesinas-MBP.lan |
511d2dc5712b17e25bed0bc7844b5623c3b106af | 2c52409f5864cd445a1f7d1dc8db4982cb52a61c | /src/main/java/com/shiro/UserRealm.java | 72947452f243c11a222a7d92c9cbf79e4e954460 | [] | no_license | Aly622/MVCSite | a870cfe4d553528f5b8c910ca73146afec3e4320 | 587ae2d2f08639c530e5cfe8ae85b9a101c3acdd | refs/heads/master | 2021-01-12T15:41:34.983110 | 2016-10-25T02:59:55 | 2016-10-25T02:59:55 | 71,853,724 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,662 | java | package com.shiro;
import com.model.Permission;
import com.model.Role;
import com.model.User;
import com.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Created by Oliver.Liu on 6/28/2016.
*/
public class UserRealm extends AuthorizingRealm {
@Autowired
private IUserService userService;
/**
* 授权操作
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// String username = (String) getAvailablePrincipal(principals);
String username = (String) principals.getPrimaryPrincipal();
Set<Role> roleSet = userService.findUserByUsername(username).getRoleSet();
//角色名的集合
Set<String> roles = new HashSet<String>();
//权限名的集合
Set<String> permissions = new HashSet<String>();
Iterator<Role> it = roleSet.iterator();
while(it.hasNext()){
roles.add(it.next().getRoleName());
for(Permission per:it.next().getPermissionSet()){
permissions.add(per.getResourceCode());
}
}
SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
authorizationInfo.addRoles(roles);
authorizationInfo.addStringPermissions(permissions);
return authorizationInfo;
}
/**
* 身份验证操作
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
String username = (String) token.getPrincipal();
User user = userService.findUserByUsername(username);
if(user==null){
//木有找到用户
throw new UnknownAccountException("没有找到该账号");
}
/* if(Boolean.TRUE.equals(user.getLocked())) {
throw new LockedAccountException(); //帐号锁定
} */
/**
* 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以在此判断或自定义实现
*/
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(),getName());
return info;
}
@Override
public String getName() {
return getClass().getName();
}
}
| [
"li_jian0812@126.com"
] | li_jian0812@126.com |
974db10c096ac0bfdb732542b1681773558e69ab | e26f54e0e1ddd2edc081af3dfcc534b7e03fdc29 | /week-05/day-1/src/garden/Plant.java | b56e1a4daab26712bc4b7db6d9bd9691c2af7a5d | [] | no_license | green-fox-academy/RBKoronczi | c7456bd3ad83cb6b18be112fefe7eeb36429fd8f | b7fec112d9bf43796f8f96290eed751a97bacff4 | refs/heads/master | 2020-04-02T22:20:14.940470 | 2019-01-31T14:37:37 | 2019-01-31T14:37:37 | 154,830,129 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 790 | java | package garden;
public class Plant {
String color;
double waterLevel;
double necessaryWaterLevel;
double waterEfficiency;
Plant(String color, double necessaryWaterLevel, double waterEfficiency) {
this.color = color;
this.waterLevel = 0;
this.necessaryWaterLevel = necessaryWaterLevel;
this.waterEfficiency = waterEfficiency;
}
boolean needsWater() {
return (necessaryWaterLevel > waterLevel);
}
void waterPlant(double waterAmount) {
waterLevel += waterAmount * waterEfficiency;
}
String getStatus() {
String result = "The " + color + " " + getType();
if(needsWater()) {
result += " needs water";
} else {
result += " doesn't need water";
}
return result;
}
String getType() {
return "Plant";
}
}
| [
"rbkoronczi@gmail.com"
] | rbkoronczi@gmail.com |
9ffc2dd5c501e3b52da8c2ce304f830fdd49fd0a | 3aa6ef4ec0b52c5d8a1a34ec5d99a640bfe086e3 | /Parallel Project/jdbcmedical/src/com/capgemini/medicaljdbc/dao/OrderDAO.java | becfd0a0fad8db7d112d205542aba37e6731701d | [] | no_license | jagnish1998/TY_CG_HTD_PuneMumbai_JFS_JagnishSharma | 7f37251e437119dd1381f9e34fd0ec9f61f7f0fa | 4b1f28bcdc020f840418491fedf08e0fe0974f6d | refs/heads/master | 2023-01-14T12:06:02.282243 | 2019-12-22T06:05:39 | 2019-12-22T06:05:39 | 225,846,035 | 0 | 0 | null | 2023-01-07T12:37:41 | 2019-12-04T11:00:47 | JavaScript | UTF-8 | Java | false | false | 234 | java | package com.capgemini.medicaljdbc.dao;
import java.util.List;
import com.capgemini.medicaljdbc.bean.OrderBean;
public interface OrderDAO {
public boolean placeOrder(OrderBean orderBean);
public List<OrderBean> getAll(int uid);
}
| [
"jagnish@gmail.com"
] | jagnish@gmail.com |
86e5fec8549959a19f029c683e3a18fa2aadccc1 | 1ff2a4c2b56e358e24bad26ea284e30642fc1d1e | /Date.java | bb4998ad644c861ead055aefc0ad6e55c9833977 | [] | no_license | m-Laknara/SDGP | ee48a0ff81fd2a3d85b61def8734d9db3dcc46bf | d4cfedc3bb64fdaca73c04bb9612a9d16d785e98 | refs/heads/master | 2023-03-12T02:29:00.662096 | 2021-03-01T17:14:14 | 2021-03-01T17:14:14 | 343,495,595 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 418 | java |
import java.io.Serializable;
import java.time.LocalDate;
public class Date implements Serializable {
private LocalDate date;
public Date(LocalDate date) {
this.date = date;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
@Override
public String toString() {
return "" + date;
}
}
| [
"minsadilaknara@gmail.com"
] | minsadilaknara@gmail.com |
10ac5213162717830798749782cc6d8346b573be | 5d1862806380c76fa416a022e63dd55d5aac8689 | /src/main/java/pe/edu/upeu/parcial1_jorgequispe/entity/platos.java | 2973bdcff23d94dbafafe7fd1248e9d91a2dc269 | [] | no_license | Jorge-Quispe/parcial1_jorgequispe | e7bd796ac39e6c56eafc69e682ddc2ab4b029827 | 6679b7b0bad7267202c9de4218978058ba0746ae | refs/heads/master | 2023-01-02T19:32:01.810978 | 2020-10-15T16:50:42 | 2020-10-15T16:50:42 | 304,390,710 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 864 | java | package pe.edu.upeu.parcial1_jorgequispe.entity;
public class platos {
private int idplatos;
private String nombre;
private double precio;
private int cantidad;
public platos(int idplatos, String nombre, double precio, int cantidad) {
super();
this.idplatos = idplatos;
this.nombre = nombre;
this.precio = precio;
this.cantidad = cantidad;
}
public platos() {
// TODO Auto-generated constructor stub
}
public int getIdplatos() {
return idplatos;
}
public void setIdplatos(int idplatos) {
this.idplatos = idplatos;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public double getPrecio() {
return precio;
}
public void setPrecio(double precio) {
this.precio = precio;
}
public int getCantidad() {
return cantidad;
}
public void setCantidad(int cantidad) {
this.cantidad = cantidad;
}
}
| [
"jorgequispes@upeu.edu.pe"
] | jorgequispes@upeu.edu.pe |
9e23a419bdb1f03eca0a09e2ead3877e77051498 | 8335afe80e5eac4dcf8332064cd39cebd03d1b8f | /app/src/main/java/model/CourseDetailsbyCourseId/Author.java | f56a03f02fec57a335e51d664356bbfa066fa093 | [] | no_license | VethicsGit/Loft | a55f5f017a04cf36955f21f6b0cef00c2d0bced6 | 6ebe298bfd0e1886d42d9a696733f153d29fd08d | refs/heads/master | 2020-03-28T23:21:29.219076 | 2018-09-19T14:21:56 | 2018-09-19T14:21:56 | 146,724,564 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,047 | java |
package model.CourseDetailsbyCourseId;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Author {
@SerializedName("instructor_id")
@Expose
private String instructorId;
@SerializedName("role_id")
@Expose
private String roleId;
@SerializedName("gender")
@Expose
private String gender;
@SerializedName("date_of_birth")
@Expose
private String dateOfBirth;
@SerializedName("address")
@Expose
private String address;
@SerializedName("city")
@Expose
private String city;
@SerializedName("state")
@Expose
private String state;
@SerializedName("zip")
@Expose
private String zip;
@SerializedName("country")
@Expose
private String country;
@SerializedName("email")
@Expose
private String email;
@SerializedName("profile_pic")
@Expose
private String profilePic;
@SerializedName("short_description")
@Expose
private String shortDescription;
@SerializedName("highest_qualification")
@Expose
private String highestQualification;
@SerializedName("profile_bio")
@Expose
private String profileBio;
@SerializedName("status")
@Expose
private String status;
@SerializedName("created_at")
@Expose
private String createdAt;
@SerializedName("updated_at")
@Expose
private String updatedAt;
@SerializedName("website_url")
@Expose
private String websiteUrl;
@SerializedName("google_plus_url")
@Expose
private String googlePlusUrl;
@SerializedName("twitter_url")
@Expose
private String twitterUrl;
@SerializedName("facebook_url")
@Expose
private String facebookUrl;
@SerializedName("linkedin_url")
@Expose
private String linkedinUrl;
@SerializedName("youtube_url")
@Expose
private String youtubeUrl;
@SerializedName("ip_address")
@Expose
private String ipAddress;
@SerializedName("name")
@Expose
private String name;
public String getInstructorId() {
return instructorId;
}
public void setInstructorId(String instructorId) {
this.instructorId = instructorId;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getProfilePic() {
return profilePic;
}
public void setProfilePic(String profilePic) {
this.profilePic = profilePic;
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getHighestQualification() {
return highestQualification;
}
public void setHighestQualification(String highestQualification) {
this.highestQualification = highestQualification;
}
public String getProfileBio() {
return profileBio;
}
public void setProfileBio(String profileBio) {
this.profileBio = profileBio;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public String getWebsiteUrl() {
return websiteUrl;
}
public void setWebsiteUrl(String websiteUrl) {
this.websiteUrl = websiteUrl;
}
public String getGooglePlusUrl() {
return googlePlusUrl;
}
public void setGooglePlusUrl(String googlePlusUrl) {
this.googlePlusUrl = googlePlusUrl;
}
public String getTwitterUrl() {
return twitterUrl;
}
public void setTwitterUrl(String twitterUrl) {
this.twitterUrl = twitterUrl;
}
public String getFacebookUrl() {
return facebookUrl;
}
public void setFacebookUrl(String facebookUrl) {
this.facebookUrl = facebookUrl;
}
public String getLinkedinUrl() {
return linkedinUrl;
}
public void setLinkedinUrl(String linkedinUrl) {
this.linkedinUrl = linkedinUrl;
}
public String getYoutubeUrl() {
return youtubeUrl;
}
public void setYoutubeUrl(String youtubeUrl) {
this.youtubeUrl = youtubeUrl;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| [
"41325213+VethicsGit@users.noreply.github.com"
] | 41325213+VethicsGit@users.noreply.github.com |
8f352386db325998a203264fe57a72fce74b7a1a | 4a0bfc51841a2152c002a6a6c6969c19fc268b13 | /src/test/java/com/automatedtest/sample/guruTelecomPageTest.java | e167f44e45d93ac6ef55b8e044cd75f4a6860e6c | [
"MIT"
] | permissive | rohitsitani/cucumber-java-selenium-webdriver-example | 744e0e13af71cb57906b12d9936cc69799d54248 | f8d1477b24683aa87a68066b4e5021949c6b8b3b | refs/heads/master | 2023-07-16T12:43:35.566018 | 2021-08-31T13:09:08 | 2021-08-31T13:09:08 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 652 | java | package com.automatedtest.sample;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(features = {"src/test/resources/com/automatedtest/sample/gurutelecom.feature"},
strict = false, plugin = {"pretty",
"json:target/cucumber_json_reports/guruTelecom-page.json",
"html:target/guruTelecom-page-html",
"junit:target/guruTelecom-page-html/guruTelecom-page.xml"},
glue = {"com.automatedtest.sample.infrastructure.driver",
"com.automatedtest.sample.gurutelecom"})
public class guruTelecomPageTest {
}
| [
"garima.sanghai@gmail.com"
] | garima.sanghai@gmail.com |
322aeab4a727dec983bdd7450a6a35c3c33d0899 | 3de32c0453720fed7933f9937745bbdae04ce9f9 | /huffmancoder/src/main/java/com/sulu/huffmancoder/CharCounter.java | 247ac90f04a7444792700a2807f3701f93286827 | [] | no_license | lusu8892/data_structure | 170cbd93d016d58eeacf2f4e7d5f9eecc8fad95c | e9fdbea8a6311d7b099c2dc88a0cf137c2d849f5 | refs/heads/master | 2021-01-22T04:49:58.551012 | 2017-09-07T20:54:03 | 2017-09-07T20:54:03 | 81,589,641 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 16,552 | java | /**
* Created by sulu on 3/9/17.
* Class CharCounter computes the count of each char in from a char array or file and stores
* the result in a data structure.
*/
package com.sulu.huffmancoder;
import org.apache.commons.lang3.ArrayUtils;
import java.io.*;
import java.util.*;
public class CharCounter {
public char [] getCharPrimArray () { return charPrimArray;}
private char [] charPrimArray;
// public Character[] getCharObjArray() {
// return charObjArray;
// }
// private Character[] charObjArray;
// public LinkedList<Character> getCountedLLChar() {
// return countedLLChar;
// }
// private LinkedList<Character> countedLLChar = new LinkedList<>();
// public LinkedList<Integer> getCountLLInt() {
// return countLLInt;
// }
// private LinkedList<Integer> countLLInt = new LinkedList<>();
// public LinkedList<CharCount> getCountedCharAndCount() {
// return countedCharAndCount;
// }
private LinkedList<CharCount> countedCharAndCount = new LinkedList<>();
/**
* A constructor with a Character array argument indicates that the counts are to be computed from that array.
* @param inputCharPrimArray
*/
public CharCounter (char [] inputCharPrimArray) {
this.charPrimArray = inputCharPrimArray;
// this.charObjArray = ArrayUtils.toObject(inputCharPrimArray);
}
/**
* A constructor with a String argument specifies the name of a file that the counts are to be computed from.
* @param pathName
*/
public CharCounter (String pathName) throws java.io.IOException {
this.charPrimArray = ArrayUtils.toPrimitive( readFileAsChar( pathName ) );
// this.charObjArray = readFileAsChar( pathName );
}
/**
* Read file character-by-character
* @param pathName
* @return
*/
private static Character[] readFileAsChar (String pathName) {
Character [] charObjArray = null;
try {
File fileDir = new File(pathName);
BufferedReader in = new BufferedReader(
new InputStreamReader(
new FileInputStream(fileDir), "UTF8"));
LinkedList<Character> LLChar = new LinkedList<>();
int num = 0;
while ( (num = in.read()) != -1 ) {
LLChar.addLast((char)num);
}
in.close();
charObjArray = LLChar.toArray(new Character[LLChar.size()]);
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
// return charObjArray;
}
catch (IOException e)
{
System.out.println(e.getMessage());
// return charObjArray;
}
catch (Exception e)
{
System.out.println(e.getMessage());
// return charObjArray;
}
return charObjArray;
//
// BufferedReader br = null;
//
// try {
// br = new BufferedReader( new FileReader(pathName) );
// int num = 0;
// while((num=br.read()) != -1)
// {
// LLChar.addFirst((char)num);
// }
//
// return LLChar.toArray(new Character[LLChar.size()]);
//
// }
// catch (IOException ioe)
// {
// ioe.printStackTrace();
// return null;
// }
//
// File file = new File(pathName);
//
// try {
// FileInputStream fis = new FileInputStream(file);
// while (fis.available() > 0 ) {
// LLChar.addFirst((char)fis.read());
// }
// return LLChar.toArray(new Character[LLChar.size()]);
//
// } catch (IOException e) {
// e.printStackTrace();
// return null;
// }
}
// public int [] getCount () {
// return getCount (charPrimArray);
// }
public void countChar ( ) {
countCharSub( charPrimArray );
}
/**
* Private helper method
* @param charAr
* @return
*/
private void countCharSub ( char [] charAr ) {
Character [] charObjAr = ArrayUtils.toObject( charAr );
Arrays.sort(charObjAr);
LinkedList<Character> LLChar = new LinkedList(Arrays.asList(charObjAr)); // construct a LLChar by sorted Array
// create a linkedlist to store number of occurrences of the corresponding byte
// LinkedList<Integer> LLCount = new LinkedList<>();
while ( !LLChar.isEmpty() ) {
Character chObj = LLChar.getFirst();
int count = numOccur(LLChar, chObj);
if ( count != 0 ) {
countedCharAndCount.addLast( new CharCount( chObj, count) );
// LLCount.addLast( count );
}
}
// return ArrayUtils.toPrimitive(LLCount.toArray(new Integer[0]));
}
/**
* returns an integer array that contains the number of occurrences of the corresponding
* char in the array char. The order of the array is specified by the current order defined below.
* @return
*/
public int [] getCount ( ) {
LinkedList<Integer> countedLL = new LinkedList<>();
ListIterator<CharCount> listIt = countedCharAndCount.listIterator();
while ( listIt.hasNext() ) {
countedLL.addLast( listIt.next().count );
}
int [] countAr = ArrayUtils.toPrimitive( countedLL.toArray(new Integer[0]) );
return countAr;
}
/**
* returns an integer value that contains the number of occurrences of char ch.
* @param ch
* @return
*/
public int getCount ( char ch ) {
int count = 0;
ListIterator<CharCount> listIt = countedCharAndCount.listIterator();
while ( listIt.hasNext() ) {
CharCount charCount = listIt.next();
if ( ch == charCount.ch ) {
count = charCount.count;
break;
}
}
return count;
}
/**
* Returns number of occurrence of certain Char type argument
* @param LLChar input source of linkedList the number of occurrence from which is counted
* @param ch the argument wanted to count
* @return
*/
private int numOccur (LinkedList<Character> LLChar, Character ch) {
int count = 0;
// if ( LLChar.contains(ch) && !countedLLChar.contains(ch) ) {
//
// int startIndex = LLChar.indexOf( ch );
//
// ListIterator listIterator = LLChar.listIterator( startIndex );
// while ( listIterator.hasNext() ) {
// if (ch == listIterator.next()) {
// count++;
// listIterator.remove(); // once found one remove it from linkedlist
// }
// else {
// break; // jump out from loop
// }
// }
//
// countedLLChar.addLast( ch ); // append ch to countedLLChar linkedlist
// countLLInt.addLast( count ); // append count to countLL linkedlist
//
// // append ch and its corresponding count to countedCharAndCount linkedlist
// countedCharAndCount.addLast( new CharCount( ch, count) );
// } else if ( !LLChar.contains(ch) ) {
// System.out.println ("The input source does NOT contain " + ch);
// } else if ( countedLLChar.contains(ch) ) {
// count = getCountFromCharAndCountLL( ch );
// System.out.println ("The char: " + ch +
// " has been counted and the count is " + count);
// }
if ( LLChar.contains( ch ) ) {
int startIndex = LLChar.indexOf( ch );
ListIterator listIterator = LLChar.listIterator( startIndex );
while ( listIterator.hasNext() ) {
if (ch == listIterator.next()) {
count++;
listIterator.remove(); // once found one remove it from linkedlist
}
else {
break; // jump out from loop
}
}
// append ch and its corresponding count to countedCharAndCount linkedlist
// countedCharAndCount.addLast( new CharCount( ch, count) );
// countedLLChar.addLast( ch ); // append ch to countedLLChar linkedlist
// countLLInt.addLast( count ); // append count to countLL linkedlist
} else {
System.out.println ("The input source does NOT contain " + ch);
}
return count; // if no such element in LLChar then count is 0.
}
// private Integer getCountFromCharAndCountLL (char chInQ) {
//
// Integer count = null;
// if ( countedCharAndCount.isEmpty() ) {
// count = null;
// } else {
// Iterator<CharCount> iterator = countedCharAndCount.iterator();
// while ( iterator.hasNext() ) {
// CharCount oneChCount = iterator.next();
// if ( oneChCount.ch == chInQ ) {
// count = oneChCount.count;
// break;
// }
// }
// }
// return count;
// }
/**
* Returns a char array of the bytes that have been counted, i.e. those with non-zero counts.
* @return
*/
public char[] getElements() {
// LinkedList<Character> LLChar = getCountedLLChar();
LinkedList<Character> countedLLChar = new LinkedList<>();
ListIterator<CharCount> listIt = countedCharAndCount.listIterator();
while ( listIt.hasNext() ) {
countedLLChar.addLast( listIt.next().ch );
}
char [] countedCharPrimArray = ArrayUtils.toPrimitive( countedLLChar.toArray(new Character[0]) );
return countedCharPrimArray;
}
/**
* Defines the order for the current object, which controls the ordering of the arrays returned by toString.
* If order equals char (the default) the ordering is in terms of increasing char value.
* If order equals countInc or countDec the order is in terms of increasing or decreasing count, respectively.
* For counts that are equal, the order should be in increasing char order.
* If order is not one of char, countInc, or countDec throw an exception.
* @throws Exception
*/
public void setOrder() throws Exception {
setOrder("char");
}
/**
* The default setOrder method which is overloading method setOrder( String order ),
* by invoking the method with string "byte" as default argument value.
* @throws Exception
*/
public void setOrder (String order) throws IllegalArgumentException{
if (order.equals("char")) {
Collections.sort(countedCharAndCount, new countChar());
} else if (order.equals("countInc")) {
Collections.sort(countedCharAndCount, new countInc());
return;
} else if (order.equals("countDec")) {
Collections.sort(countedCharAndCount, new countDec());
return;
} else {
throw new IllegalArgumentException();
}
}
// private void sortDefault () {
// countedLLChar.clear();
// countLLInt.clear();
// ListIterator<CharCount> liCharCount = countedCharAndCount.listIterator();
//
// while (liCharCount.hasNext()) {
// CharCount charCount = liCharCount.next();
// countedLLChar.addLast(charCount.ch);
// countLLInt.addLast(charCount.count);
// }
// return;
// }
//
// private void sortCountInc () {
// Integer [] countArray = countLLInt.toArray(new Integer[0]);
//
// Arrays.sort(countArray); // sort countArray increasingly
// countLLInt = new LinkedList(Arrays.asList(countArray));
//
// countedLLChar.clear();
// for (Integer count : countArray) {
// ListIterator<CharCount> liCharCount = countedCharAndCount.listIterator();
// while (liCharCount.hasNext()) {
// CharCount charCount = liCharCount.next();
// if (count.equals(charCount.count)) {
// if (!countedLLChar.contains(charCount.ch)) {
// countedLLChar.addLast(charCount.ch);
// break;
// }
// }
// }
// }
//
// return;
// }
//
// private void sortCountDec () {
// sortCountInc();
//
// Integer [] countArray = countLLInt.toArray(new Integer[0]);
// Character [] charArray = countedLLChar.toArray(new Character[0]);
//
// reverseArray(countArray, 0, countArray.length - 1);
// reverseArray(charArray, 0, charArray.length - 1);
//
// countLLInt = new LinkedList(Arrays.asList(countArray));
// countedLLChar = new LinkedList(Arrays.asList(charArray));
//
// return;
// }
//
// private <AnyType> void reverseArray ( AnyType [] array, int left, int right) {
// if ( left >= right ) {
// return; // base case
// } else {
//
// // swap the two ends: array[left] and array[right]
// AnyType temp = array[left];
// array[left] = array[right];
// array[right] = temp;
//
// // reverse the "middle"
// reverseArray( array, left + 1, right - 1);
// }
// }
/**
* Returns a String containing the current bytes and counts in the current order.
* It should have the format byte:count, separated by spaces, with no leading or trailing spaces.
* The byte should be formatted as a (signed) integer.
* For example 32:3 44:1 63:1 72:1 97:1 101:2 104:1 108:2 111:3 114:1 117:1 119:1 121:1
*
* Note that in Java bytes are signed (and there is no unsigned byte),
* so that the implicit integer range of a byte is [−128, 127].
* When you convert a byte to the integer, it should be negative for byte values 0x80 to 0xFF.
*
* @return
*/
public String toString () {
// String charCountInfo = null;
//
// if ( countedLLChar.size() == countLLInt.size() ) {
// ListIterator<Character> liCh = countedLLChar.listIterator();
// ListIterator<Integer> liInt = countLLInt.listIterator();
//
// charCountInfo = new String();
// while (liCh.hasNext() && liInt.hasNext()) {
// char ch = liCh.next();
// int count = liInt.next();
// String countInfo = new String(ch + ":" + count + " ");
// charCountInfo = charCountInfo.concat(countInfo);
// }
// }
// return charCountInfo;
ListIterator<CharCount> listIterator = countedCharAndCount.listIterator();
String charCountInfo = new String();
while ( listIterator.hasNext() ) {
charCountInfo = charCountInfo.concat(listIterator.next().countInfo );
charCountInfo = charCountInfo.concat(" ");
}
return charCountInfo;
}
private static class CharCount {
public CharCount (Character ch, Integer count) {
this.ch = ch;
this.count = count;
this.countInfo = new String (ch + ":" + count );
}
public CharCount () {
this (null, null);
}
public Character ch;
public Integer count;
public String countInfo;
}
private class countChar implements Comparator<CharCount> {
@Override
public int compare(CharCount o1, CharCount o2) {
return o1.ch.compareTo(o2.ch);
}
}
private class countInc implements Comparator<CharCount> {
@Override
public int compare(CharCount o1, CharCount o2) {
// if result > 0 o1.count is bigger than o2.count
// if result < 0 o1.count is less than o2.count
// if result = 0 o1.count is equal to o2.count
int result = o1.count.compareTo(o2.count);
if ( result == 0 ) {
return o1.ch.compareTo(o2.ch);
}
return result;
}
}
private class countDec implements Comparator<CharCount> {
@Override
public int compare(CharCount o1, CharCount o2) {
int result = o2.count.compareTo(o1.count);
if ( result == 0 ) {
return o2.ch.compareTo(o1.ch);
}
return result;
}
}
}
| [
"sxl924@case.edu"
] | sxl924@case.edu |
87fe406cde7f842eb0754a54ce7fb8894ccd287d | cfbb949fb5b1be357d1c7ec903ecb827fb1b82e7 | /src/main/java/id/gate/root/gaterootbe/service/impl/FileStorageServiceImpl.java | 86aa094a2b1e60477ba8f5a8c2302310978a8655 | [] | no_license | ikhsanhikari/gateandway-be | 10abb1a15b5ebe26e00a0e9aa3908356d23f041b | 05235036fc1f2e936e345af1deb640e7b4ad9ffe | refs/heads/master | 2020-09-25T12:50:53.339770 | 2019-12-05T03:40:05 | 2019-12-05T03:40:05 | 226,008,185 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,818 | java | package id.gate.root.gaterootbe.service.impl;
import id.gate.root.gaterootbe.exception.FileStorageException;
import id.gate.root.gaterootbe.exception.MyFileNotFoundException;
import id.gate.root.gaterootbe.property.FileStorageProperties;
import id.gate.root.gaterootbe.service.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
@Service
public class FileStorageServiceImpl implements FileStorageService {
private final Path fileStorageLocation;
@Autowired
public FileStorageServiceImpl(FileStorageProperties fileStorageProperties) {
this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir())
.toAbsolutePath().normalize();
try {
Files.createDirectories(this.fileStorageLocation);
} catch (Exception ex) {
throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex);
}
}
public String storeFile(MultipartFile file) {
// Normalize file name
String fileName = StringUtils.cleanPath(file.getOriginalFilename());
try {
// Check if the file's name contains invalid characters
if (fileName.contains("..")) {
throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
}
// Copy file to the target location (Replacing existing file with the same name)
Path targetLocation = this.fileStorageLocation.resolve(fileName);
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return fileName;
} catch (IOException ex) {
throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
}
}
public Resource loadFileAsResource(String fileName) {
try {
Path filePath = this.fileStorageLocation.resolve(fileName).normalize();
Resource resource = new UrlResource(filePath.toUri());
if (resource.exists()) {
return resource;
} else {
throw new MyFileNotFoundException("File not found " + fileName);
}
} catch (MalformedURLException ex) {
throw new MyFileNotFoundException("File not found " + fileName, ex);
}
}
}
| [
"mspenterprise@MacBook-Pro-MSP-3.local"
] | mspenterprise@MacBook-Pro-MSP-3.local |
9993010de93fd0e1733d6c71f70a3650f93e8c59 | 2590cdf71496badf9f21d60435711b5027b7369b | /Spark2/src/main/java/com/sapient/HealthCareUsingSparkSQL.java | 6c98938af79e77c2367e74431fd2fc21dd986b8b | [] | no_license | rsamrat073/Hadoop-Training | a2af455fbc8f0ba4ee01ade4b7c3f19622955b75 | 740ac4ccfa14a8a54af7ae19d2f04fd1b2a7ee9a | refs/heads/master | 2021-09-05T21:47:25.688367 | 2018-01-31T07:12:49 | 2018-01-31T07:12:49 | 117,648,402 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,549 | java | package com.sapient;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import org.apache.spark.api.java.function.MapFunction;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import com.sapient.JavaSQLDataSourceExample.Cube;
import com.sapient.JavaSQLDataSourceExample.Square;
public class HealthCareUsingSparkSQL {
public static void main(String[] args) {
//winutils.exe chmod 777 D:\tmp\hive
System.setProperty("hadoop.home.dir", "C:\\Users\\TEMP\\Desktop\\SparkWS\\");
SparkSession spark = SparkSession.builder().master("local[*]").appName("Java Spark SQL data sources example")
.config("spark.sql.warehouse.dir", new File("spark-warehouse").getAbsolutePath()).enableHiveSupport()
.getOrCreate();
runBasicDataSourceExample(spark);
spark.stop();
}
private static void runBasicDataSourceExample(SparkSession spark) {
Dataset<Row> usersDF = spark.read().csv("D:\\Hadoop Materials\\CTS\\HiveCodes\\HIVE\\*.csv");
System.out.println(usersDF.count());
usersDF = usersDF.toDF("id", "un", "dob", "cont1", "mailId", "cont2", "gender", "disease", "weight");
usersDF.write().partitionBy("gender","disease").bucketBy(5, "mailId").format("orc")
.saveAsTable("HEALTH_CARE1");
spark.sql("REFRESH TABLE HEALTH_CARE");
usersDF = spark.sql("select * from HEALTH_CARE1 limit 30 ");
usersDF.show();
}
} | [
"sroy28@BLRVIKR07.sapient.com"
] | sroy28@BLRVIKR07.sapient.com |
70c84a8c0a26554ef3733d26f93d4e2edc0b3492 | 5dfafe256376318c628f7cc7c3df96b919352897 | /algorithms/src/main/java/com/wildbeeslabs/jentle/algorithms/sort/Timsort.java | 345b5e44228fb1774a390dca09e5e1b98990f071 | [
"MIT"
] | permissive | AlexRogalskiy/jentle | e5cf9ea30ee4896cc275edae2d4ab5f2502ed68b | 5d6f9feee02902cb0a330c7359c0c268feed2015 | refs/heads/master | 2022-12-21T15:42:20.627784 | 2020-06-27T07:54:11 | 2020-06-27T07:54:11 | 99,516,907 | 0 | 0 | MIT | 2022-12-14T20:39:26 | 2017-08-06T22:30:41 | Java | UTF-8 | Java | false | false | 34,653 | java | package com.wildbeeslabs.jentle.algorithms.sort;
/**
* A stable, adaptive, iterative mergesort that requires far fewer than
* n lg(n) comparisons when running on partially sorted arrays, while
* offering performance comparable to a traditional mergesort when run
* on random arrays. Like all proper mergesorts, this sort is stable and
* runs O(n log n) time (worst case). In the worst case, this sort requires
* temporary storage space for n/2 object references; in the best case,
* it requires only a small constant amount of space.
* <p>
* This implementation was adapted from Tim Peters's list sort for
* Python, which is described in detail here:
* <p>
* http://svn.python.org/projects/python/trunk/Objects/listsort.txt
* <p>
* Tim's C code may be found here:
* <p>
* http://svn.python.org/projects/python/trunk/Objects/listobject.c
* <p>
* The underlying techniques are described in this paper (and may have
* even earlier origins):
* <p>
* "Optimistic Sorting and Information Theoretic Complexity"
* Peter McIlroy
* SODA (Fourth Annual ACM-SIAM Symposium on Discrete Algorithms),
* pp 467-474, Austin, Texas, 25-27 January 1993.
* <p>
* While the API to this class consists solely of static methods, it is
* (privately) instantiable; a TimSort instance holds the state of an ongoing
* sort, assuming the input array is large enough to warrant the full-blown
* TimSort. Small arrays are sorted in place, using a binary insertion sort.
*
* @author Josh Bloch
*/
public class Timsort {
public static final Sorter INSTANCE = new Sorter() {
@Override
public void sort(final int[] A, final int left, final int right) {
Timsort.sort(A, left, right + 1);
}
@Override
public String toString() {
return "Timsort-JDK8";
}
};
/**
* This is the minimum sized sequence that will be merged. Shorter
* sequences will be lengthened by calling binarySort. If the entire
* array is less than this length, no merges will be performed.
* <p>
* This constant should be a power of two. It was 64 in Tim Peter's C
* implementation, but 32 was empirically determined to work better in
* this implementation. In the unlikely event that you set this constant
* to be a number that's not a power of two, you'll need to change the
* {@link #minRunLength} computation.
* <p>
* If you decrease this constant, you must change the stackLen
* computation in the TimSort constructor, or you risk an
* ArrayOutOfBounds exception. See listsort.txt for a discussion
* of the minimum stack length required as a function of the length
* of the array being sorted and the minimum merge sequence length.
*/
private static final int MIN_MERGE = 32;
/**
* The array being sorted.
*/
private final int[] a;
/**
* When we get into galloping mode, we stay there until both runs win less
* often than MIN_GALLOP consecutive times.
*/
private static final int MIN_GALLOP = 7;
/**
* This controls when we get *into* galloping mode. It is initialized
* to MIN_GALLOP. The mergeLo and mergeHi methods nudge it higher for
* random data, and lower for highly structured data.
*/
private int minGallop = MIN_GALLOP;
/**
* Maximum initial size of tmp array, which is used for merging. The array
* can grow to accommodate demand.
* <p>
* Unlike Tim's original C version, we do not allocate this much storage
* when sorting smaller arrays. This change was required for performance.
*/
private static final int INITIAL_TMP_STORAGE_LENGTH = 256;
/**
* Temp storage for merges. A workspace array may optionally be
* provided in constructor, and if so will be used as long as it
* is big enough.
*/
private int[] tmp;
private int tmpBase; // base of tmp array slice
private int tmpLen; // length of tmp array slice
/**
* A stack of pending runs yet to be merged. Run i starts at
* address base[i] and extends for len[i] elements. It's always
* true (so long as the indices are in bounds) that:
* <p>
* runBase[i] + runLen[i] == runBase[i + 1]
* <p>
* so we could cut the storage for this, but it's a minor amount,
* and keeping all the info explicit simplifies the code.
*/
private int stackSize = 0; // Number of pending runs on stack
private final int[] runBase;
private final int[] runLen;
/**
* Creates a TimSort instance to maintain the state of an ongoing sort.
*
* @param a the array to be sorted
* @param work a workspace array (slice)
* @param workBase origin of usable space in work array
* @param workLen usable size of work array
*/
private Timsort(int[] a, int[] work, int workBase, int workLen) {
this.a = a;
// Allocate temp storage (which may be increased later if necessary)
int len = a.length;
int tlen = (len < 2 * INITIAL_TMP_STORAGE_LENGTH) ?
len >>> 1 : INITIAL_TMP_STORAGE_LENGTH;
if (work == null || workLen < tlen || workBase + tlen > work.length) {
tmp = new int[tlen];
tmpBase = 0;
tmpLen = tlen;
} else {
tmp = work;
tmpBase = workBase;
tmpLen = workLen;
}
/*
* Allocate runs-to-be-merged stack (which cannot be expanded). The
* stack length requirements are described in listsort.txt. The C
* version always uses the same stack length (85), but this was
* measured to be too expensive when sorting "mid-sized" arrays (e.g.,
* 100 elements) in Java. Therefore, we use smaller (but sufficiently
* large) stack lengths for smaller arrays. The "magic numbers" in the
* computation below must be changed if MIN_MERGE is decreased. See
* the MIN_MERGE declaration above for more information.
* The maximum value of 49 allows for an array up to length
* Integer.MAX_VALUE-4, if array is filled by the worst case stack size
* increasing scenario. More explanations are given in section 4 of:
* http://envisage-project.eu/wp-content/uploads/2015/02/sorting.pdf
*/
int stackLen = (len < 120 ? 5 :
len < 1542 ? 10 :
len < 119151 ? 24 : 49);
runBase = new int[stackLen];
runLen = new int[stackLen];
}
/*
* The next method (package private and static) constitutes the
* entire API of this class.
*/
/**
* Sorts the given range, using the given workspace array slice
* for temp storage when possible. This method is designed to be
* invoked from public methods (in class Arrays) after performing
* any necessary array bounds checks and expanding parameters into
* the required forms.
*
* @param a the array to be sorted
* @param lo the index of the first element, inclusive, to be sorted
* @param hi the index of the last element, exclusive, to be sorted
* @since 1.8
*/
public static void sort(int[] a, int lo, int hi) {
assert a != null && lo >= 0 && lo <= hi && hi <= a.length;
int nRemaining = hi - lo;
if (nRemaining < 2)
return; // Arrays of size 0 and 1 are always sorted
// If array is small, do a "mini-TimSort" with no merges
if (nRemaining < MIN_MERGE) {
int initRunLen = countRunAndMakeAscending(a, lo, hi);
binarySort(a, lo, hi, lo + initRunLen);
return;
}
/**
* March over the array once, left to right, finding natural runs,
* extending short natural runs to minRun elements, and merging runs
* to maintain stack invariant.
*/
Timsort ts = new Timsort(a, null, 0, 0);
int minRun = minRunLength(nRemaining);
do {
// Identify next run
int runLen = countRunAndMakeAscending(a, lo, hi);
// If run is short, extend to min(minRun, nRemaining)
if (runLen < minRun) {
int force = nRemaining <= minRun ? nRemaining : minRun;
binarySort(a, lo, lo + force, lo + runLen);
runLen = force;
}
// Push run onto pending-run stack, and maybe merge
ts.pushRun(lo, runLen);
ts.mergeCollapse();
// Advance to find next run
lo += runLen;
nRemaining -= runLen;
} while (nRemaining != 0);
// Merge all remaining runs to complete sort
assert lo == hi;
ts.mergeForceCollapse();
assert ts.stackSize == 1;
}
/**
* Sorts the specified portion of the specified array using a binary
* insertion sort. This is the best method for sorting small numbers
* of elements. It requires O(n log n) compares, but O(n^2) data
* movement (worst case).
* <p>
* If the initial part of the specified range is already sorted,
* this method can take advantage of it: the method assumes that the
* elements from index {@code lo}, inclusive, to {@code start},
* exclusive are already sorted.
*
* @param a the array in which a range is to be sorted
* @param lo the index of the first element in the range to be sorted
* @param hi the index after the last element in the range to be sorted
* @param start the index of the first element in the range that is
* not already known to be sorted ({@code lo <= start <= hi})
*/
@SuppressWarnings("fallthrough")
private static void binarySort(int[] a, int lo, int hi, int start) {
assert lo <= start && start <= hi;
if (start == lo)
start++;
for (; start < hi; start++) {
int pivot = a[start];
// Set left (and right) to the index where a[start] (pivot) belongs
int left = lo;
int right = start;
assert left <= right;
/*
* Invariants:
* pivot >= all in [lo, left).
* pivot < all in [right, start).
*/
while (left < right) {
int mid = (left + right) >>> 1;
if (pivot < a[mid])
right = mid;
else
left = mid + 1;
}
assert left == right;
/*
* The invariants still hold: pivot >= all in [lo, left) and
* pivot < all in [left, start), so pivot belongs at left. Note
* that if there are elements equal to pivot, left points to the
* first slot after them -- that's why this sort is stable.
* Slide elements over to make room for pivot.
*/
int n = start - left; // The number of elements to move
// Switch is just an optimization for arraycopy in default case
switch (n) {
case 2:
a[left + 2] = a[left + 1];
case 1:
a[left + 1] = a[left];
break;
default:
System.arraycopy(a, left, a, left + 1, n);
}
a[left] = pivot;
}
}
/**
* Returns the length of the run beginning at the specified position in
* the specified array and reverses the run if it is descending (ensuring
* that the run will always be ascending when the method returns).
* <p>
* A run is the longest ascending sequence with:
* <p>
* a[lo] <= a[lo + 1] <= a[lo + 2] <= ...
* <p>
* or the longest descending sequence with:
* <p>
* a[lo] > a[lo + 1] > a[lo + 2] > ...
* <p>
* For its intended use in a stable mergesort, the strictness of the
* definition of "descending" is needed so that the call can safely
* reverse a descending sequence without violating stability.
*
* @param a the array in which a run is to be counted and possibly reversed
* @param lo index of the first element in the run
* @param hi index after the last element that may be contained in the run.
* It is required that {@code lo < hi}.
* @return the length of the run beginning at the specified position in
* the specified array
*/
private static int countRunAndMakeAscending(int[] a, int lo, int hi) {
assert lo < hi;
int runHi = lo + 1;
if (runHi == hi)
return 1;
// Find end of run, and reverse range if descending
if (a[runHi++] < a[lo]) { // Descending
while (runHi < hi && a[runHi] < a[runHi - 1])
runHi++;
reverseRange(a, lo, runHi);
} else { // Ascending
while (runHi < hi && a[runHi] >= a[runHi - 1])
runHi++;
}
return runHi - lo;
}
/**
* Reverse the specified range of the specified array.
*
* @param a the array in which a range is to be reversed
* @param lo the index of the first element in the range to be reversed
* @param hi the index after the last element in the range to be reversed
*/
private static void reverseRange(int[] a, int lo, int hi) {
hi--;
while (lo < hi) {
int t = a[lo];
a[lo++] = a[hi];
a[hi--] = t;
}
}
/**
* Returns the minimum acceptable run length for an array of the specified
* length. Natural runs shorter than this will be extended with
* {@link #binarySort}.
* <p>
* Roughly speaking, the computation is:
* <p>
* If n < MIN_MERGE, return n (it's too small to bother with fancy stuff).
* Else if n is an exact power of 2, return MIN_MERGE/2.
* Else return an int k, MIN_MERGE/2 <= k <= MIN_MERGE, such that n/k
* is close to, but strictly less than, an exact power of 2.
* <p>
* For the rationale, see listsort.txt.
*
* @param n the length of the array to be sorted
* @return the length of the minimum run to be merged
*/
private static int minRunLength(int n) {
assert n >= 0;
int r = 0; // Becomes 1 if any 1 bits are shifted off
while (n >= MIN_MERGE) {
r |= (n & 1);
n >>= 1;
}
return n + r;
}
/**
* Pushes the specified run onto the pending-run stack.
*
* @param runBase index of the first element in the run
* @param runLen the number of elements in the run
*/
private void pushRun(int runBase, int runLen) {
this.runBase[stackSize] = runBase;
this.runLen[stackSize] = runLen;
stackSize++;
}
/**
* Examines the stack of runs waiting to be merged and merges adjacent runs
* until the stack invariants are reestablished:
* <p>
* 1. runLen[i - 3] > runLen[i - 2] + runLen[i - 1]
* 2. runLen[i - 2] > runLen[i - 1]
* <p>
* This method is called each time a new run is pushed onto the stack,
* so the invariants are guaranteed to hold for i < stackSize upon
* entry to the method.
*/
private void mergeCollapse() {
while (stackSize > 1) {
int n = stackSize - 2;
if (n > 0 && runLen[n - 1] <= runLen[n] + runLen[n + 1]) {
if (runLen[n - 1] < runLen[n + 1])
n--;
mergeAt(n);
} else if (runLen[n] <= runLen[n + 1]) {
mergeAt(n);
} else {
break; // Invariant is established
}
}
}
/**
* Merges all runs on the stack until only one remains. This method is
* called once, to complete the sort.
*/
private void mergeForceCollapse() {
while (stackSize > 1) {
int n = stackSize - 2;
if (n > 0 && runLen[n - 1] < runLen[n + 1])
n--;
mergeAt(n);
}
}
/**
* Merges the two runs at stack indices i and i+1. Run i must be
* the penultimate or antepenultimate run on the stack. In other words,
* i must be equal to stackSize-2 or stackSize-3.
*
* @param i stack index of the first of the two runs to merge
*/
private void mergeAt(int i) {
assert stackSize >= 2;
assert i >= 0;
assert i == stackSize - 2 || i == stackSize - 3;
int base1 = runBase[i];
int len1 = runLen[i];
int base2 = runBase[i + 1];
int len2 = runLen[i + 1];
assert len1 > 0 && len2 > 0;
assert base1 + len1 == base2;
/*
* Record the length of the combined runs; if i is the 3rd-last
* run now, also slide over the last run (which isn't involved
* in this merge). The current run (i+1) goes away in any case.
*/
runLen[i] = len1 + len2;
if (i == stackSize - 3) {
runBase[i + 1] = runBase[i + 2];
runLen[i + 1] = runLen[i + 2];
}
stackSize--;
/*
* Find where the first element of run2 goes in run1. Prior elements
* in run1 can be ignored (because they're already in place).
*/
int k = gallopRight(a[base2], a, base1, len1, 0);
assert k >= 0;
base1 += k;
len1 -= k;
if (len1 == 0)
return;
/*
* Find where the last element of run1 goes in run2. Subsequent elements
* in run2 can be ignored (because they're already in place).
*/
len2 = gallopLeft(a[base1 + len1 - 1], a, base2, len2, len2 - 1);
assert len2 >= 0;
if (len2 == 0)
return;
// Merge remaining runs, using tmp array with min(len1, len2) elements
if (len1 <= len2)
mergeLo(base1, len1, base2, len2);
else
mergeHi(base1, len1, base2, len2);
}
/**
* Locates the position at which to insert the specified key into the
* specified sorted range; if the range contains an element equal to key,
* returns the index of the leftmost equal element.
*
* @param key the key whose insertion point to search for
* @param a the array in which to search
* @param base the index of the first element in the range
* @param len the length of the range; must be > 0
* @param hint the index at which to begin the search, 0 <= hint < n.
* The closer hint is to the result, the faster this method will run.
* @return the int k, 0 <= k <= n such that a[b + k - 1] < key <= a[b + k],
* pretending that a[b - 1] is minus infinity and a[b + n] is infinity.
* In other words, key belongs at index b + k; or in other words,
* the first k elements of a should precede key, and the last n - k
* should follow it.
*/
private static int gallopLeft(int key, int[] a, int base, int len, int hint) {
assert len > 0 && hint >= 0 && hint < len;
int lastOfs = 0;
int ofs = 1;
if (key > a[base + hint]) {
// Gallop right until a[base+hint+lastOfs] < key <= a[base+hint+ofs]
int maxOfs = len - hint;
while (ofs < maxOfs && key > a[base + hint + ofs]) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
if (ofs > maxOfs)
ofs = maxOfs;
// Make offsets relative to base
lastOfs += hint;
ofs += hint;
} else { // key <= a[base + hint]
// Gallop left until a[base+hint-ofs] < key <= a[base+hint-lastOfs]
final int maxOfs = hint + 1;
while (ofs < maxOfs && key <= a[base + hint - ofs]) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
if (ofs > maxOfs)
ofs = maxOfs;
// Make offsets relative to base
int tmp = lastOfs;
lastOfs = hint - ofs;
ofs = hint - tmp;
}
assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
/*
* Now a[base+lastOfs] < key <= a[base+ofs], so key belongs somewhere
* to the right of lastOfs but no farther right than ofs. Do a binary
* search, with invariant a[base + lastOfs - 1] < key <= a[base + ofs].
*/
lastOfs++;
while (lastOfs < ofs) {
int m = lastOfs + ((ofs - lastOfs) >>> 1);
if (key > a[base + m])
lastOfs = m + 1; // a[base + m] < key
else
ofs = m; // key <= a[base + m]
}
assert lastOfs == ofs; // so a[base + ofs - 1] < key <= a[base + ofs]
return ofs;
}
/**
* Like gallopLeft, except that if the range contains an element equal to
* key, gallopRight returns the index after the rightmost equal element.
*
* @param key the key whose insertion point to search for
* @param a the array in which to search
* @param base the index of the first element in the range
* @param len the length of the range; must be > 0
* @param hint the index at which to begin the search, 0 <= hint < n.
* The closer hint is to the result, the faster this method will run.
* @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k]
*/
private static int gallopRight(int key, int[] a, int base, int len, int hint) {
assert len > 0 && hint >= 0 && hint < len;
int ofs = 1;
int lastOfs = 0;
if (key < a[base + hint]) {
// Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs]
int maxOfs = hint + 1;
while (ofs < maxOfs && key < a[base + hint - ofs]) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
if (ofs > maxOfs)
ofs = maxOfs;
// Make offsets relative to b
int tmp = lastOfs;
lastOfs = hint - ofs;
ofs = hint - tmp;
} else { // a[b + hint] <= key
// Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs]
int maxOfs = len - hint;
while (ofs < maxOfs && key >= a[base + hint + ofs]) {
lastOfs = ofs;
ofs = (ofs << 1) + 1;
if (ofs <= 0) // int overflow
ofs = maxOfs;
}
if (ofs > maxOfs)
ofs = maxOfs;
// Make offsets relative to b
lastOfs += hint;
ofs += hint;
}
assert -1 <= lastOfs && lastOfs < ofs && ofs <= len;
/*
* Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to
* the right of lastOfs but no farther right than ofs. Do a binary
* search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs].
*/
lastOfs++;
while (lastOfs < ofs) {
int m = lastOfs + ((ofs - lastOfs) >>> 1);
if (key < a[base + m])
ofs = m; // key < a[b + m]
else
lastOfs = m + 1; // a[b + m] <= key
}
assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs]
return ofs;
}
/**
* Merges two adjacent runs in place, in a stable fashion. The first
* element of the first run must be greater than the first element of the
* second run (a[base1] > a[base2]), and the last element of the first run
* (a[base1 + len1-1]) must be greater than all elements of the second run.
* <p>
* For performance, this method should be called only when len1 <= len2;
* its twin, mergeHi should be called if len1 >= len2. (Either method
* may be called if len1 == len2.)
*
* @param base1 index of first element in first run to be merged
* @param len1 length of first run to be merged (must be > 0)
* @param base2 index of first element in second run to be merged
* (must be aBase + aLen)
* @param len2 length of second run to be merged (must be > 0)
*/
private void mergeLo(int base1, int len1, int base2, int len2) {
assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
// Copy first run into temp array
int[] a = this.a; // For performance
int[] tmp = ensureCapacity(len1);
int cursor1 = tmpBase; // Indexes into tmp array
int cursor2 = base2; // Indexes int a
int dest = base1; // Indexes int a
System.arraycopy(a, base1, tmp, cursor1, len1);
// Move first element of second run and deal with degenerate cases
a[dest++] = a[cursor2++];
if (--len2 == 0) {
System.arraycopy(tmp, cursor1, a, dest, len1);
return;
}
if (len1 == 1) {
System.arraycopy(a, cursor2, a, dest, len2);
a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
return;
}
int minGallop = this.minGallop; // Use local variable for performance
outer:
while (true) {
int count1 = 0; // Number of times in a row that first run won
int count2 = 0; // Number of times in a row that second run won
/*
* Do the straightforward thing until (if ever) one run starts
* winning consistently.
*/
do {
assert len1 > 1 && len2 > 0;
if (a[cursor2] < tmp[cursor1]) {
a[dest++] = a[cursor2++];
count2++;
count1 = 0;
if (--len2 == 0)
break outer;
} else {
a[dest++] = tmp[cursor1++];
count1++;
count2 = 0;
if (--len1 == 1)
break outer;
}
} while ((count1 | count2) < minGallop);
/*
* One run is winning so consistently that galloping may be a
* huge win. So try that, and continue galloping until (if ever)
* neither run appears to be winning consistently anymore.
*/
do {
assert len1 > 1 && len2 > 0;
count1 = gallopRight(a[cursor2], tmp, cursor1, len1, 0);
if (count1 != 0) {
System.arraycopy(tmp, cursor1, a, dest, count1);
dest += count1;
cursor1 += count1;
len1 -= count1;
if (len1 <= 1) // len1 == 1 || len1 == 0
break outer;
}
a[dest++] = a[cursor2++];
if (--len2 == 0)
break outer;
count2 = gallopLeft(tmp[cursor1], a, cursor2, len2, 0);
if (count2 != 0) {
System.arraycopy(a, cursor2, a, dest, count2);
dest += count2;
cursor2 += count2;
len2 -= count2;
if (len2 == 0)
break outer;
}
a[dest++] = tmp[cursor1++];
if (--len1 == 1)
break outer;
minGallop--;
} while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
if (minGallop < 0)
minGallop = 0;
minGallop += 2; // Penalize for leaving gallop mode
} // End of "outer" loop
this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field
if (len1 == 1) {
assert len2 > 0;
System.arraycopy(a, cursor2, a, dest, len2);
a[dest + len2] = tmp[cursor1]; // Last elt of run 1 to end of merge
} else if (len1 == 0) {
throw new IllegalArgumentException(
"Comparison method violates its general contract!");
} else {
assert len2 == 0;
assert len1 > 1;
System.arraycopy(tmp, cursor1, a, dest, len1);
}
}
/**
* Like mergeLo, except that this method should be called only if
* len1 >= len2; mergeLo should be called if len1 <= len2. (Either method
* may be called if len1 == len2.)
*
* @param base1 index of first element in first run to be merged
* @param len1 length of first run to be merged (must be > 0)
* @param base2 index of first element in second run to be merged
* (must be aBase + aLen)
* @param len2 length of second run to be merged (must be > 0)
*/
private void mergeHi(int base1, int len1, int base2, int len2) {
assert len1 > 0 && len2 > 0 && base1 + len1 == base2;
// Copy second run into temp array
int[] a = this.a; // For performance
int[] tmp = ensureCapacity(len2);
int tmpBase = this.tmpBase;
System.arraycopy(a, base2, tmp, tmpBase, len2);
int cursor1 = base1 + len1 - 1; // Indexes into a
int cursor2 = tmpBase + len2 - 1; // Indexes into tmp array
int dest = base2 + len2 - 1; // Indexes into a
// Move last element of first run and deal with degenerate cases
a[dest--] = a[cursor1--];
if (--len1 == 0) {
System.arraycopy(tmp, tmpBase, a, dest - (len2 - 1), len2);
return;
}
if (len2 == 1) {
dest -= len1;
cursor1 -= len1;
System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
a[dest] = tmp[cursor2];
return;
}
// Use local variable for performance
int minGallop = this.minGallop; // " " " " "
outer:
while (true) {
int count1 = 0; // Number of times in a row that first run won
int count2 = 0; // Number of times in a row that second run won
/*
* Do the straightforward thing until (if ever) one run
* appears to win consistently.
*/
do {
assert len1 > 0 && len2 > 1;
if (tmp[cursor2] < a[cursor1]) {
a[dest--] = a[cursor1--];
count1++;
count2 = 0;
if (--len1 == 0)
break outer;
} else {
a[dest--] = tmp[cursor2--];
count2++;
count1 = 0;
if (--len2 == 1)
break outer;
}
} while ((count1 | count2) < minGallop);
/*
* One run is winning so consistently that galloping may be a
* huge win. So try that, and continue galloping until (if ever)
* neither run appears to be winning consistently anymore.
*/
do {
assert len1 > 0 && len2 > 1;
count1 = len1 - gallopRight(tmp[cursor2], a, base1, len1, len1 - 1);
if (count1 != 0) {
dest -= count1;
cursor1 -= count1;
len1 -= count1;
System.arraycopy(a, cursor1 + 1, a, dest + 1, count1);
if (len1 == 0)
break outer;
}
a[dest--] = tmp[cursor2--];
if (--len2 == 1)
break outer;
count2 = len2 - gallopLeft(a[cursor1], tmp, tmpBase, len2, len2 - 1);
if (count2 != 0) {
dest -= count2;
cursor2 -= count2;
len2 -= count2;
System.arraycopy(tmp, cursor2 + 1, a, dest + 1, count2);
if (len2 <= 1) // len2 == 1 || len2 == 0
break outer;
}
a[dest--] = a[cursor1--];
if (--len1 == 0)
break outer;
minGallop--;
} while (count1 >= MIN_GALLOP | count2 >= MIN_GALLOP);
if (minGallop < 0)
minGallop = 0;
minGallop += 2; // Penalize for leaving gallop mode
} // End of "outer" loop
this.minGallop = minGallop < 1 ? 1 : minGallop; // Write back to field
if (len2 == 1) {
assert len1 > 0;
dest -= len1;
cursor1 -= len1;
System.arraycopy(a, cursor1 + 1, a, dest + 1, len1);
a[dest] = tmp[cursor2]; // Move first elt of run2 to front of merge
} else if (len2 == 0) {
throw new IllegalArgumentException(
"Comparison method violates its general contract!");
} else {
assert len1 == 0;
assert len2 > 0;
System.arraycopy(tmp, tmpBase, a, dest - (len2 - 1), len2);
}
}
/**
* Ensures that the external array tmp has at least the specified
* number of elements, increasing its size if necessary. The size
* increases exponentially to ensure amortized linear time complexity.
*
* @param minCapacity the minimum required capacity of the tmp array
* @return tmp, whether or not it grew
*/
private int[] ensureCapacity(int minCapacity) {
if (tmpLen < minCapacity) {
// Compute smallest power of 2 > minCapacity
int newSize = minCapacity;
newSize |= newSize >> 1;
newSize |= newSize >> 2;
newSize |= newSize >> 4;
newSize |= newSize >> 8;
newSize |= newSize >> 16;
newSize++;
if (newSize < 0) // Not bloody likely!
newSize = minCapacity;
else
newSize = Math.min(newSize, a.length >>> 1);
@SuppressWarnings({"unchecked", "UnnecessaryLocalVariable"})
int[] newArray = new int[newSize];
tmp = newArray;
tmpLen = newSize;
tmpBase = 0;
}
return tmp;
}
}
| [
"alexander.rogalsky@yandex.ru"
] | alexander.rogalsky@yandex.ru |
b46100ed098f5387cda16ff1f23e87abc9ac6588 | 1c0bc5df1606465f6b42604b222c377fc690b9de | /APCSA Projects/src/Unit0/AsciiArt.java | 1efd5058e14ed876b1af71ca025f32da02b6b69e | [] | no_license | OnMyHorizon/APCSA2020 | 1e9897d4d898597aa0f5a2a3026663c2430b38a2 | 1547da7cc85d6c7299c65f3c6be24e6054130e10 | refs/heads/master | 2020-12-26T11:01:05.519246 | 2020-03-13T17:20:06 | 2020-03-13T17:20:06 | 237,489,051 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,238 | java | package Unit0;
//(c) A+ Computer Science
//www.apluscompsci.com
//Name -
//Date -
//Class -
//Lab -
public class AsciiArt
{
public static void main ( String[] args )
{
System.out.println("Jensen McKenzie \n\n" );
System.out.println("Smile Face" );
System.out.println("\n\n\n\n" );
System.out.println("*****************************" );
System.out.println("* *" );
System.out.println("* * * *" );
System.out.println("* *" );
System.out.println("* *" );
System.out.println("* * *" );
System.out.println("* *" );
System.out.println("* ** ** *" );
System.out.println("* ************* *" );
System.out.println("* *" );
System.out.println("*****************************" );
//add other output
//System.out.println(" \n\n\n\nHelpFul Hints" );
//System.out.println("\\\\ draws one backslash on the screen!\n" );
//System.out.println("\\\" draws one double quote on the screen!\n" );
//System.out.println("\\\' draws one single quote on the screen!\n" );
}
} | [
"mckenziegarandm1677@CA-SU-F106-38.sduhsd.lan"
] | mckenziegarandm1677@CA-SU-F106-38.sduhsd.lan |
356e97e20b71411a69f7e682fc62afbdc876ef61 | ea2f1e323b007490468cc718b939061ec51988cc | /src/test/java/nl/dvberkel/kata/base64/Base64EncodeTest.java | fd87186324b8aaf2fc49249f3110125ae174b902 | [
"MIT"
] | permissive | dvberkel/Base64Kata | fab870036575d22581ea49e3b41a464d6289db6f | 71c83d91a1b86bc37b6a0a6fca4c901d388b26bb | refs/heads/master | 2016-09-05T16:00:24.715959 | 2014-09-19T11:50:39 | 2014-09-19T11:50:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 8,123 | java | package nl.dvberkel.kata.base64;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static nl.dvberkel.kata.base64.Base64EncodeTestCase.verifyThat;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@RunWith(Parameterized.class)
public class Base64EncodeTest {
private final byte[] source;
private final String destination;
private Encoder kata;
public Base64EncodeTest(Base64EncodeTestCase testCase) {
this.source = testCase.getSource();
this.destination = testCase.getDestination();
}
@Before
public void createKata() {
kata = new Kata();
}
@Test
public void shouldEncodeValuesCorrectly() {
assertThat(kata.encode(source), is(destination));
}
@Parameterized.Parameters(name="{0}")
public static Collection<Base64EncodeTestCase[]> data() {
List<Base64EncodeTestCase[]> data = new ArrayList<>();
data.add(verifyThat(0b0, 0b0, 0b0).encodesAs("AAAA"));
data.add(verifyThat(0b0, 0b0, 0b0, 0b0, 0b0, 0b0).encodesAs("AAAAAAAA"));
data.add(verifyThat(0b0, 0b0, 0b0, 0b0, 0b0, 0b0, 0b0, 0b0, 0b0).encodesAs("AAAAAAAAAAAA"));
data.add(verifyThat(0b0, 0b0).encodesAs("AAA="));
data.add(verifyThat(0b0).encodesAs("AA=="));
data.add(verifyThat(0b0, 0b0, 0b0, 0b0, 0b0).encodesAs("AAAAAAA="));
data.add(verifyThat(0b0, 0b0, 0b0, 0b0).encodesAs("AAAAAA=="));
data.add(verifyThat(0b0, 0b0, 0b0, 0b0, 0b0, 0b0, 0b0, 0b0).encodesAs("AAAAAAAAAAA="));
data.add(verifyThat(0b0, 0b0, 0b0, 0b0, 0b0, 0b0, 0b0).encodesAs("AAAAAAAAAA=="));
data.add(verifyThat(0b0, 0b0, 0b00000001).encodesAs("AAAB"));
data.add(verifyThat(0b0, 0b0, 0b00000010).encodesAs("AAAC"));
data.add(verifyThat(0b0, 0b0, 0b00000011).encodesAs("AAAD"));
data.add(verifyThat(0b0, 0b0, 0b00000100).encodesAs("AAAE"));
data.add(verifyThat(0b0, 0b0, 0b00000101).encodesAs("AAAF"));
data.add(verifyThat(0b0, 0b0, 0b00000110).encodesAs("AAAG"));
data.add(verifyThat(0b0, 0b0, 0b00000111).encodesAs("AAAH"));
data.add(verifyThat(0b0, 0b0, 0b00001000).encodesAs("AAAI"));
data.add(verifyThat(0b0, 0b0, 0b00001001).encodesAs("AAAJ"));
data.add(verifyThat(0b0, 0b0, 0b00001010).encodesAs("AAAK"));
data.add(verifyThat(0b0, 0b0, 0b00001011).encodesAs("AAAL"));
data.add(verifyThat(0b0, 0b0, 0b00001100).encodesAs("AAAM"));
data.add(verifyThat(0b0, 0b0, 0b00001101).encodesAs("AAAN"));
data.add(verifyThat(0b0, 0b0, 0b00001110).encodesAs("AAAO"));
data.add(verifyThat(0b0, 0b0, 0b00001111).encodesAs("AAAP"));
data.add(verifyThat(0b0, 0b0, 0b00010000).encodesAs("AAAQ"));
data.add(verifyThat(0b0, 0b0, 0b00010001).encodesAs("AAAR"));
data.add(verifyThat(0b0, 0b0, 0b00010010).encodesAs("AAAS"));
data.add(verifyThat(0b0, 0b0, 0b00010011).encodesAs("AAAT"));
data.add(verifyThat(0b0, 0b0, 0b00010100).encodesAs("AAAU"));
data.add(verifyThat(0b0, 0b0, 0b00010101).encodesAs("AAAV"));
data.add(verifyThat(0b0, 0b0, 0b00010110).encodesAs("AAAW"));
data.add(verifyThat(0b0, 0b0, 0b00010111).encodesAs("AAAX"));
data.add(verifyThat(0b0, 0b0, 0b00011000).encodesAs("AAAY"));
data.add(verifyThat(0b0, 0b0, 0b00011001).encodesAs("AAAZ"));
data.add(verifyThat(0b0, 0b0, 0b00011010).encodesAs("AAAa"));
data.add(verifyThat(0b0, 0b0, 0b00011011).encodesAs("AAAb"));
data.add(verifyThat(0b0, 0b0, 0b00011100).encodesAs("AAAc"));
data.add(verifyThat(0b0, 0b0, 0b00011101).encodesAs("AAAd"));
data.add(verifyThat(0b0, 0b0, 0b00011110).encodesAs("AAAe"));
data.add(verifyThat(0b0, 0b0, 0b00011111).encodesAs("AAAf"));
data.add(verifyThat(0b0, 0b0, 0b00100000).encodesAs("AAAg"));
data.add(verifyThat(0b0, 0b0, 0b00100001).encodesAs("AAAh"));
data.add(verifyThat(0b0, 0b0, 0b00100010).encodesAs("AAAi"));
data.add(verifyThat(0b0, 0b0, 0b00100011).encodesAs("AAAj"));
data.add(verifyThat(0b0, 0b0, 0b00100100).encodesAs("AAAk"));
data.add(verifyThat(0b0, 0b0, 0b00100101).encodesAs("AAAl"));
data.add(verifyThat(0b0, 0b0, 0b00100110).encodesAs("AAAm"));
data.add(verifyThat(0b0, 0b0, 0b00100111).encodesAs("AAAn"));
data.add(verifyThat(0b0, 0b0, 0b00101000).encodesAs("AAAo"));
data.add(verifyThat(0b0, 0b0, 0b00101001).encodesAs("AAAp"));
data.add(verifyThat(0b0, 0b0, 0b00101010).encodesAs("AAAq"));
data.add(verifyThat(0b0, 0b0, 0b00101011).encodesAs("AAAr"));
data.add(verifyThat(0b0, 0b0, 0b00101100).encodesAs("AAAs"));
data.add(verifyThat(0b0, 0b0, 0b00101101).encodesAs("AAAt"));
data.add(verifyThat(0b0, 0b0, 0b00101110).encodesAs("AAAu"));
data.add(verifyThat(0b0, 0b0, 0b00101111).encodesAs("AAAv"));
data.add(verifyThat(0b0, 0b0, 0b00110000).encodesAs("AAAw"));
data.add(verifyThat(0b0, 0b0, 0b00110001).encodesAs("AAAx"));
data.add(verifyThat(0b0, 0b0, 0b00110010).encodesAs("AAAy"));
data.add(verifyThat(0b0, 0b0, 0b00110011).encodesAs("AAAz"));
data.add(verifyThat(0b0, 0b0, 0b00110100).encodesAs("AAA0"));
data.add(verifyThat(0b0, 0b0, 0b00110101).encodesAs("AAA1"));
data.add(verifyThat(0b0, 0b0, 0b00110110).encodesAs("AAA2"));
data.add(verifyThat(0b0, 0b0, 0b00110111).encodesAs("AAA3"));
data.add(verifyThat(0b0, 0b0, 0b00111000).encodesAs("AAA4"));
data.add(verifyThat(0b0, 0b0, 0b00111001).encodesAs("AAA5"));
data.add(verifyThat(0b0, 0b0, 0b00111010).encodesAs("AAA6"));
data.add(verifyThat(0b0, 0b0, 0b00111011).encodesAs("AAA7"));
data.add(verifyThat(0b0, 0b0, 0b00111100).encodesAs("AAA8"));
data.add(verifyThat(0b0, 0b0, 0b00111101).encodesAs("AAA9"));
data.add(verifyThat(0b0, 0b0, 0b00111110).encodesAs("AAA+"));
data.add(verifyThat(0b0, 0b0, 0b00111111).encodesAs("AAA/"));
data.add(verifyThat(0b0, 0b00000000, 0b01000000).encodesAs("AABA"));
data.add(verifyThat(0b0, 0b00001111, 0b11000000).encodesAs("AA/A"));
data.add(verifyThat(0b0, 0b00010000, 0b00000000).encodesAs("ABAA"));
data.add(verifyThat(0b00000011, 0b11110000, 0b00000000).encodesAs("A/AA"));
data.add(verifyThat(0b00000100, 0b00000000, 0b00000000).encodesAs("BAAA"));
data.add(verifyThat(0b11111100, 0b00000000, 0b00000000).encodesAs("/AAA"));
data.add(verifyThat(0b00000001).encodesAs("AQ=="));
data.add(verifyThat(0b11111111).encodesAs("/w=="));
data.add(verifyThat(0b00000000, 0b00000001).encodesAs("AAE="));
data.add(verifyThat(0b11111111, 0b11111111).encodesAs("//8="));
data.add(verifyThat(0b00001001, 0b10101011, 0b01101100).encodesAs("Cats"));
return data;
}
}
class Base64EncodeTestCase {
private final byte[] source;
private String destination;
public static Base64EncodeTestCase verifyThat(int... source) {
byte[] bytes = new byte[source.length];
for (int index = 0; index < source.length; index++) {
bytes[index] = (byte) source[index];
}
return verifyThat(bytes);
}
public static Base64EncodeTestCase verifyThat(byte... source) {
return new Base64EncodeTestCase(source);
}
private Base64EncodeTestCase(byte[] source) {
this.source = source;
}
public Base64EncodeTestCase[] encodesAs(String destination) {
this.destination = destination;
return new Base64EncodeTestCase[]{this};
}
public byte[] getSource() {
return source;
}
public String getDestination() {
return destination;
}
@Override
public String toString() {
return String.format("encode(%s) should be \"%s\"", Arrays.toString(source), destination);
}
}
| [
"daan.v.berkel.1980@gmail.com"
] | daan.v.berkel.1980@gmail.com |
8c1b48eb18bacbeeb9401d7ef3084c848319659d | 812830827f7fb93649dd85f0158f1c7ffcbf7e9e | /chapter_005/src/test/java/ru/job4j/generic/StoreTest.java | 4ef4718bba3a38d7286f74968d8b51ce7c46ed38 | [
"Apache-2.0"
] | permissive | Vikkingg13/job4j | 832f360a3f459b84e8ba8bd941e25866b1eaa519 | c7b6c8d5740b7c7dff777ddd97f4e81c13733fa8 | refs/heads/master | 2022-09-08T18:10:05.388496 | 2020-02-04T13:29:19 | 2020-02-04T13:34:22 | 202,783,887 | 1 | 0 | Apache-2.0 | 2022-09-08T01:06:09 | 2019-08-16T19:02:03 | Java | UTF-8 | Java | false | false | 1,293 | java | package ru.job4j.generic;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
public class StoreTest {
@Test
public void whenAddUserInStore() {
UserStore store = new UserStore(10);
User user = new User("k1abc");
store.add(user);
assertThat(store.findById("k1abc"), is(user));
}
@Test
public void whenReplaceUserInStoreThenOldUserNotHaveAndHaveNewUser() {
UserStore store = new UserStore(10);
User first = new User("k1abc");
User second = new User("e4def");
store.add(first);
store.replace(first.getId(), second);
assertThat(store.findById("e4def"), is(second));
assertThat(store.findById("k1abc"), is((User) null));
}
@Test
public void whenDeleteUserInStore() {
UserStore store = new UserStore(10);
User first = new User("k1abc");
store.add(first);
store.delete(first.getId());
assertThat(store.findById(first.getId()), is((User) null));
}
@Test
public void whenAddRoleInStore() {
RoleStore store = new RoleStore(5);
Role role = new Role("3etgh");
store.add(role);
assertThat(store.findById("3etgh"), is(role));
}
}
| [
"14GameOver@mail.ru"
] | 14GameOver@mail.ru |
87ec555a6757e35b1f31d43abee5ab8f8fb23210 | 0a80b61fec2aa242a0cec7c53a33351c3ccfb6b1 | /WinAgent/src/com/club203/dialog/AuthenDialog.java | f910602442b6abc03233cd842a370ab02ff8b8c0 | [] | no_license | triplekill/WinAgent | 3ad0dbda90763d32ce58943add12eb7c345fd2e2 | 65eec57197ba3b818da6304ebb313fdda6828e3b | refs/heads/master | 2020-09-16T12:05:14.783645 | 2019-04-10T14:21:26 | 2019-04-10T14:21:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,452 | java | package com.club203.dialog;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 这里鉴权对话框,作为所有鉴权对话框的基类,仅包含界面
* @author lihan
*/
public abstract class AuthenDialog extends JDialog{
/**
*
*/
private static final long serialVersionUID = 1L;
//相对于1920 x 1080显示器的分辨率
private final int WIDTH = 290;
private final int HEIGHT = 152;
//当前分辨率
private final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//用户名密码框
protected final JTextField usernameField;
protected final JPasswordField passwordField;
//确认按钮
protected final JButton submitButton;
protected final JButton resetButton;
//记住密码选择控件
protected final JCheckBox rememberCheckBox;
private final static Logger logger = LoggerFactory.getLogger(AuthenDialog.class);
public AuthenDialog() {
setTitle("接入鉴权");
logger.info("Starting initializing authentication dialog");
changeSwingSkin();
Container container = getContentPane();
container.setLayout(null);
JLabel userLabel = new JLabel("用户名:");
userLabel.setBounds(widthZoom(15), heightZoom(15), widthZoom(200), heightZoom(25));
usernameField = new JTextField();
usernameField.setBounds(widthZoom(85), heightZoom(15), widthZoom(160), heightZoom(25));
JLabel passLabel = new JLabel("密码:");
passLabel.setBounds(widthZoom(15), heightZoom(50), widthZoom(200), heightZoom(25));
passwordField = new JPasswordField();
passwordField.setBounds(widthZoom(85), heightZoom(50), widthZoom(160), heightZoom(25));
submitButton = new JButton("确定");
submitButton.setBounds(widthZoom(20), heightZoom(87), widthZoom(60), heightZoom(25));
resetButton = new JButton("重置");
resetButton.setBounds(widthZoom(100), heightZoom(87), widthZoom(60), heightZoom(25));
rememberCheckBox = new JCheckBox("记住密码",true);
rememberCheckBox.setBounds(widthZoom(180), heightZoom(87), widthZoom(90), heightZoom(25));
container.add(userLabel);
container.add(passLabel);
container.add(usernameField);
container.add(passwordField);
container.add(submitButton);
container.add(resetButton);
container.add(rememberCheckBox);
setResizable(false);
setSize(widthZoom(WIDTH), heightZoom(HEIGHT));
setLocationRelativeTo(null);
//设置模态对话框,用于阻塞建连操作
//即输入完成后才能退出
setModal(true);
setAlwaysOnTop(true);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
}
public int widthZoom(int width) {
double widthZ = 1.0 * width / 1920;
return (int)(widthZ * screenSize.getWidth());
}
public int heightZoom(int height) {
double heightZ = 1.0 * height / 1080;
return (int)(heightZ * screenSize.getHeight());
}
public void changeSwingSkin() {
try{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
}catch(Exception e){
JOptionPane.showMessageDialog(null, "主界面皮肤加载失败");
logger.info("Using the default look and feel.");
}
}
}
| [
"18653059888@163.com"
] | 18653059888@163.com |
5014bb8d18a047f7cec2e5981b07c9fcfb08ef80 | be4dcae13ec8ea3e3ec61869febef96d91ddb200 | /staticchecking/src/main/java/petspeak/PetSpeak.java | efab8b065a2c5e7ce20064af9c9291abef5ecb1a | [] | no_license | zcdJason/java8-maven | 32379e852c48870f114c2fa8d749a26ac2b50694 | db7dea9d4a04384a269d0c5cefa23682f7c89beb | refs/heads/master | 2023-07-11T04:06:37.303186 | 2021-08-16T01:50:39 | 2021-08-16T01:50:39 | 395,219,459 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 787 | java | // staticchecking/petspeak/PetSpeak.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Speaking pets in Java
// {java staticchecking.petspeak.PetSpeak}
package petspeak;
interface Pet {
void speak();
}
class Cat implements Pet {
public void speak() {
System.out.println("meow!");
}
}
class Dog implements Pet {
public void speak() {
System.out.println("woof!");
}
}
public class PetSpeak {
static void command(Pet p) {
p.speak();
}
public static void main(String[] args) {
Pet[] pets = {new Cat(), new Dog()};
for (Pet pet : pets)
command(pet);
}
}
/* Output:
meow!
woof!
*/
| [
"736777445@qq.com"
] | 736777445@qq.com |
6839af38ce4dd8b51c7d963d239d48ae3b792bf4 | dbe629451864b72f8ae631acdac3ff06a64685b8 | /app/src/main/java/htl/grieskirchen/aedinger16woche24/MainActivity.java | bce77f4b7132148f5b20624593a76e8e38479703 | [] | no_license | aedinger16/aedinger16Woche24 | 3df996e2fbd3f48eeb85c5587f8e54b57eb642a7 | 9d2eb685228e02ac0adb4677564d7b84e79d93e9 | refs/heads/master | 2020-05-02T19:43:39.174665 | 2019-03-28T09:15:59 | 2019-03-28T09:15:59 | 178,166,791 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 486 | java | package htl.grieskirchen.aedinger16woche24;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.google.firebase.firestore.FirebaseFirestore;
public class MainActivity extends AppCompatActivity {
private FirebaseFirestore db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = FirebaseFirestore.getInstance();
}
}
| [
"alex_edi@gmx.at"
] | alex_edi@gmx.at |
32b8bcbc707d0c170e893d6484598bd551a81d75 | c918dc8a4fa4a4bae144458fcd41e2dc8a2dca21 | /src/main/java/com/papi/quartz/enums/QuartzJobs.java | 30b91a3c3d69afe87abf50d5a707ef32ddbccd0b | [] | no_license | fanshaowei/quartzserver | 14b53335f3a09cec135be4f468a3fabdfb053b2a | 97c95c27b0ff79d8b1d9b45eb60ef9687ff318ea | refs/heads/master | 2022-12-24T16:36:17.828655 | 2020-07-22T03:05:31 | 2020-07-22T03:05:31 | 74,102,609 | 2 | 2 | null | 2022-12-16T06:47:58 | 2016-11-18T06:40:49 | CSS | UTF-8 | Java | false | false | 787 | java | package com.papi.quartz.enums;
public enum QuartzJobs {
BasicJob("com.papi.quartz.quartzjobs.BasicJob"),
HelloJob("com.papi.quartz.quartzjobs.HelloJob"),
SceneRelateJob("com.papi.quartz.quartzjobs.SceneRelateJob"),
SenseControlJob("com.papi.quartz.quartzjobs.SenseControlJob");
private String clazz;
private QuartzJobs(String clazz){
this.clazz = clazz;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public static String getJobType(String clazz){
QuartzJobs[] quartzJobs = QuartzJobs.values();
String jobType = "";
for(QuartzJobs qj: quartzJobs){
if(clazz.equals(qj.getClazz())){
jobType = qj.name();
}
}
return jobType;
}
}
| [
"a4848438@foxmail.com"
] | a4848438@foxmail.com |
b99f64b354b170b02610e5e9f00247b986a44771 | 5996c2bc9c7cb55cade1551ddbb81d6512f68a78 | /NetworkCalculator/src/networkCalcPackage/ExpressionFrame.java | de46b653f06175258643dcedc97223e63553a95b | [] | no_license | hdpriest/NetworkDev | 82a35c3c7ff604adde0864329754ee4630825ab7 | 02f78a8c1d643a3e222cb68ecba01285e06439af | refs/heads/master | 2016-08-04T13:17:34.008640 | 2014-09-11T16:59:03 | 2014-09-11T16:59:03 | 21,250,485 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,082 | java | package networkCalcPackage;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.math.RoundingMode;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
class ExpressionFrame {
private int N;
private int M;
private float[][] DataFrame;
private float[] k;
private float[] means;
private float[] gccSums;
private String[] X_lab;
private String[] Y_lab;
private int X_iterator;
public ExpressionFrame (int Dim1, int Dim2) {
DataFrame = new float[Dim1][Dim2];
N = Dim1;
M = Dim2;
k = new float[Dim1];
means = new float[Dim1];
gccSums= new float[Dim1];
X_lab = new String[Dim1];
Y_lab = new String[Dim2];
X_iterator = -1;
}
public void resetIterator () {
X_iterator=-1;
}
public int getNumColumns () {
int I = DataFrame[0].length;
return I;
}
public int getNumRows () {
int I = DataFrame.length;
return I;
}
public boolean hasNext () {
if(DataFrame[X_iterator+1] != null){
return true;
}else{
return false;
}
}
public double[] getRowByIndexDbl (int I){
float[] Row = _getRow(I);
double[] dRow = new double[M];
for(int i=0;i<M;i++){
dRow[i] = (double) Row[i];
}
return dRow;
}
private float[] _getRow(int I){
float[] Row = new float[M];
for(int j=0;j<M;j++){
Row[j]=_getValueByEntry(I,j);
}
return Row;
}
public float[] getRowByIndex (int I){
if(DataFrame[I] != null){
return _getRow(I);
}else{
System.err.println("Cannot get row "+I+" from matrix.\n\n");
System.exit(0);
}
return null;
}
private float _getValueByEntry (int I,int J){
return DataFrame[I][J];
}
public float getValueByEntry (int I,int J){
return _getValueByEntry(I,J);
}
public void setValueByEntry (float Value,int I, int J){
_setValueByEntry(Value,I,J);
}
private void _setValueByEntry (float Value,int I, int J){
DataFrame[I][J]=Value;
}
public String[] getRowNames (){
return X_lab;
}
public void setRowNames (String[] Rows) {
X_lab = Rows;
}
public void setColumnNames (String[] Cols){
Y_lab = Cols;
}
public float[][] getDataFrame () {
return DataFrame;
}
public float[] getNextRow () {
float[] thisRow = new float[DataFrame[0].length];
thisRow=DataFrame[X_iterator+1];
X_iterator++;
return thisRow;
}
public void maskMatrix (float maskLevel) {
int H = DataFrame.length;
int W = DataFrame[0].length;
for(int i=0;i<H;i++){
for(int j=0;j<W;j++){
if(DataFrame[i][j]<maskLevel){
DataFrame[i][j]=0;
}
}
}
}
public boolean testValue (int i,int j){
boolean res=true;
if(DataFrame[i][j] == 0){
res=false;
}else{
res=true;
}
return res;
}
public void calculateKs (){
int H = DataFrame.length;
for(int i=0;i<H;i++){
float thisK=0f;
for(int j=0;j<DataFrame[i].length;j++){
if(i==j){
}else{
thisK+=DataFrame[i][j];
}
}
k[i]=thisK;
}
}
public float findK (int R,int j){
/*for(int i=0;i<DataFrame[R].length;i++){
if(i==j){
/// do not add DataFrame[R][j] to the k of R
}else{
K+=DataFrame[R][i];
}
}
return K;*/
float K=k[R];
return K;
}
public void addRow (float[] Row){
int I=X_iterator;
System.arraycopy(Row, 0, DataFrame[I+1], 0, Row.length);
X_iterator++;
}
public void changeRow (int I,float[] Row){
System.arraycopy(Row, 0, DataFrame[I], 0, Row.length);
}
public void printMatrixToFile (String path,String Sep){
try {
PrintWriter writer = new PrintWriter(path,"UTF-8");
writer.print(Sep);
for(int y=0;y<Y_lab.length;y++){
writer.print(Y_lab[y]);
if(y != Y_lab.length-1){
writer.print(Sep);
}
}
writer.print("\n");
for(int i=0;i<DataFrame.length;i++){
float[] Row = new float[DataFrame[i].length];
Row = DataFrame[i];
writer.print(X_lab[i]);
writer.print(Sep);
for(int j=0;j<Row.length;j++){
writer.print(Row[j]);
if(j != Row.length-1){
writer.print(Sep);
}
}
writer.print("\n");
}
writer.close();
} catch (Exception e){
//
}
}
public void calculateMeans() {
for(int i=0;i<DataFrame.length;i++){
float[] Row = _getRow(i);
float s=0;
for(int j=0;j<Row.length;j++){
s+=Row[j];
}
means[i]=s/Row.length;
}
}
public float getMean(int i){
return means[i];
}
public float getGiniDenom(int i) {
return gccSums[i];
}
public void calculateGiniSums() {
for(int i=0;i<DataFrame.length;i++){
float[] array1 = _getRow(i);
float Denominator=0.0f;
int[] sortRanks1 = Operations.getIndicesInOrder(array1);
for(int j=0;j<array1.length;j++){
float v2=((2*(j+1))-array1.length-1) * array1[sortRanks1[j]];
Denominator+=v2;
}
gccSums[i]=Denominator;
}
}
}
| [
"hdpriest@gmail.com"
] | hdpriest@gmail.com |
5fdc274d676e81be2c623203f3799700cb98708a | 470f0ff9759312c9cc45e491356c50520a8e7157 | /java/hackerrank/src/main/java/com/vaani/hackerrank/misc/ByteLandianTours.java | 99a2a280ed0e9c74954cc40a5f25cb63716133dd | [
"MIT"
] | permissive | kinshuk4/hackerrank-solutions | 276df85d3d6bf636792d823b5b229260723d971f | 13272de17b3575e1caec0bf9ef8ae072d9434733 | refs/heads/master | 2022-10-08T20:06:17.618241 | 2020-06-25T21:13:02 | 2020-06-25T21:13:02 | 170,718,285 | 0 | 0 | MIT | 2022-10-05T19:49:43 | 2019-02-14T16:01:21 | Java | UTF-8 | Java | false | false | 4,498 | java | /*
*
* This source file is a part of lainexperiment project.
* Description for it can be found in ReadMe.txt.
*
*/
/*
* Date: 10/12/2015
*
* Hacker rank
* Problem: ByteLandian Tours
* Status: accepted / timeout
*
* Problem
*
* The country of Byteland contains N cities and N - 1 bidirectional roads between them
* such that there is a path between any two cities. The cities are numbered (0,...,N - 1).
* The people were very unhappy about the time it took to commute, especially salesmen who
* had to go about every city selling goods. So it was decided that new roads would be built
* between any two "somewhat near" cities. Any two cities in Bytleland that can be reached
* by traveling on exactly two old roads are known as "somewhat near" each other.
* Now a salesman situated in city 0, just like any other typical salesman, has to visit
* all cities exactly once and return back to city 0 in the end. In how many ways can he
* do this?
*
* Input Format
*
* The first line contains the number of test cases T. T test cases follow. The first line
* contains N, the number of cities in Byteland. The following N - 1 lines contain the
* description of the roads. The ith line contains two integers ai and bi, meaning that
* there was originally a road connecting cities with numbers ai and bi.
*
* Output Format
*
* Output T lines, one corresponding to each test case containing the required answer for
* that test case. Since the answers can be huge, output them modulo 1000000007
*
* Input
*
2
3
0 1
1 2
5
0 1
1 2
2 3
2 4
*
* Output
*
2
4
*
*/
package com.vaani.hackerrank.misc;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.function.Consumer;
import java.util.stream.IntStream;
public class ByteLandianTours {
static Set<Integer>[] G;
static class Pair {
int l;
int v;
Pair(int l, int v) {
this.l = l;
this.v = v;
}
}
static int dfs() {
Stack<Pair> s = new Stack<>();
s.add(new Pair(0, 0));
Stack<Integer> path = new Stack<>();
boolean[] visited = new boolean[G.length];
int res = 0;
while (!s.isEmpty()) {
Pair p = s.pop();
while (p.l != path.size()) {
visited[path.pop()] = false;
}
path.push(p.v);
Consumer<Pair> f = a -> {
s.add(a);
visited[p.v] = true;
};
int adj = (int) G[p.v].stream().
filter(a -> !visited[a]).
map(a -> new Pair(path.size(), a)).
peek(f).
count();
if (adj == 0) {
if (path.size() == G.length && G[p.v].contains(0)) {
//System.out.println(path);
res++;
}
}
}
return res;
}
@SuppressWarnings("unchecked")
private static void moreEdges() {
Set<Integer>[] newG = new Set[G.length];
Arrays.setAll(newG, i -> new HashSet<>(G[i]));
IntStream.range(0, G.length).forEach(v -> {
List<Integer> l = new ArrayList<>();
for (int adj: G[v]) {
// if (adj < v) continue;
G[adj].stream().filter(u -> u > v).forEach(u -> {
l.add(u);
newG[u].add(v);
});
}
newG[v].addAll(l);
});
G = newG;
}
@SuppressWarnings("unchecked")
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = System.getProperty("local") == null?
new Scanner(System.in): new Scanner(ByteLandianTours.class.getResourceAsStream("ByteLandianTours.in"));
int T = scanner.nextInt();
for (int i = 0; i < T; ++i) {
int N = scanner.nextInt();
G = new Set[N];
Arrays.setAll(G, HashSet::new);
for (int n = 0; n < N - 1; ++n) {
int v = scanner.nextInt();
int a = scanner.nextInt();
G[v].add(a);
G[a].add(v);
}
moreEdges();
System.out.println(dfs());
}
scanner.close();
}
}
| [
"kinshuk.ram@gmail.com"
] | kinshuk.ram@gmail.com |
5f0b18de9576326d19dd69a941c020dc36edc0c1 | 5f1906d6559df437f8fa355f97f4867d08babbba | /src/main/java/com/vikash/model/BeanClass.java | 9b551989d8a69bfa0c1bdc473ca23d316416380e | [] | permissive | vikas981/pdfcompare | 1dafab14091db0455f45ec465f1a3abaaeb8e902 | b18c19f2af244d5ad05143051fc57a72b1edd877 | refs/heads/main | 2021-07-12T00:19:14.716807 | 2021-03-12T09:49:08 | 2021-03-12T09:49:08 | 240,467,957 | 0 | 0 | Apache-2.0 | 2020-02-14T09:05:44 | 2020-02-14T09:05:43 | null | UTF-8 | Java | false | false | 675 | java | package com.vikash.model;
public class BeanClass {
private String first;
private String second;
private int number;
public BeanClass(String pdftext1,int number) {
super();
this.first = pdftext1;
this.number = number ;
}
public BeanClass(String pdftext2) {
super();
this.second = pdftext2;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getSecond() {
return second;
}
public void setPdftext2(String second) {
this.second = second;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
| [
"vs98990@gmail.com"
] | vs98990@gmail.com |
84f4e58c547af8a2497b947d37a1de09f51bc9ce | 893b90846a90dbd0869aa87af698b0f970d3c98b | /src/org/pvemu/network/game/input/game/GameActionOkPacket.java | 9859be4114f1229a9abdc74e61d02aeac88ef4b0 | [] | no_license | warhound1/PvEmu | dd8d0e01b1ababef7bf807c638b0b3a0e67c7410 | 097bf84671677ed75c6acf33b520e8dac230076d | refs/heads/master | 2020-12-25T01:51:45.586246 | 2015-07-11T16:09:44 | 2015-07-11T16:09:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,494 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.pvemu.network.game.input.game;
import org.apache.mina.core.session.IoSession;
import org.pvemu.game.gameaction.ActionPerformer;
//import org.pvemu.game.GameActionHandler;
import org.pvemu.game.objects.player.Player;
import org.pvemu.common.Loggin;
import org.pvemu.common.utils.Utils;
import org.pvemu.network.InputPacket;
import org.pvemu.network.SessionAttributes;
/**
*
* @author Vincent Quatrevieux <quatrevieux.vincent@gmail.com>
*/
public class GameActionOkPacket implements InputPacket {
@Override
public String id() {
return "GK";
}
@Override
public void perform(String extra, IoSession session) {
boolean ok = extra.charAt(0) == 'K';
short actionID = 0;
String[] args;
try {
args = Utils.split(extra.substring(1), "|");
actionID = Short.parseShort(args[0]);
} catch (Exception e) {
return;
}
ActionPerformer performer = SessionAttributes.FIGHTER.exists(session) ?
SessionAttributes.FIGHTER.getValue(session) :
SessionAttributes.PLAYER.getValue(session);
if(performer == null)
return;
performer.getActionsManager().endGameAction(actionID, ok, args);
}
}
| [
"quatrevieux.vincent@gmail.com"
] | quatrevieux.vincent@gmail.com |
4df12997d839a7756fa76ea3ce23ca44e288d97c | cd9fd02501e99806debb0a6f1b1a3ebd0fbe1676 | /java08_swing/src/PackMan.java | 331ee361a72a7c5495dad6404467bcf882bee1ca | [] | no_license | bisnin0/2020-08-19 | cba33a3ad1716376f208d97bf6fada8144125217 | 19895c52c059a60ce015714d1c9522d3207faa3e | refs/heads/master | 2022-12-14T03:33:30.149917 | 2020-08-19T08:52:17 | 2020-08-19T08:52:17 | 288,681,044 | 0 | 0 | null | null | null | null | UHC | Java | false | false | 2,594 | java |
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class PackMan extends JFrame {
MyCanvas mc = new MyCanvas();
MyAdapter ma = new MyAdapter();
int x=170,y=150,w=220,h=200;
Image img;
int a=0, b=1; //이미지 바꾸기
int q=1; //방향설정
int start = 0;
public PackMan() {
super("Pack-Man");
add(mc);
mc.repaint();
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
while(true) { //방향설정
mc.addKeyListener(ma);
if(q==1) {
left();
}else if(q==2) {
right();
}else if(q==3) {
top();
}else if(q==4) {
bottom();
}
mc.repaint();
try {
Thread.sleep(100);
}catch(Exception e) {}
}
}
public void left() {
x-=10;
w-=10;
if(a==0) {
a++; b++;
}else if(a==1) {
a--; b--;
}
if(w==0) {
x+=400; w+=400;
}
}
public void right() {
x+=10;
w+=10;
if(a==2) {
a++; b++;
}else if(a==3) {
a--; b--;
}
if(w==430) {
x-=400; w-=400;
}
}
public void top() {
y-=10;
h-=10;
if(a==4) {
a++; b++;
}else if(a==5) {
a--; b--;
}
if(h==0) {
y+=400; h+=400;
}
}
public void bottom() {
y+=10;
h+=10;
if(a==6) {
a++; b++;
}else if(a==7) {
a--; b--;
}
if(h==430) {
y-=400; h-=400;
}
}
class MyAdapter extends KeyAdapter{
public void keyPressed(KeyEvent ke) {
int key = ke.getKeyCode();
if("A".equals(ke.getKeyText(key)) || key==KeyEvent.VK_LEFT) {
a=0; b=1; q=1;
}else if("D".equals(ke.getKeyText(key)) || key==KeyEvent.VK_RIGHT) {
a=2; b=3; q=2;
}else if("W".equals(ke.getKeyText(key)) || key==KeyEvent.VK_UP) {
a=4; b=5; q=3;
}else if("S".equals(ke.getKeyText(key)) || key==KeyEvent.VK_DOWN) {
a=6; b=7; q=4;
}
}
}
public class MyCanvas extends Canvas{
MyCanvas(){
img = Toolkit.getDefaultToolkit().getImage("img/packman.jpg");
}
public void paint(Graphics g) {
g.drawString("화면을 한번 누르면 시작합니다.", 105, 80);
g.drawString("조작키 : W,A,S,D or 방향키", 120, 100);
int pw = img.getWidth(this);
int ph = img.getHeight(this);
int imgw = pw/8;
int imgh = ph/10;
g.drawImage(img, x, y, w, h, imgw*a, imgh/3, imgw*b, imgh*10, this);
}
}
public static void main(String[] args) {
new PackMan();
}
}
| [
"dustmq299@gmail.com"
] | dustmq299@gmail.com |
34501563013c1f5ae4fbc4ca86b1c846235bef2c | 7dad6e7dece644a1f27700cd679b61eed62d9cda | /pay_project/pay_manager_admin/src/main/java/com/pay/manger/controller/job/TxPayOrderClearJob.java | 51317210378e2f9a48387501c8a5cb80eac41d8c | [] | no_license | iwenzhou/pay | cd505d97ad7fd1865c336af8394f820c5d61044a | 5fde4c7c1d68603fc2d74d223f486f9e134efeeb | refs/heads/master | 2020-04-10T19:03:07.413585 | 2017-12-05T07:35:49 | 2017-12-05T07:35:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 808 | java | package com.pay.manger.controller.job;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.pay.business.tx.service.TxPayOrderClearService;
@Component
@Controller
@RequestMapping("/TxPayOrderClearJob")
public class TxPayOrderClearJob {
@Autowired
private TxPayOrderClearService txPayOrderClearService;
/**
* startUp
* 每小时执行订单统计
* void 返回类型
*/
@RequestMapping("/startUp")
public void startUp() {
Date d = new Date(new Date().getTime()-24*60*60*1000);
try {
txPayOrderClearService.job(d);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| [
"zhoulibo_vip@163.com"
] | zhoulibo_vip@163.com |
7e3e220d88d5ce8649048cbc6c9202361918711e | 52d800f3bc17a6f2070707c6df8714aea66fe193 | /GestionEcole/build/classes/Modele/ReportCardDetail.java | 8811b6136ed8c0f9c0950fdfe0c41ab627f142cf | [] | no_license | Epitimiah/Projet_Java | b8041550b78fd544077bffdee9380f54f8bae78d | 1076d50334e89e9c9c871895cb204e80abe31d9e | refs/heads/master | 2020-05-30T05:23:47.877628 | 2019-06-09T13:33:29 | 2019-06-09T13:33:29 | 189,557,261 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,199 | java | package Modele;
/**
* Classe pour acceder a la table "reportcarddetail" dans la base de donnees
* @author Adrien Lea Levanah
*/
public class ReportCardDetail {
private int id = 0;
private int idReportCard = 0;
private int idCourse = 0;
private String comment = "";
public ReportCardDetail(int id, int idReportCard, int idCourse, String comment){
this.id = id;
this.idReportCard = idReportCard;
this.idCourse = idCourse;
this.comment = comment;
}
public ReportCardDetail(){}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public int getIdRC(){
return idReportCard;
}
public void setIdRC(int idRC){
this.idReportCard = idRC;
}
public int getIdCourse(){
return idCourse;
}
public void setIdCourse(int idCourse){
this.idCourse = idCourse;
}
public String getComment(){
return comment;
}
public void setComment(String comment){
this.comment = comment;
}
@Override
public String toString() {
return "" + this.comment;
}
}
| [
"alchemist.audiotool@gmail.com"
] | alchemist.audiotool@gmail.com |
3c211c72d9eae8c8a941a93b9f07d37415d1b78c | 88d0fe4c32b01e5f32ca60e80ffacf59cfb3f449 | /PushTest/app/src/main/java/irshx/com/pushtest/MainActivity.java | d601e1ef32a91907766cd84e9fee7bf84d8c3abc | [] | no_license | UCM-FEG-IT/tarefa-1-programacao-movel-irshx | e014fce4032328c2cc39a24606a89a29bbe14ded | 1edad5d2ab53392e41e2be817aa7d1400af1eb0a | refs/heads/master | 2020-03-26T08:58:49.237047 | 2018-09-12T23:54:09 | 2018-09-12T23:54:09 | 144,728,965 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 331 | java | package irshx.com.pushtest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
| [
"irshxx6@gmail.com"
] | irshxx6@gmail.com |
0cd6781993fc0093e0f3147a272e80e47e1eb3de | a9914626c19f4fbcb5758a1953a4efe4c116dfb9 | /L2JTW_DataPack_Ertheia/dist/game/data/scripts/handlers/targethandlers/Summon.java | c72b8c7c9b5a0da66f363660f40f0659360f914b | [] | no_license | mjsxjy/l2jtw_datapack | ba84a3bbcbae4adbc6b276f9342c248b6dd40309 | c6968ae0475a076080faeead7f94bda1bba3def7 | refs/heads/master | 2021-01-19T18:21:37.381390 | 2015-08-03T00:20:39 | 2015-08-03T00:20:39 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,567 | java | /*
* Copyright (C) 2004-2014 L2J DataPack
*
* This file is part of L2J DataPack.
*
* L2J DataPack is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* L2J DataPack 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, see <http://www.gnu.org/licenses/>.
*/
package handlers.targethandlers;
import com.l2jserver.gameserver.handler.ITargetTypeHandler;
import com.l2jserver.gameserver.model.L2Object;
import com.l2jserver.gameserver.model.actor.L2Character;
import com.l2jserver.gameserver.model.skills.Skill;
import com.l2jserver.gameserver.model.skills.targets.L2TargetType;
/**
* Target Summon handler.
* @author UnAfraid
*/
public class Summon implements ITargetTypeHandler
{
@Override
public L2Object[] getTargetList(Skill skill, L2Character activeChar, boolean onlyFirst, L2Character target)
{
if (activeChar.hasSummon())
{
return new L2Character[]
{
activeChar.getSummon()
};
}
return EMPTY_TARGET_LIST;
}
@Override
public Enum<L2TargetType> getTargetType()
{
return L2TargetType.SUMMON;
}
}
| [
"rocknow@9bd44e3e-6552-0410-907e-a6ca40b856b6"
] | rocknow@9bd44e3e-6552-0410-907e-a6ca40b856b6 |
dfe4d6b92ef2055eb1b1a534aa204b7a52adf3a9 | 2e3870ec74be3d5284130e60a0852a7d4479d296 | /app/src/main/java/com/ming/androblog/models/User.java | a267cf50feedca385c83a4f6aaf8e64fe39764a0 | [] | no_license | markhuang0521/AndroBlog | ebc89d1e659f953f2e6e3d06a3c0fea413dbc2d0 | 3ab8298eea0ce2edbd5374d6928716868ac6ae55 | refs/heads/master | 2022-12-22T21:41:24.837176 | 2020-10-04T02:15:11 | 2020-10-04T02:15:11 | 301,022,984 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,303 | java | package com.ming.androblog.models;
import java.util.HashMap;
import java.util.Map;
public class User {
public static final String REF_USER = "users";
public static final String COL_USER_ID = "userId";
public static final String COL_USER_IMAGE = "imageUrl";
public static final String COL_USER_NAME = "userName";
private String userId;
private String userName;
private String imageUrl;
public User() {
}
public User(String userId, String userName, String imageUrl) {
this.userId = userId;
this.userName = userName;
this.imageUrl = imageUrl;
}
public Map<String, Object> toMap() {
Map<String, Object> data = new HashMap<>();
data.put("imageUrl", imageUrl);
data.put("userId", userId);
data.put("userName", userName);
return data;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
| [
"markhuang286@gmail.com"
] | markhuang286@gmail.com |
768dc678100af00741e3781184d2dd61397f9e7b | e39cefeecde17598ffa5494b89a5129cdfffe99c | /src/main/java/com/numberToword/exception/ValidationException.java | ce43bcd3069d2555e7aa734021a0ed65a0b4aeac | [] | no_license | gurumandapati/assignment | 84f128ee5567875ce79ea9f37c6645c55a522f9d | 569facf24bc7f447daca2d340b98c01fdb028c6a | refs/heads/master | 2021-07-06T12:46:13.765437 | 2019-06-30T17:37:19 | 2019-06-30T17:37:19 | 194,524,032 | 0 | 0 | null | 2020-10-13T14:19:30 | 2019-06-30T14:16:14 | Java | UTF-8 | Java | false | false | 219 | java | package com.numberToword.exception;
public class ValidationException extends Exception{
private static final long serialVersionUID = 1L;
public ValidationException(String message) {
super(message);
}
}
| [
"guru.raju29@gmail.com"
] | guru.raju29@gmail.com |
474964bd963260e6e6626485e0a2e903ee068def | b933eb80e206c1da787c02250261ae676aa160fd | /src/test/java/fr/chocolateroad/shop/web/rest/errors/ExceptionTranslatorTestController.java | 65570d02dd6b0e128f8eee4ed8c646bc03749dc0 | [] | no_license | jmcrommen/tp-jhipster-shop | 7cd1d39df1be8f1eff2dcb68361880f5ea89f2dd | abff40bc1c78542270003059c39a60a4524dc16d | refs/heads/master | 2020-05-22T10:32:17.669711 | 2019-05-12T22:48:55 | 2019-05-12T22:48:55 | 186,312,148 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,132 | java | package fr.chocolateroad.shop.web.rest.errors;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.Map;
@RestController
public class ExceptionTranslatorTestController {
@GetMapping("/test/concurrency-failure")
public void concurrencyFailure() {
throw new ConcurrencyFailureException("test concurrency failure");
}
@PostMapping("/test/method-argument")
public void methodArgument(@Valid @RequestBody TestDTO testDTO) {
}
@GetMapping("/test/missing-servlet-request-part")
public void missingServletRequestPartException(@RequestPart String part) {
}
@GetMapping("/test/missing-servlet-request-parameter")
public void missingServletRequestParameterException(@RequestParam String param) {
}
@GetMapping("/test/access-denied")
public void accessdenied() {
throw new AccessDeniedException("test access denied!");
}
@GetMapping("/test/unauthorized")
public void unauthorized() {
throw new BadCredentialsException("test authentication failed!");
}
@GetMapping("/test/response-status")
public void exceptionWithResponseStatus() {
throw new TestResponseStatusException();
}
@GetMapping("/test/internal-server-error")
public void internalServerError() {
throw new RuntimeException();
}
public static class TestDTO {
@NotNull
private String test;
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
}
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "test response status")
@SuppressWarnings("serial")
public static class TestResponseStatusException extends RuntimeException {
}
}
| [
"JCrommen@cincom.com"
] | JCrommen@cincom.com |
fc2b0fe97170faa098138412b964aeff464d81f3 | 1c6a54d8091da636f5dc99d121c853f586050ef1 | /app/src/main/java/com/diss/cabadvertisement/ui/presenter/LoginPresenter.java | 4806da20319109fe87e584df4d11fa7a2ec1c19e | [] | no_license | Shyamyaduwanshi-desired/CabAdvertisement | ee380917d15b4d4960beacd910a66ff2aebc463e | 8cab4ec945fc067b542b866bb757ba34a9921f08 | refs/heads/master | 2020-06-27T16:20:50.392726 | 2019-08-29T06:23:31 | 2019-08-29T06:23:31 | 199,995,840 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 17,136 | java | package com.diss.cabadvertisement.ui.presenter;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;
import com.diss.cabadvertisement.ui.Approval_activity;
import com.diss.cabadvertisement.ui.DashboardActivity;
import com.diss.cabadvertisement.ui.LoginActivity;
import com.diss.cabadvertisement.ui.OtpActivity;
import com.diss.cabadvertisement.ui.SubscriptionPlanActivity;
import com.diss.cabadvertisement.ui.util.AppData;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginPresenter {
private Context context;
private Login login;
private AppData appData;
public LoginPresenter(Context context, Login login) {
this.context = context;
this.login = login;
appData = new AppData(context);
AndroidNetworking.initialize(context);
}
public interface Login{
void success(String response, String diff_, String otp);
void error(String response);
void fail(String response);
}
public void LoginUser(final String phone, final String password, final String deviceToken) {//, final String deviceToken
final ProgressDialog progress = new ProgressDialog(context);
progress.setMessage("Please Wait..");
progress.setCancelable(false);
progress.show();
AndroidNetworking.post(AppData.url)
.addBodyParameter("action", "login")
.addBodyParameter("mobile_no", phone)
.addBodyParameter("password", password)
.addBodyParameter("device_token", deviceToken)
.addBodyParameter("device_type", "android")
.addHeaders("Username","admin")
.addHeaders("Password","admin123")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject reader) {
// do anything with response
progress.dismiss();
try {
String status = reader.getString("code");
String msg = reader.getString("message");
Log.e("","login output json= "+reader.toString());
if(status.equals("200")){
appData.setUserID(reader.getJSONObject("body").getString("ID"));
appData.setUsername(reader.getJSONObject("body").getString("display_name"));
appData.setEmail(reader.getJSONObject("body").getString("user_email"));
appData.setUserStatus(reader.getJSONObject("body").getString("user_status"));
appData.setMobile(reader.getJSONObject("body").getString("user_phone"));
appData.setProfilePic(reader.getJSONObject("body").getString("user_pic_full"));
appData.setCompanyNm(reader.getJSONObject("body").getString("company_name"));
appData.setCompanyOfficeAddress(reader.getJSONObject("body").getString("company_office_address"));
appData.setCompanyContactNo(reader.getJSONObject("body").getString("company_contact_no"));
appData.setCompanyAreaOfBusiness(reader.getJSONObject("body").getString("company_area_of_business"));
appData.setCurrentCampaignId("3");//dummy data
String userStatus=reader.getJSONObject("body").getString("user_status");
String otp="";
switch (userStatus)
{
case "0"://not verify otp
appData.setForGotUserId(reader.getJSONObject("body").getString("ID"));
otp=reader.getJSONObject("body").getString("otp");
break;
case "1"://verified otp but not approve by admin
break;
case "2":// approved by admin
break;
case "3":// not subscription done by user
break;
case "4"://subscription done by user
break;
}
login.success(msg,userStatus,otp);
}else {
login.error(msg);
}
} catch (JSONException e) {
e.printStackTrace();
login.fail("Something went wrong. Please try after some time.");
}
}
@Override
public void onError(ANError error) {
// handle error
progress.dismiss();
login.fail("Something went wrong. Please try after some time.");
}
});
}
public void ForgotPass(final String phone) {
final ProgressDialog progress = new ProgressDialog(context);
progress.setMessage("Please Wait..");
progress.setCancelable(false);
progress.show();
AndroidNetworking.post(AppData.url)
.addBodyParameter("action", "forgot_password")
.addBodyParameter("mobile_no", phone)
.addHeaders("Username","admin")
.addHeaders("Password","admin123")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject reader) {
// do anything with response
if (progress!=null)
progress.dismiss();
try {
String status = reader.getString("code");
String msg = reader.getString("message");
Log.e("","Forgot output json= "+reader.toString());
if(status.equals("200")){
appData.setForGotUserId(reader.getJSONObject("body").getString("ID"));
login.success(msg,reader.getJSONObject("body").getString("ID"),reader.getJSONObject("body").getString("otp"));
}else {
login.error(msg);
}
} catch (JSONException e) {
e.printStackTrace();
login.fail("Something went wrong. Please try after some time.");
}
}
@Override
public void onError(ANError error) {
// handle error
if (progress!=null)
progress.dismiss();
login.fail("Something went wrong. Please try after some time.");
}
});
}
public void ResetPass(final String newPass,final String confirmPass) {
final ProgressDialog progress = new ProgressDialog(context);
progress.setMessage("Please Wait..");
progress.setCancelable(false);
progress.show();
AndroidNetworking.post(AppData.url)
.addBodyParameter("action", "reset_password")
.addBodyParameter("new_pass", newPass)
.addBodyParameter("confirm_new_pass", confirmPass)
.addBodyParameter("user_id", appData.getForGotUserId())
.addHeaders("Username","admin")
.addHeaders("Password","admin123")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject reader) {
// do anything with response
if (progress!=null)
progress.dismiss();
try {
String status = reader.getString("code");
String msg = reader.getString("message");
Log.e("","Reset output json= "+reader.toString());
if(status.equals("200")){
appData.setForGotUserId("NA");
login.success(msg,"","");
}else {
login.error(msg);
}
} catch (JSONException e) {
e.printStackTrace();
login.fail("Something went wrong. Please try after some time.");
}
}
@Override
public void onError(ANError error) {
// handle error
if (progress!=null)
progress.dismiss();
login.fail("Something went wrong. Please try after some time.");
}
});
}
public void ResendOTP(final String phone) {
final ProgressDialog progress = new ProgressDialog(context);
progress.setMessage("Please Wait..");
progress.setCancelable(false);
progress.show();
AndroidNetworking.post(AppData.url)
.addBodyParameter("action", "resend_otp")
.addBodyParameter("mobile_no", phone)
.addHeaders("Username","admin")
.addHeaders("Password","admin123")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject reader) {
// do anything with response
if (progress!=null)
progress.dismiss();
try {
String status = reader.getString("code");
String msg = reader.getString("message");
Log.e("","resend OTP output json= "+reader.toString());
if(status.equals("200")){
login.success(msg,"",reader.getJSONObject("body").getString("otp"));
}else {
login.error(msg);
}
} catch (JSONException e) {
e.printStackTrace();
login.fail("Something went wrong. Please try after some time.");
}
}
@Override
public void onError(ANError error) {
// handle error
if (progress!=null)
progress.dismiss();
login.fail("Something went wrong. Please try after some time.");
}
});
}
public void VerifyOTP(final String userid, final String deviceToken) {
final ProgressDialog progress = new ProgressDialog(context);
progress.setMessage("Please Wait..");
progress.setCancelable(false);
progress.show();
AndroidNetworking.post(AppData.url)
.addBodyParameter("action", "otp_verify")
.addBodyParameter("user_id", userid)
.addBodyParameter("device_token", deviceToken)
.addBodyParameter("device_type", "android")
.addHeaders("Username","admin")
.addHeaders("Password","admin123")
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject reader) {
// do anything with response
if (progress!=null)
progress.dismiss();
try {
String status = reader.getString("code");
String msg = reader.getString("message");
Log.e("","vefify OTP output json= "+reader.toString());
if(status.equals("200")){
appData.setUserStatus(reader.getJSONObject("body").getString("user_status"));
login.success(msg,"1","");//verified
}else {
login.error(msg);
}
} catch (JSONException e) {
e.printStackTrace();
login.fail("Something went wrong. Please try after some time.");
}
}
@Override
public void onError(ANError error) {
// handle error
if (progress!=null)
progress.dismiss();
login.fail("Something went wrong. Please try after some time.");
}
});
}
/*public void LoginVendor(final String phone, final String password) {
final ProgressDialog progress = new ProgressDialog(context);
progress.setMessage("Login Please Wait..");
progress.setCancelable(false);
progress.show();
StringRequest postRequest = new StringRequest(Request.Method.POST, AppData.url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
progress.dismiss();
try {
JSONObject reader = new JSONObject(response);
String status = reader.getString("code");
String msg = reader.getString("message");
Log.e("","login output json= "+reader.toString());
if(status.equals("200")){
appData.setUserID(reader.getJSONObject("body").getString("ID"));
appData.setUsername(reader.getJSONObject("body").getString("display_name"));
appData.setEmail(reader.getJSONObject("body").getString("user_email"));
login.success(msg,"");
}else {
login.error(msg);
}
} catch (JSONException e) {
e.printStackTrace();
login.fail("Something went wrong. Please try after some time.");
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
progress.dismiss();
login.fail("Server Error.\n Please try after some time.");
}
}
) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("action", "login");
params.put("mobile_no", "+919893160596");
params.put("password", "admin123");
// params.put("username", phone);
// params.put("password", password);
Log.e("","Input param= "+params.toString());
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
params.put("Username","admin");
params.put("Password","admin123");
Log.e("","header param= "+params.toString());
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(context);
queue.add(postRequest);
}*/
}
| [
"shyam.desired@gmail.com"
] | shyam.desired@gmail.com |
0b0b6fcbbae9b11ea9c7564b247e8607583d1571 | e12e559a882a9b4e5e769fee9e3ab92f1783bae9 | /app/src/main/java/com/fdc/pixelcare/Views/CustomTextView.java | 095e1258a0e4c0f0d898dfa7fdff8808c2202732 | [] | no_license | Salma15/pixelcareBeta_app | 9db0818fc7319c5c66ffcd4c608487072b339d2a | a411187d2b01c65c893df0c4331b670e005460a6 | refs/heads/master | 2020-05-25T13:41:13.145712 | 2019-06-10T06:23:55 | 2019-06-10T06:23:55 | 187,826,858 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 835 | java | package com.fdc.pixelcare.Views;
import android.content.Context;
import android.graphics.Typeface;
import android.support.v7.widget.AppCompatTextView;
import android.util.AttributeSet;
/**
* Created by lenovo on 03-03-2017.
*/
public class CustomTextView extends AppCompatTextView {
public CustomTextView(Context context) {
super(context);
setFont();
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
setFont();
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFont();
}
private void setFont() {
Typeface font = Typeface.createFromAsset(getContext().getAssets(), "fonts/Roboto-Regular.ttf");
setTypeface(font, Typeface.NORMAL);
}
}
| [
"pai.shashidhar@gmail.com"
] | pai.shashidhar@gmail.com |
966f424dafc0db4c00b807ab9a38c1a6b879325b | 976f32e2d212d6f5978911813f1bc9aef363be62 | /dao/ProfilDao.java | 1036acfc98cfe468af6d10a93a2ceb4c26214c44 | [] | no_license | Marema1/projet_java_wari_ism | 24202276d1cda57b8051b285eec67bc889191ce7 | 4850e99fbe4b3e17fd48812da612569635d043c8 | refs/heads/master | 2020-09-27T18:41:15.724117 | 2019-12-07T22:13:54 | 2019-12-07T22:13:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,671 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import models.Profil;
/**
*
* @author hp
*/
public class ProfilDao implements ISystem<Profil> {
private DaoMysql dao;
private final String SQL_INSERT="INSERT INTO `profil` (`id_profil`, `libelle`) VALUES (NULL, ?)";
private final String SQL_UPDATE="UPDATE `profil` SET `libelle` = ? WHERE `profil`.`id_profil` =?";
private final String SQL_SELECT_ONE="select * from profil where id_profil=?";
private final String SQL_SELECT_ALL="select * from profil";
private final String SQL_SELECT_LIBELLE="select * from profil where libelle=?";
public ProfilDao() {
dao= DaoMysql.getInstance();
}
@Override
public int create(Profil obj) {
int result=0;
try {
dao.initPS(SQL_INSERT);
//Injecter les Valeurs dans la requete
//ORM Objet vers Table
dao.getPstm().setString(1, obj.getLibelle());
result= dao.executeMaj();
} catch (SQLException ex) {
System.out.println("Erreur Connexion à la BD");
}
return result;
}
@Override
public int update(Profil obj) {
int result=0;
try {
/* Execution requete */
//PreparedStatement ps=connexion.prepareStatement(sql);
dao.initPS(SQL_UPDATE);
//ps.setString(1, obj.getLibelle());
dao.getPstm().setString(1, obj.getLibelle());
dao.getPstm().setInt(2, obj.getId());
result=dao.executeMaj();
} catch (SQLException ex) {
System.out.println("Erreur Connexion à la BD");
}
return result;
}
@Override
public Profil findById(int id) {
Profil result=null;
try {
result=new Profil();
dao.initPS(SQL_SELECT_ONE);
/* Execution requete */
dao.getPstm().setInt(1, id);
//ORM table vers Objet
ResultSet rs=dao.executeSelect();
if(rs.first()){
result.setId(rs.getInt("id_profil"));
result.setLibelle(rs.getString("libelle"));
}
dao.CloseConnection();
} catch (SQLException ex) {
System.out.println("Erreur Connexion à la BD");
}
return result;
}
@Override
public List<Profil> findAll() {
List<Profil> result=null;
try {
result=new ArrayList<>();
dao.initPS(SQL_SELECT_ALL);
ResultSet rs=dao.executeSelect();
while(rs.next()){
Profil p=new Profil();
p.setId(rs.getInt("id_profil"));
p.setLibelle(rs.getString("libelle"));
result.add(p);
}
} catch (SQLException ex) {
System.out.println("Erreur Connexion à la BD");
}
return result;
}
public Profil findByLibelle(String libelle) {
Profil result=null;
try {
result=new Profil();
dao.initPS(SQL_SELECT_LIBELLE);
/* Execution requete */
dao.getPstm().setString(1, libelle);
ResultSet rs=dao.executeSelect();
if(rs.next()){
result.setId(rs.getInt("id_profil"));
result.setLibelle(rs.getString("libelle"));
}
dao.CloseConnection();
} catch (SQLException ex) {
System.out.println("Erreur Connexion à la BD");
}
return result;
}
}
| [
"noreply@github.com"
] | noreply@github.com |
636d96e29053025eeb9ddb3ffb868a5e4e335c6f | c677b223a06cf8481986006a5be4a3b66e587a13 | /src/controle/ConexaoBD.java | d7ab8aba840e60e4826e05bb379fefde9e597a88 | [] | no_license | gabriell15/Projeto-Engenharia | 44baeb9b1de0ab2502fe137e13620ecbd8285596 | 09d17d7ff36c50c62a79e906af90cec46386623e | refs/heads/master | 2023-05-02T08:08:15.005215 | 2021-05-29T23:53:21 | 2021-05-29T23:53:21 | 371,005,387 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,698 | java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controle;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* @author Gabriel Ferreira
*/
public class ConexaoBD {
public Statement stn;
public ResultSet rs;
private String driver = "org.postgresql.Driver";
private String caminho = "jdbc:postgresql://localhost:5432/Engenharia";
private String usuario = "postgres";
private String senha = "saopaulo15";
Connection con;
public void conexao(){
try {
System.setProperty("jdbc.Drivers", driver);
con = DriverManager.getConnection(caminho, usuario, senha );
JOptionPane.showMessageDialog(null, "Conexão efetuada com sucesso!!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro de Conexão :\n"+ex.getMessage());
}
}
public void executaSql(String sql){
try {
stn = con.createStatement(rs.TYPE_SCROLL_INSENSITIVE, rs.CONCUR_READ_ONLY);
rs = stn.executeQuery(sql);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao executa sql Conexão :\n"+ex.getMessage());
}
}
public void desconecta(){
try {
con.close();
JOptionPane.showMessageDialog(null, "Desconectado com sucesso!!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao fechar a conexão com o banco de dados: \n"+ex.getMessage());
}
}
}
/*public class ConexaoBD {
private String caminho = "127.0.0.1";
private String porta= "3306";
private String nome= "Teste";
private String usuario = "root";
private String senha = "";
private String URL= "jdbc:mysql://"+caminho+":"+porta+"/"+nome+"?useTimezone=true&serverTimezone=GMT";
public static ConexaoBD getConnection(){
ConexaoBD conexaoBD= null;
if(ConexaoBD == null){
conexaoBD= new ConexaoBD();
return new ConexaoBD();
}else {
return null;
}
}
public void Conn() {
try{
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection(URL, usuario, senha);
}
catch(Exception ex){
System.err.println("Erro ao conectar"+ex);
}
}
}
*/
| [
"gabrielspfc38@gmail.com"
] | gabrielspfc38@gmail.com |
63946719be2e5523ed0eae17059e18a730cd5776 | 5b82e2f7c720c49dff236970aacd610e7c41a077 | /QueryReformulation-master 2/data/processed/DisplayHelpHandler.java | 7e880e4281b4d8fdfa1c4079a65c69299e35a9c2 | [] | no_license | shy942/EGITrepoOnlineVersion | 4b157da0f76dc5bbf179437242d2224d782dd267 | f88fb20497dcc30ff1add5fe359cbca772142b09 | refs/heads/master | 2021-01-20T16:04:23.509863 | 2016-07-21T20:43:22 | 2016-07-21T20:43:22 | 63,737,385 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,020 | java | /***/
package org.eclipse.ui.internal.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.help.IWorkbenchHelpSystem;
/**
* Displays the help resource specified in the <code>href</code> command
* parameter or simply displays the help bookshelf if no parameter was passed.
*
* @since 3.2
*/
public final class DisplayHelpHandler extends AbstractHandler {
/**
* The identifier of the command parameter for the URI to oepn.
*/
//$NON-NLS-1$
private static final String PARAM_ID_HREF = "href";
@Override
public final Object execute(final ExecutionEvent event) {
final IWorkbenchHelpSystem helpSystem = PlatformUI.getWorkbench().getHelpSystem();
final String href = event.getParameter(PARAM_ID_HREF);
if (href == null) {
helpSystem.displayHelp();
} else {
helpSystem.displayHelpResource(href);
}
return null;
}
}
| [
"muktacseku@gmail.com"
] | muktacseku@gmail.com |
68cb4d4d77045d5b59518091c0c174afcc4ba809 | 5b1f0a5dcc273c098157d1727207680cc293df52 | /src/main/java/br/com/zup/marvel/dto/SeriesDTO.java | df4f5bc4faa63ba16a102031e75610f3a81f5381 | [] | no_license | vagouveia/marvelapirest | d09dff2a6557aa001b29d3378f7413ab77f7d30c | cab78b752b2b5d1be7880c9a06b8a317270b45c9 | refs/heads/main | 2023-06-11T19:56:06.627137 | 2021-07-05T19:23:58 | 2021-07-05T19:23:58 | 380,556,214 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,128 | java | package br.com.zup.marvel.dto;
import java.util.Date;
import java.util.List;
public class SeriesDTO {
private Long id;
private String title;
private String description;
private String resourceURI;
private List<UrlDTO> urls;
private Integer startYear;
private Integer endYear;
private String rating;
private Date modified;
private ImageDTO thumbnail;
private ComicListDTO comicLists;
private StoryListDTO storyLists;
private EventListDTO eventLists;
private CharacterListDTO characterList;
private CreatorListDTO creatorList;
private SeriesSummaryDTO next;
private SeriesSummaryDTO previous;
private Integer available;
private Integer returned;
private String collectionURI;
private List<SeriesSummaryDTO> items;
public SeriesDTO(Long id, String title, String description, String resourceURI, List<UrlDTO> urls,
Integer startYear, Integer endYear, String rating, Date modified, ImageDTO thumbnail,
ComicListDTO comicLists, StoryListDTO storyLists, EventListDTO eventLists, CharacterListDTO characterList,
CreatorListDTO creatorList, SeriesSummaryDTO next, SeriesSummaryDTO previous, Integer available,
Integer returned, String collectionURI, List<SeriesSummaryDTO> items) {
super();
this.id = id;
this.title = title;
this.description = description;
this.resourceURI = resourceURI;
this.urls = urls;
this.startYear = startYear;
this.endYear = endYear;
this.rating = rating;
this.modified = modified;
this.thumbnail = thumbnail;
this.comicLists = comicLists;
this.storyLists = storyLists;
this.eventLists = eventLists;
this.characterList = characterList;
this.creatorList = creatorList;
this.next = next;
this.previous = previous;
this.available = available;
this.returned = returned;
this.collectionURI = collectionURI;
this.items = items;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getResourceURI() {
return resourceURI;
}
public List<UrlDTO> getUrls() {
return urls;
}
public Integer getStartYear() {
return startYear;
}
public Integer getEndYear() {
return endYear;
}
public String getRating() {
return rating;
}
public Date getModified() {
return modified;
}
public ImageDTO getThumbnail() {
return thumbnail;
}
public ComicListDTO getComicLists() {
return comicLists;
}
public StoryListDTO getStoryLists() {
return storyLists;
}
public EventListDTO getEventLists() {
return eventLists;
}
public CharacterListDTO getCharacterList() {
return characterList;
}
public CreatorListDTO getCreatorList() {
return creatorList;
}
public SeriesSummaryDTO getNext() {
return next;
}
public SeriesSummaryDTO getPrevious() {
return previous;
}
public Integer getAvailable() {
return available;
}
public Integer getReturned() {
return returned;
}
public String getCollectionURI() {
return collectionURI;
}
public List<SeriesSummaryDTO> getItems() {
return items;
}
}
| [
"vitorg@kyros.com.br"
] | vitorg@kyros.com.br |
ef7288c6f222d633749e34a04dc06c6a51813ad8 | d36ddc29363c42b15b5b580838ebdf695d4d02dd | /src/general/EffectivelyFinal.java | fa6e7d4060c48b795718f565cb369d50c7a8aa1f | [] | no_license | marcin-kosmalski/java8 | 8772dc955eacd63bdd9968dc51e18725ad3d9e1f | 018e5ed063721ddab94b01140158c3d4e32e007f | refs/heads/master | 2021-01-21T21:39:49.042019 | 2016-03-19T19:21:46 | 2016-03-19T19:21:46 | 40,875,640 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 837 | java | package general;
public class EffectivelyFinal {
public static void main(String[] args) {
// new Test1().effectivelyFinal();
new EffectivelyFinal().effectivelyFinal2();
}
public void effectivelyFinal() {
int var = 8;
Runnable runnable = () -> {
System.out.println("effecively final: " + var);
System.out.println(this);
};
// effecively final - modification not possible
// var=9;
new Thread(runnable).start();
}
public void effectivelyFinal2() {
class Bin {
public String value = "init";
}
Bin bin = new Bin();
Runnable runnable = () -> {
bin.value = "kkk";
System.out.println(this);
};
Thread thread = new Thread(runnable);
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(bin.value);
}
}
| [
"marcin.kosmalski@gmail.com"
] | marcin.kosmalski@gmail.com |
c34948a1be41682a33d2179b64403dc1a3705cc7 | d71e0d7a1f7f2307100b221686e18e4399fc6f00 | /src/main/java/com/purat/HelloWorld.java | f39f5d34ee6af7c396cb49968f604b0b81681329 | [] | no_license | compurat/Test | dc8e853a78a1fb8883f59122eeb827b413762c66 | b81ff1f259487304cbf32e94bde39b310fda21e4 | refs/heads/master | 2021-01-10T13:11:57.267279 | 2015-11-24T20:34:12 | 2015-11-24T20:34:12 | 46,817,008 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 359 | java | package com.purat;
import org.springframework.stereotype.Component;
/**
* Created by compurat on 11/24/15.
*/
@Component
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
| [
"pieter.roskam1@ahold.com"
] | pieter.roskam1@ahold.com |
6827bce95551d90b4d33d794aedfdd53bb2f0713 | cc2ec8f019b7f719fc99f21a0e28667cd993bd37 | /VeterinariaFinal1/src/epis/unsa/sugerencia/sugerenciaBorrar.java | ec8944aef6c2eabe381c094ec698599f97abb786 | [] | no_license | proyectoweb2/ProVeterinaria | c84358e5a0c93f79d1d7b455a77e7c4f13c5e200 | fb2891cae9b673df81154b82c58d141fbd01f084 | refs/heads/master | 2020-05-17T08:31:01.735811 | 2015-06-24T22:52:09 | 2015-06-24T22:52:09 | 38,015,286 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,369 | java | package epis.unsa.sugerencia;
import java.io.IOException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class sugerenciaBorrar extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain");
if( req.getParameter("num")!=null ){
int numero = Integer.parseInt(req.getParameter("num"));
final PersistenceManager pm = PMF.get().getPersistenceManager();
final Query q = pm.newQuery(Sugerencia.class);
q.setFilter("num == numParam");
q.declareParameters("int numParam");
try{
q.deletePersistentAll(numero);
resp.getWriter().println("Se han borrado personas.");
resp.sendRedirect("/sugerencialista");
}catch(Exception e){
System.out.println(e);
resp.getWriter().println("No se han podido borrar personas.");
resp.sendRedirect("/sugerencialista");
}finally{
q.closeAll();
pm.close();
}
}else {
resp.getWriter().println("No se ha especificado el color.");
resp.sendRedirect("/sugerencialista");
}
}
} | [
"poolmendoza0@gmail.com"
] | poolmendoza0@gmail.com |
10ced271d40504d81be0227ba463c23af7b451b6 | 2ae25775d0056a550c40f54fe1f8120a39694a26 | /src/main/java/org/orlounge/factory/ServiceFactory.java | 284fca1de6435aa27c970371c19ee0e030faaa0d | [] | no_license | PoojaShimpi/orlounge | b5c79cd87a13ea255556ca6a5d23e54317671ee6 | 2d1ca847426e736b0ca93d367c750519b8620349 | refs/heads/master | 2023-03-17T20:28:18.260983 | 2021-03-06T06:03:24 | 2021-03-06T06:03:24 | 337,763,205 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,496 | java | package org.orlounge.factory;
import lombok.Getter;
import lombok.Setter;
import org.orlounge.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by Satyam Soni on 9/15/2015.
*/
@Service
@Getter
@Setter
public class ServiceFactory {
@Autowired
private LoginService loginService;
@Autowired
private ForumService forumService;
@Autowired
private MessageBoardService messageBoardService;
@Autowired
private HospitalService hospitalService;
@Autowired
private GroupService groupService;
@Autowired
private StaffInfoService staffInfoService;
@Autowired
private CallScheduleService callScheduleService;
@Autowired
private ProcedureManualService procedureManualService;
@Autowired
private NoticeService noticeService;
@Autowired
private InServiceService inServiceService;
@Autowired
private PostOpService postOpService;
@Autowired
private ChecklistService checklistService;
@Autowired
private HandoverService handoverService;
@Autowired
private EventService eventService;
@Autowired
private PrefListService prefListService;
@Autowired
private ProjectService projectService;
@Autowired
private AnaesthesiaService anaesthesiaService;
@Autowired
private VoteService voteService;
@Autowired
private TagsService tagsService;
}
| [
"shimpipooja11@gmail.com"
] | shimpipooja11@gmail.com |
65ae2bbcb994f741c2809b5c2b3e80974903fbf6 | 8ec986726b3b60170aec4cb9772d3bdb163710af | /services/repository-managers/src/test/java/org/sagebionetworks/repo/manager/message/dataaccess/SubmissionMessageBuilderFactoryTest.java | d5a7011cbeec396e43ef71eba8fdec964a620c7c | [
"Apache-2.0"
] | permissive | marcomarasca/Synapse-Repository-Services | 871446d7bc8e27ca9f4e3d16c4f2007e3f69f5d3 | 294e6f422ef9a1367deaf511bc97473623233da4 | refs/heads/develop | 2023-08-17T12:25:54.442901 | 2023-08-16T15:40:47 | 2023-08-16T15:40:47 | 190,295,841 | 0 | 0 | Apache-2.0 | 2023-02-22T08:31:06 | 2019-06-04T23:55:19 | Java | UTF-8 | Java | false | false | 2,965 | java | package org.sagebionetworks.repo.manager.message.dataaccess;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sagebionetworks.markdown.MarkdownDao;
import org.sagebionetworks.repo.manager.message.BroadcastMessageBuilder;
import org.sagebionetworks.repo.model.dataaccess.Submission;
import org.sagebionetworks.repo.model.dbo.dao.dataaccess.SubmissionDAO;
import org.sagebionetworks.repo.model.message.ChangeType;
import org.sagebionetworks.repo.model.principal.PrincipalAliasDAO;
import org.springframework.test.util.ReflectionTestUtils;
public class SubmissionMessageBuilderFactoryTest {
@Mock
private PrincipalAliasDAO mockPrincipalAliasDAO;
@Mock
private MarkdownDao mockMarkdownDao;
@Mock
private SubmissionDAO mockSubmissionDao;
@Mock
private Submission mockSubmission;
SubmissionMessageBuilderFactory factory;
private Long actorUserId;
private String actorUsername;
private String objectId;
private String requirementId;
@Before
public void before(){
MockitoAnnotations.initMocks(this);
factory = new SubmissionMessageBuilderFactory();
ReflectionTestUtils.setField(factory, "principalAliasDAO", mockPrincipalAliasDAO);
ReflectionTestUtils.setField(factory, "markdownDao", mockMarkdownDao);
ReflectionTestUtils.setField(factory, "submissionDao", mockSubmissionDao);
actorUserId = 1L;
actorUsername = "username";
objectId = "123";
requirementId = "2";
when(mockPrincipalAliasDAO.getUserName(actorUserId)).thenReturn(actorUsername);
when(mockSubmissionDao.getSubmission(objectId)).thenReturn(mockSubmission);
when(mockSubmission.getAccessRequirementId()).thenReturn(requirementId);
}
@Test (expected = IllegalArgumentException.class)
public void testBuildWithInvalidObjectId() {
factory.createMessageBuilder(null, ChangeType.CREATE, actorUserId);
}
@Test (expected = IllegalArgumentException.class)
public void testBuildWithNullChangeType() {
factory.createMessageBuilder(objectId, null, actorUserId);
}
@Test (expected = IllegalArgumentException.class)
public void testBuildWithUpdateChangeType() {
factory.createMessageBuilder(objectId, ChangeType.UPDATE, actorUserId);
}
@Test (expected = IllegalArgumentException.class)
public void testBuildWithInvalidUserId() {
factory.createMessageBuilder(objectId, ChangeType.CREATE, null);
}
@Test
public void testBuild(){
ChangeType type = ChangeType.CREATE;
BroadcastMessageBuilder builder = factory.createMessageBuilder(objectId, type, actorUserId);
assertNotNull(builder);
assertTrue(builder instanceof SubmissionBroadcastMessageBuilder);
verify(mockPrincipalAliasDAO).getUserName(actorUserId);
}
}
| [
"kimyen0816@gmail.com"
] | kimyen0816@gmail.com |
476705c7ef39daa1f667457622387f0c3527d244 | cfc7628440e16a6b21b94391ba747f37bb8c8880 | /kenya-runner/src/main/java/com/github/jramsdale/kenya/ClasspathRunner.java | 6c4d106a4042930b0efe76cfeecc81c20b1552a5 | [] | no_license | jramsdale/kenya | f2bab296905146df38e14210664876a03e7ac4c6 | 48322f5734fb0cdcfb33f500354dff9f557f8265 | refs/heads/master | 2020-05-17T23:28:05.218441 | 2012-06-13T21:21:23 | 2012-06-13T21:21:23 | 2,033,357 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 404 | java | package com.github.jramsdale.kenya;
import java.io.File;
import com.google.common.base.Joiner;
public class ClasspathRunner extends AbstractRunner {
public ClasspathRunner() {
super();
}
@Override
protected void run(String[] args) {
System.out.println(Joiner.on(File.pathSeparatorChar).join(artifacts));
}
public static void main(String[] args) {
new ClasspathRunner().run(args);
}
}
| [
"jeff.ramsdale@gmail.com"
] | jeff.ramsdale@gmail.com |
e3a7eb162d50a2f5ba875ba3f09d27f73fac54c2 | 39fff770b53d43967b13f66c2eb65d9291aedb3d | /framework/src/main/java/com/ycy/framework/widget/BaseAdapter/listener/OnItemChildClickListener.java | ffdd74f50223ff82b4dd3be557712742d59e2856 | [] | no_license | ycyranqingjjs/ContentJavaApp | 084181138fa056f65d05de9b3d2925eea952979b | f95fc7830a1a90f4fc3e2309697750dfd7d741c0 | refs/heads/master | 2021-05-10T13:32:06.658841 | 2018-01-25T15:51:35 | 2018-01-25T15:51:35 | 118,479,132 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,055 | java | package com.ycy.framework.widget.BaseAdapter.listener;
import android.view.View;
import com.ycy.framework.widget.BaseAdapter.BaseQuickAdapter;
/**
* Created by AllenCoder on 2016/8/03.
* A convenience class to extend when you only want to OnItemChildClickListener for a subset
* of all the SimpleClickListener. This implements all methods in the
* {@link SimpleClickListener}
**/
public abstract class OnItemChildClickListener extends SimpleClickListener {
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
}
@Override
public void onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
}
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
onSimpleItemChildClick(adapter, view, position);
}
@Override
public void onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
}
public abstract void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position);
}
| [
"yichengyong@ztgame"
] | yichengyong@ztgame |
ffc187ca4e297d90ac28c7496a01f0e5977c9dc8 | e2af58790619e38a1ed89dfd9834eea11d92e339 | /app/src/main/java/com/deni/surat/network/endpoint/Biodata.java | 56331f064b24b02ca9edf9cd59ae18c2689f8bb0 | [] | no_license | deniace/surat_android | d9e85233090f216721bce660a5f58380472b30b1 | 541c4a475d33be70e7b3e5846709d2aa0c8b77fb | refs/heads/master | 2023-03-26T12:34:06.137341 | 2021-03-27T01:34:03 | 2021-03-27T01:34:03 | 350,784,625 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,702 | java | package com.deni.surat.network.endpoint;
import com.deni.surat.model.BiodataRequestPaging;
import com.deni.surat.model.BiodataResponseAll;
import com.deni.surat.model.BiodataResponseOne;
import com.deni.surat.model.BiodataResponsePaging;
import com.deni.surat.model.BiodataSingle;
import com.deni.surat.model.RegisterResponse;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
/**
* Created by Deni Supriyatna (deni ace) on 07 - 06 - 2020.
* Email : denisupriyatna01@gmail.com
*/
public interface Biodata {
@Headers("Content-Type: application/json")
@GET("profile")
Call<BiodataResponseAll> getProfileAll (@Header("Authorization") String token);
@Headers("Content-Type: application/json")
@POST("profile/paging")
Call<BiodataResponsePaging> getProfilePaging (@Header("Authorization") String token, @Body BiodataRequestPaging biodataRequestPaging);
@Headers("Content-Type: application/json")
@GET("profile/{idUser}")
Call<BiodataResponseOne> getProfileById (@Header("Authorization") String token, @Path("idUser") String idUser);
@Headers("Content-Type: application/json")
@PUT("profile/{idUser}")
Call<RegisterResponse> updateProfileById (@Header("Authorization") String token, @Body BiodataSingle biodataSingle, @Path("idUser") String idUser);
@Headers("Content-Type: application/json")
@DELETE("profile/{idUser}")
Call<RegisterResponse> deleteProfileById (@Header("Authorization") String token, @Path("idUser") String idUser);
}
| [
"denisupriyatna01@gmail.com"
] | denisupriyatna01@gmail.com |
9e958ad49de33b15b18f243fe77f7f05c87d757c | 21356b9e2871664ddc9828bd455fa5bf2a2e8d68 | /src/Block.java | 59426d1caf06ce7aafec36bc9552b5caa412b1dc | [
"MIT"
] | permissive | Biswajee/BlinkChain | 149cb58a630b1e07039abc32eaa5c9fb60decdcf | 7013470017cb772c369ed14b996b72d29a51e618 | refs/heads/master | 2020-04-23T10:07:25.368891 | 2019-10-06T15:52:24 | 2019-10-06T15:52:24 | 171,093,188 | 0 | 0 | null | 2019-10-06T15:52:25 | 2019-02-17T07:16:34 | Java | UTF-8 | Java | false | false | 1,160 | java | import java.util.Date;
public class Block {
public String hash;
public String previousHash;
private String data; //our data will be a simple message.
private long timeStamp; //as number of milliseconds since 1/1/1970.
private int nonce;
//Block Constructor.
public Block(String data,String previousHash ) {
this.data = data;
this.previousHash = previousHash;
this.timeStamp = new Date().getTime();
this.hash = calculateHash(); //Making sure we do this after we set the other values.
}
public String calculateHash() {
String calculatedhash = StringUtil.applySha256(
previousHash +
Long.toString(timeStamp) +
data
);
return calculatedhash;
}
public void mineBlock(int difficulty) {
String target = new String(new char[difficulty]).replace('\0', '0'); //Create a string with difficulty * "0"
while(!hash.substring( 0, difficulty).equals(target)) {
nonce ++;
hash = calculateHash();
}
System.out.println("Block Mined!!! : " + hash);
}
} | [
"roy.biswajeet161@gmail.com"
] | roy.biswajeet161@gmail.com |
bd03f09ad877800e07d141ba6ec2199991ea23b8 | adeaabe436c7c94ecfffe48e0d3d76ad1301ffa4 | /BreakdownSeq.java | bd244e94da9b2d2212712dd3501768411c531702 | [] | no_license | PanCakeMan/CPTS564 | 91ed11eef3f6af3bf460ad9234c47e304d496bad | a1de06e1692c2b740d478d05b0b42973bf9de04f | refs/heads/master | 2020-03-14T01:29:16.524269 | 2018-05-01T22:45:56 | 2018-05-01T22:45:56 | 131,378,396 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,206 | java |
/*
WARNING: THIS FILE IS AUTO-GENERATED. DO NOT MODIFY.
This file was generated from .idl using "rtiddsgen".
The rtiddsgen tool is part of the RTI Connext distribution.
For more information, type 'rtiddsgen -help' at a command shell
or consult the RTI Connext manual.
*/
import java.util.Collection;
import com.rti.dds.infrastructure.Copyable;
import com.rti.dds.util.Enum;
import com.rti.dds.util.Sequence;
import com.rti.dds.util.LoanableSequence;
/**
* A sequence of Breakdown instances.
*/
public final class BreakdownSeq extends LoanableSequence implements Copyable {
// -----------------------------------------------------------------------
// Package Fields
// -----------------------------------------------------------------------
/**
* When a memory loan has been taken out in the lower layers of
* RTI Data Distribution Service, store a pointer to the native sequence here.
* That way, when we call finish(), we can give the memory back.
*/
/*package*/ transient Sequence _loanedInfoSequence = null;
// -----------------------------------------------------------------------
// Public Fields
// -----------------------------------------------------------------------
// --- Constructors: -----------------------------------------------------
public BreakdownSeq() {
super(Breakdown.class);
}
public BreakdownSeq (int initialMaximum) {
super(Breakdown.class, initialMaximum);
}
public BreakdownSeq (Collection elements) {
super(Breakdown.class, elements);
}
public Breakdown get(int index) {
return (Breakdown) super.get(index);
}
// --- From Copyable: ----------------------------------------------------
/**
* Copy data into <code>this</code> object from another.
* The result of this method is that both <code>this</code>
* and <code>src</code> will be the same size and contain the
* same data.
*
* @param src The Object which contains the data to be copied
* @return <code>this</code>
* @exception NullPointerException If <code>src</code> is null.
* @exception ClassCastException If <code>src</code> is not a
* <code>Sequence</code> OR if one of the objects contained in
* the <code>Sequence</code> is not of the expected type.
* @see com.rti.dds.infrastructure.Copyable#copy_from(java.lang.Object)
*/
public Object copy_from(Object src) {
Sequence typedSrc = (Sequence) src;
final int srcSize = typedSrc.size();
final int origSize = size();
// if this object's size is less than the source, ensure we have
// enough room to store all of the objects
if (getMaximum() < srcSize) {
setMaximum(srcSize);
}
// trying to avoid clear() method here since it allocates memory
// (an Iterator)
// if the source object has fewer items than the current object,
// remove from the end until the sizes are equal
if (srcSize < origSize){
removeRange(srcSize, origSize);
}
// copy the data from source into this (into positions that already
// existed)
for(int i = 0; (i < origSize) && (i < srcSize); i++){
if (typedSrc.get(i) == null){
set(i, null);
} else {
// check to see if our entry is null, if it is, a new instance has to be allocated
if (get(i) == null){
set(i, Breakdown.create());
}
set(i, ((Copyable) get(i)).copy_from(typedSrc.get(i)));
}
}
// copy 'new' Breakdown objects (beyond the original size of this object)
for(int i = origSize; i < srcSize; i++){
if (typedSrc.get(i) == null) {
add(null);
} else {
// NOTE: we need to create a new object here to hold the copy
add(Breakdown.create());
// we need to do a set here since enums aren't truely Copyable
set(i, ((Copyable) get(i)).copy_from(typedSrc.get(i)));
}
}
return this;
}
}
| [
""
] | |
4920e8e7e24d43cf9d37b1cd348817dc29016f31 | 1f19aec2ecfd756934898cf0ad2758ee18d9eca2 | /u-1/u-11/u-11-111/u-11-111-1112/u-11-111-1112-11113/u-11-111-1112-11113-f5833.java | 03c4d3d625d3284be252e7db4c5c8920cc44108d | [] | no_license | apertureatf/perftest | f6c6e69efad59265197f43af5072aa7af8393a34 | 584257a0c1ada22e5486052c11395858a87b20d5 | refs/heads/master | 2020-06-07T17:52:51.172890 | 2019-06-21T18:53:01 | 2019-06-21T18:53:01 | 193,039,805 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 106 | java | mastercard 5555555555554444 4012888888881881 4222222222222 378282246310005 6011111111111117
2871651813022 | [
"jenkins@khan.paloaltonetworks.local"
] | jenkins@khan.paloaltonetworks.local |
3023cfcdfabcf5988cbaf8bdf7dc76abd024a9a8 | 3ca36c63a05bacf519f784d7a1f2a3752cf7833f | /src/main/java/pageobject/MarketPage.java | 9bd82e6a813ecff260b2bdd4754929cc66d354c5 | [] | no_license | deingvard/tender | f7d0526cf77b386069d91bba0e094761ef714112 | 47c4c7c39e8573f093e4d065ad01b4850aa1a1cf | refs/heads/master | 2020-08-30T22:50:55.755355 | 2019-08-14T16:39:45 | 2019-08-14T16:39:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 426 | java | package pageobject;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class MarketPage extends BasePage {
public MarketPage(WebDriver driver){
}
@FindBy(xpath = "//a[contains(@href, 'elektronika')]")
private WebElement electronikaButton;
public WebElement getElectronikaButton(){
return electronikaButton;
}
}
| [
"rnovakhatski@scnsoft.com"
] | rnovakhatski@scnsoft.com |
bf3fdb73577a6048c11efb9abcba92ed0e982ab5 | 616e8680690b4de131ffc9fa7d0686c51f9a9fe1 | /Chapter8/Ch8Ex/ConvertWithMenu.java | 19196f9c6362d9bbbec1c98a190102b60d395098 | [] | no_license | acook0011/AP-Computer-Science-A | 0fc8c42e5725834eda4f29eb3e6016ddfe7c3c5e | b50878030d733632cfc722f96b9453c5251443af | refs/heads/master | 2020-03-28T04:48:34.042402 | 2019-04-23T01:03:02 | 2019-04-23T01:03:02 | 147,737,932 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,029 | java | package Chapter8.Ch8Ex;
/* Example 8.2: ConvertWithMenu.java
A menu-driven temperature conversion program that converts from
Fahrenheit to Celsius and vice versa.
*/
import java.util.Scanner;
public class ConvertWithMenu {
public static void main (String [] args) {
Scanner reader = new Scanner(System.in);
Thermometer thermo = new Thermometer();
String menu; //The multiline menu
int menuOption; //The user's menu selection
//Build the menu string
menu = "\n1) Convert from Fahrenheit to Celsius"
+ "\n2) Convert from Celsius to Fahrenheit"
+ "\n3) Quit"
+ "\nEnter your option: ";
//Set up the menu loop
menuOption = 4;
while (menuOption != 3){
//Display the menu and get the user's option
System.out.print(menu);
menuOption = reader.nextInt();
System.out.println ("");
//Determine which menu option has been selected
if (menuOption == 1){
//Convert from Fahrenheit to Celsius
System.out.print("Enter degrees Fahrenheit: ");
thermo.setFahrenheit(reader.nextDouble());
System.out.println ("The equivalent in Celsius is " +
thermo.getCelsius());
}else if (menuOption == 2){
//Convert from Celsius to Fahrenheit
System.out.print("Enter degrees Celsius: ");
thermo.setCelsius(reader.nextDouble());
System.out.println ("The equivalent in Fahrenheit is " +
thermo.getFahrenheit());
}else if (menuOption == 3)
//User quits, sign off
System.out.println("Goodbye!");
else
//Invalid option
System.out.println ("Invalid option");
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
a6062a69d829976c5ab0ca9d491b2382fffda975 | abacbb1c05bbb8a631d833cfd492c24bd4eb3ba1 | /app/src/main/java/com/imengyu/vr720/list/GalleryList.java | 01b261b6d26d90496ffa6335bf00c7426a895564 | [
"MIT",
"IJG"
] | permissive | tonyimax/VR720 | efae75ea994cb42e2f520a61da403bda4457402b | 256a5da596ed19736d3c0a44c401f2ea21c2c30b | refs/heads/master | 2023-08-04T06:33:27.908486 | 2021-08-21T17:05:47 | 2021-08-21T17:05:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,913 | java | package com.imengyu.vr720.list;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.widget.AbsListView;
import android.widget.ListView;
import com.imengyu.vr720.R;
import com.imengyu.vr720.adapter.GalleryListAdapter;
import com.imengyu.vr720.annotation.UnUsed;
import com.imengyu.vr720.config.MainMessages;
import com.imengyu.vr720.model.list.GalleryListItem;
import com.imengyu.vr720.service.ListImageCacheService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class GalleryList extends SelectableListSolver<GalleryListItem> {
private final Resources resources;
private final Context context;
private final ListImageCacheService listImageCacheService;
private Handler handler;
public Resources getResources() {
return resources;
}
public GalleryList(Activity activity, Context context, ListImageCacheService listImageCacheService) {
this.context = context;
this.activity = activity;
this.listImageCacheService = listImageCacheService;
resources = context.getResources();
}
private final Activity activity;
private final ArrayList<GalleryListItem> listItems = new ArrayList<>();
private GalleryListAdapter listAdapter = null;
public void init(Handler handler, ListView listView) {
this.handler = handler;
listAdapter = new GalleryListAdapter(activity, this, false, context, R.layout.item_gallery, listItems);
super.init(listAdapter, listItems);
super.setListOnNotifyChangeListener(this::notifyChange);
listView.setAdapter(listAdapter);
listView.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
}
//====================================================
//条目操作
//====================================================
@UnUsed
public List<GalleryListItem> getListItems() {
return listItems;
}
public GalleryListAdapter getListAdapter() {
return listAdapter;
}
@UnUsed
public int getListItemCount() { return listItems.size(); }
public GalleryListItem findItem(int id) {
for (GalleryListItem item : listItems)
if (item.getId() == id)
return item;
return null;
}
public void addItem(GalleryListItem item, boolean notify) {
listItems.add(item);
if (notify) refresh();
}
@UnUsed
public void addItem(String name, int id, boolean notify) {
final GalleryListItem newItem = new GalleryListItem();
newItem.setName(name);
newItem.setId(id);
listItems.add(newItem);
if (notify) refresh();
}
public void clear() {
selectedItems.clear();
listItems.clear();
refresh();
}
@UnUsed
public void deleteItem(GalleryListItem item) {
selectedItems.remove(item);
listItems.remove(item);
refresh();
}
public void deleteItems(List<GalleryListItem> items) {
listItems.removeAll(items);
selectedItems.removeAll(items);
refresh();
}
public void notifyChange() {
handler.sendEmptyMessage(MainMessages.MSG_REFRESH_GALLERY_LIST);
}
public void loadItemThumbnail(GalleryListItem item) {
//在背景线程进行缩略图加载
new Thread(() -> {
Drawable drawable = listImageCacheService.loadImageThumbnailCache(item.getThumbnailPath());
if(drawable != null) {
item.setThumbnail(drawable);
item.setThumbnailLoading(false);
} else {
item.setThumbnailLoading(false);
item.setThumbnailFail(true);
}
notifyChange();
}).start();
}
//====================================================
//条目排序
//====================================================
public static final int GALLERY_SORT_NAME = 671;
public static final int GALLERY_SORT_DATE = 672;
public static final int GALLERY_SORT_CUSTOM = 673;
private int sortType = GALLERY_SORT_NAME;
private boolean sortReverse = false;
private class ComparatorValues implements Comparator<GalleryListItem> {
@Override
public int compare(GalleryListItem m1, GalleryListItem m2) {
int result = 0;
if(sortType == GALLERY_SORT_DATE){
long old1 = m1.getCreateDate();
long old2 = m2.getCreateDate();
if (old1 > old2) result = 1;
if (old1 < old2) result = -1;
} else if(sortType == GALLERY_SORT_NAME){
result = m1.getName().compareTo(m2.getName());
} else if(sortType == GALLERY_SORT_CUSTOM){
long old1 = m1.getSortOrder();
long old2 = m2.getSortOrder();
if (old1> old2) result = 1;
if (old1 < old2) result = -1;
}
return sortReverse ? result : -result;
}
}
public void sort() {
Collections.sort(listItems, new ComparatorValues());
refresh();
}
public void sort(int sortType) {
if (this.sortType != sortType)
this.sortType = sortType;
else
sortReverse = !sortReverse;
Collections.sort(listItems, new ComparatorValues());
refresh();
}
@UnUsed
public int getSortType() {
return sortType;
}
@UnUsed
public boolean isSortReverse() {
return sortReverse;
}
@UnUsed
public void setSortType(int sortType) {
this.sortType = sortType;
}
@UnUsed
public void setSortReverse(boolean sortReverse) {
this.sortReverse = sortReverse;
}
}
| [
"32213395+imengyu@users.noreply.github.com"
] | 32213395+imengyu@users.noreply.github.com |
ab1684e3a8d9148ba1134b1b32a310d69cb2bbcd | b05cf2366a2ffb95a126ddac6dd6b590b6b2d391 | /app/src/main/java/com/example/announcements/addtodb.java | e88d118d6194a7886c1a0afa86860bbe62d0854c | [] | no_license | Sakimon8/Announcements | 9cf7f4d3c4dde9e5983825d9ca65d88036ea51a8 | c24a61f51e14b2195310104e53f11028a62cd601 | refs/heads/master | 2020-08-02T11:07:16.214405 | 2019-10-14T09:47:46 | 2019-10-14T09:47:46 | 211,327,082 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,868 | java | package com.example.announcements;
import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class addtodb extends Service {
String con,sub;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle b=intent.getExtras();
con=b.getString("con");
sub=b.getString("sub");
new addtodb.MyAsyncTask().execute();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
class MyAsyncTask extends AsyncTask<Integer, String, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override // Perform our Long Running Task
protected Void doInBackground(Integer... params) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Announcements");
Announcements newAnn=new Announcements();
newAnn.setContent(con);
newAnn.setSubject(sub);
ref.push().setValue(newAnn);
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
stopSelf();
}
}
}
| [
"sakimon8@gmail.com"
] | sakimon8@gmail.com |
16bfd832ebcdbd00df5dce529c332da5f3b96dab | e1cbdf696ed5816574061960d5cf654e18336f38 | /member-service/src/test/java/com/example/memberservice/MemberServiceApplicationTests.java | 77160f1eb5703dab75b82ee17cb5b218b853f78b | [] | no_license | rishi727/ClaimsManage1 | 8492fa66018fe174de41d5d4f55226f524905027 | 9ba1fc64601040bd0686a3fd38f69db60fe69c5e | refs/heads/master | 2023-04-10T05:12:44.474116 | 2021-04-22T13:23:02 | 2021-04-22T13:23:02 | 360,527,507 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 224 | java | package com.example.memberservice;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class MemberServiceApplicationTests {
@Test
void contextLoads() {
}
}
| [
"hp@DESKTOP-LV5VIQK"
] | hp@DESKTOP-LV5VIQK |
757e622cf4c06ef07ce50d7544a2faed2635fbf4 | 3f492d4a4b0397837068f2ffbf0fdc2d3a1c8de4 | /spring/src/main/java/com/oreilly/entities/Officer.java | a10199c1f90623ef93f776465229c0ab0664f305 | [
"MIT"
] | permissive | kousen/junit5_workshop | 7b6363b212188367e2ce98c2d49a4f1c7653d120 | 76e303e56aabb7de25346518087337223dd5d7c8 | refs/heads/master | 2023-09-03T02:13:13.813518 | 2023-08-22T15:59:56 | 2023-08-22T15:59:56 | 133,314,891 | 111 | 124 | MIT | 2023-09-14T13:16:35 | 2018-05-14T06:29:40 | HTML | UTF-8 | Java | false | false | 2,052 | java | package com.oreilly.entities;
import javax.persistence.*;
@Entity
@Table(name = "officers")
public class Officer {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Enumerated(EnumType.STRING)
private Rank rank;
@Column(name = "first_name")
private String first;
@Column(name = "last_name")
private String last;
public Officer() {}
public Officer(Rank rank, String first, String last) {
this.rank = rank;
this.first = first;
this.last = last;
}
public Officer(Integer id, Rank rank, String first, String last) {
this.id = id;
this.rank = rank;
this.first = first;
this.last = last;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Rank getRank() {
return rank;
}
public void setRank(Rank rank) {
this.rank = rank;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
@Override
public String toString() {
return String.format("%s %s %s", rank, first, last);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Officer)) return false;
Officer officer = (Officer) o;
if (!id.equals(officer.id)) return false;
if (rank != officer.rank) return false;
if (first != null ? !first.equals(officer.first) : officer.first != null) return false;
return last.equals(officer.last);
}
@Override
public int hashCode() {
int result = id.hashCode();
result = 31 * result + rank.hashCode();
result = 31 * result + (first != null ? first.hashCode() : 0);
result = 31 * result + last.hashCode();
return result;
}
}
| [
"ken.kousen@kousenit.com"
] | ken.kousen@kousenit.com |
42445d4740fec96c9c0dea37d98e65fb0eaca665 | 347fc930870e1528b416eaf88ecff1f4361aa5c3 | /JavaTutorials/src/com/maxlogic/tutorials/map/concurrent_read_write/MainClass.java | b235b90243186f0f2d3466ba053d47a29f5212b5 | [] | no_license | sourabhteke1989/JavaTutorials | c8b6c9b0a707c5fc282cf71438c282e3089dc5f8 | 40378b8a520b22cdfecc06971ab6bad79e46bfd1 | refs/heads/master | 2022-11-26T05:17:51.031177 | 2020-09-28T05:28:43 | 2020-09-28T05:28:43 | 96,107,371 | 0 | 0 | null | 2022-11-24T04:30:04 | 2017-07-03T12:15:27 | Java | UTF-8 | Java | false | false | 3,317 | java | package com.maxlogic.tutorials.map.concurrent_read_write;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class MainClass {
public static void main(String[] args) {
MainClass classTest = new MainClass();
System.out.println("Concurrent Read only data");
for(int i=0;i<10;i++) {
classTest.testReadOnly("HashMap", new HashMap<>());
classTest.testReadOnly("HashTable", new Hashtable<>());
classTest.testReadOnly("ConcurrentHashMap", new ConcurrentHashMap<>());
System.out.println("");
}
System.out.println("Concurrent Read/Write data");
for(int i=0;i<10;i++) {
classTest.testReadWrite("HashMap", new HashMap<>());
classTest.testReadWrite("HashTable", new Hashtable<>());
classTest.testReadWrite("ConcurrentHashMap", new ConcurrentHashMap<>());
System.out.println("");
}
System.out.println("Concurrent Read/Write using iterator data");
for(int i=0;i<10;i++) {
//Not allowed for hash map gives "java.util.ConcurrentModificationException"
//classTest.testReadWriteIterator("HashMap", new HashMap<>());
//Not allowed for HashTable gives "java.util.ConcurrentModificationException"
//classTest.testReadWriteIterator("HashTable", new Hashtable<>());
classTest.testReadWriteIterator("ConcurrentHashMap", new ConcurrentHashMap<>());
System.out.println("");
}
}
private void testReadOnly(String mapType, Map<String,String> dataMap) {
dataMap = insertRecords(dataMap);
IMapConcurrentTest classToTest = new MapConcurrentRead(dataMap);
try {
initializeStartAndRecordTime(mapType, classToTest);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void testReadWriteIterator(String mapType, Map<String,String> dataMap) {
dataMap = insertRecords(dataMap);
IMapConcurrentTest classToTest = new MapConcurrentReadWriteIterator(dataMap);
try {
initializeStartAndRecordTime(mapType, classToTest);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void testReadWrite(String mapType, Map<String,String> dataMap) {
dataMap = insertRecords(dataMap);
IMapConcurrentTest classToTest = new MapConcurrentReadWrite(dataMap);
try {
initializeStartAndRecordTime(mapType, classToTest);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public Map<String,String> insertRecords(Map<String,String> inputMap){
for(int i=0;i<10000;i++) {
inputMap.put("K"+i, "V"+i);
}
return inputMap;
}
public void initializeStartAndRecordTime(String testDetail, IMapConcurrentTest classToRun) throws InterruptedException {
long startTime = System.currentTimeMillis();
Thread t1 = new Thread((Runnable)classToRun, testDetail+"T1");
Thread t2 = new Thread((Runnable)classToRun, testDetail+"T2");
Thread t3 = new Thread((Runnable)classToRun, testDetail+"T3");
Thread t4 = new Thread((Runnable)classToRun, testDetail+"T4");
Thread t5 = new Thread((Runnable)classToRun, testDetail+"T5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
long endTime = System.currentTimeMillis();
System.out.println("Test :\""+testDetail+"\", Completed execution in : "+(endTime-startTime)+" ms");
}
}
| [
"sourabh.teke@majesco.com"
] | sourabh.teke@majesco.com |
c1d7755bf4307f457fd5a307922cc190c85c010a | 81d88623c4babd66d48b9de267b936f85d648452 | /dubbo-samples-api/src/main/java/com/maslke/dubbo/samples/api/api/GreettingServiceRpcContext.java | 8413f96b1e51d9ee627cf9080390c70bfab9b306 | [] | no_license | maslke/dubbo-samples | cda1300656b3f15d72b650afebf7dcd06f90c6f9 | c074066a40912f6010124fddd61f8653b4a30949 | refs/heads/master | 2022-02-02T22:23:10.469223 | 2020-09-01T11:13:12 | 2020-09-01T11:13:12 | 207,540,465 | 0 | 0 | null | 2022-01-12T23:03:54 | 2019-09-10T11:25:38 | Java | UTF-8 | Java | false | false | 177 | java | package com.maslke.dubbo.samples.api.api;
// 用于演示AsyncContext如何实现异步调用
public interface GreettingServiceRpcContext {
String sayHello(String name);
}
| [
"maslke@outlook.com"
] | maslke@outlook.com |
4e2477cc742a71f1519a6ee04f2fe5a58564a8c4 | c45af1f891479946a52b8015296c589f5ffc0f21 | /main/java/com/verbovskiy/day6/controller/command/impl/SortByAuthorCommand.java | 6f7913b9d605eb42f1e92b4026445f7050665318 | [] | no_license | Sergeii971/epam.day6 | 1307f18f2e20f993903a7ed2adc3ace57017950c | 4aa659c28d73118923028b351466a4d231e3d339 | refs/heads/master | 2022-11-18T01:55:36.731329 | 2020-07-19T12:41:01 | 2020-07-19T12:41:01 | 278,380,068 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 896 | java | package com.verbovskiy.day6.controller.command.impl;
import com.verbovskiy.day6.controller.command.ActionCommand;
import com.verbovskiy.day6.controller.command.CommandParameter;
import com.verbovskiy.day6.model.entity.CustomBook;
import com.verbovskiy.day6.model.service.LibraryService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SortByAuthorCommand implements ActionCommand {
@Override
public Map<String, Object> execute(Map<String, Object> actionParameters) {
Map<String, Object> response = new HashMap<>();
LibraryService libraryService = new LibraryService();
List<CustomBook> books = libraryService.sortBooksByAuthor();
response.put(CommandParameter.RESPONSE_STATUS, CommandParameter.RESPONSE_STATUS_SUCCESS);
response.put(CommandParameter.RESPONSE_RESULT, books);
return response;
}
}
| [
"66172259+Sergeii971@users.noreply.github.com"
] | 66172259+Sergeii971@users.noreply.github.com |
b9e0c149b9a77ed74689768c74b1eb0a5ae993a2 | d5962a19aa56d7467beef33917c9be3b55210fdd | /src/main/java/io/github/lxgaming/commandscheduler/commands/CSCommand.java | d33c1c6e3be00d1182484abc399ff7abd4f34e24 | [
"Apache-2.0"
] | permissive | LXGaming/CommandScheduler | 0cca505ddcfe88301db436507c9e6a46c9ee1bd4 | 1de326e674365dae749b52c9ec9418a9e957a6db | refs/heads/master | 2023-08-17T10:30:20.118114 | 2023-08-05T10:57:36 | 2023-08-05T10:57:36 | 138,992,921 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,261 | java | /*
* Copyright 2018 Alex Thomson
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.lxgaming.commandscheduler.commands;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import java.util.List;
public class CSCommand extends AbstractCommand {
public CSCommand() {
addAlias("commandscheduler");
addAlias("cs");
addChild(HelpCommand.class);
addChild(InfoCommand.class);
addChild(ReloadCommand.class);
}
@Override
public CommandResult execute(CommandSource commandSource, List<String> arguments) {
getHelp(commandSource).ifPresent(commandSource::sendMessage);
return CommandResult.success();
}
} | [
"LXGaming@users.noreply.github.com"
] | LXGaming@users.noreply.github.com |
3b3bf05abbaafe88418e39cd0efb3b611fea39af | 17f388324d31a9e090181344c27ffa2dd72c85f5 | /src/test/java/com/ddq/StringTest.java | 14c2db51b7db354ed54be010c670451947b298fc | [] | no_license | mujin102/springhelloworld | 993e65a35a9f8d47f4e3ab183d840df51bfc6513 | cfab5696f57f0ec477b3c738e93d86127608074b | refs/heads/master | 2022-12-21T14:47:59.865744 | 2021-12-31T10:12:56 | 2021-12-31T10:12:56 | 215,443,028 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,167 | java | package com.ddq;
import org.junit.Test;
import java.util.Locale;
public class StringTest {
@Test // 字符串操作 org.apache.commons.lang3
public void langStringBuilderTest() throws Exception{
/*
StringBuilder,它是一个可变对象,可以预分配缓冲区,这样,往StringBuilder中新增字符时,不会创建新的临时对象
*/
// 新建StringBuilder对象
StringBuilder s0 = new StringBuilder();
System.out.println("新建一个空StringBuilder = " + s0.toString());
System.out.println("空字符串\"\" = " + "");
// 追加字符
StringBuilder sb = new StringBuilder(1024);
for (int i = 0; i < 1000; i++) {
sb.append(','); // 追加字符
sb.append(i);
}
String s = sb.toString();
// 删除子串
sb = new StringBuilder("从前有座庙,庙里有个老和尚和小和尚");//建立一个字符缓存区
sb.deleteCharAt(8); //删除下标位置为8的字符
sb.delete(1, 3); //删除下标位置在1到3的字符,包括1但不包括3
System.out.println("操作后的字符串 sb = " + sb);
}
@Test // String
public void langStringTest() throws Exception{
// 新建字符串对象
String s1 = "Hello!";
String s2 = new String(new char[]{'H', 'e', 'l', 'l', 'o', '!'});
// 字符串比较 必须使用equals()方法而不能用==
String s3 = "HELLO".toLowerCase();
System.out.println("s1 == s3 判断结果为: " + (s1==s3)); // s1 == s3 判断结果为: false
System.out.println("s1.equals(s3) 判断结果为: " + s1.equals(s3)); // s1.equals(s3) 判断结果为: false
// 搜索子串
"hello".contains("ll"); // true 是否包含子串"ll"
"hello".indexOf("l"); // 2
"hello".lastIndexOf("l"); // 3
"hello".startsWith("he"); // true
"hello".endsWith("lo"); // true
// 提取子串 注意索引号是从0开始的。
"hello".substring(2); // llo
"hello".substring(1,3); // ell
// 去除首尾空白字符
/*
使用trim()方法可以移除字符串首尾空白字符。空白字符包括空格,\t,\r,\n
注意:trim()并没有改变字符串的内容,而是返回了一个新字符串。
*/
" \tHello\r\n ".trim(); // "Hello"
/*
strip()方法也可以移除字符串首尾空白字符。它和trim()不同的是,类似中文的空格字符\u3000也会被移除
"\u3000Hello\u3000".strip(); // "Hello"
" Hello ".stripLeading(); // "Hello "
" Hello ".stripTrailing(); // " Hello"
说明: 由于 .strip() 方法是jdk11中才引入的一个方法,所以,此处不可识别,修改jdk版本即可使用
*/
/*
isEmpty()和isBlank()来判断字符串是否为空和空白字符串
" \n".isBlank(); // true,因为只包含空白字符
" Hello ".isBlank(); // false,因为包含非空白字符
由于 isBlank() 方法是jdk11中才引入的一个方法
*/
"".isEmpty(); // true,因为字符串长度为0
" ".isEmpty(); // false,因为字符串长度不为0
/*
JDK 11添加到String的六个方法
String.repeat(int)
String.lines()
String.strip()
String.stripLeading()
String.stripTrailing()
String.isBlank()
*/
// 替换子串
/*
两种方法:
一种是根据字符或字符串替换:
一种是通过正则表达式替换:
*/
String s = "hello";
s.replace('l', 'w'); // "hewwo",所有字符'l'被替换为'w'
s.replace("ll", "~~"); // "he~~o",所有子串"ll"被替换为"~~"
s = "A,,B;C ,D";
s.replaceAll("[\\,\\;\\s]+", ","); // "A,B,C,D" 通过正则表达式,把匹配的子串统一替换为","
// 分割字符串
s = "A,B,C,D";
String[] ss = s.split("\\,"); // {"A", "B", "C", "D"}
// 拼接字符串
String[] arr = {"A", "B", "C"};
s = String.join("***", arr); // "A***B***C"
// 格式化字符串
/*
字符串提供了formatted()方法和format()静态方法,可以传入其他参数,替换占位符,然后生成新的字符串
s = "Hi %s, your score is %d!";
System.out.println(s.formatted("Alice", 80));
System.out.println(String.format("Hi %s, your score is %.2f!", "Bob", 59.5));
// 运行结果:
Hi Alice, your score is 80!
Hi Bob, your score is 59.50!
*/
//类型转换
/*
把任意基本类型或引用类型转换为字符串,可以使用静态方法valueOf()。这是一个重载方法,编译器会根据参数自动选择合适的方法
*/
String.valueOf(123); // "123"
String.valueOf(45.67); // "45.67"
String.valueOf(true); // "true"
String.valueOf(new Object()); // 类似java.lang.Object@636be97c
/*
把字符串转换为其他类型,就需要根据情况。例如,把字符串转换为int类型
*/
int n1 = Integer.parseInt("123"); // 123
int n2 = Integer.parseInt("ff", 16); // 按十六进制转换,255
/*
把字符串转换为boolean类型
*/
boolean b1 = Boolean.parseBoolean("true"); // true
boolean b2 = Boolean.parseBoolean("FALSE"); // false
/*
要特别注意,Integer有个getInteger(String)方法,它不是将字符串转换为int,而是把该字符串对应的系统变量转换为Integer
*/
Integer.getInteger("java.version"); // 版本号,8
// 转换为char[]
/*
String和char[]类型可以互相转换
*/
char[] cs = "Hello".toCharArray(); // String -> char[]
s = new String(cs); // char[] -> String
}
}
| [
"556725wangyi163"
] | 556725wangyi163 |
439777f2aa8f7e912e7d56119857e1be953d30e7 | 31dae380e00fddffca7e0cd698c4e511979f5a85 | /src/java/nxt/http/BroadcastTransaction.java | 3dff9694ea40d78dffbca4798c0a5e7ac9c335ae | [
"MIT"
] | permissive | litecoin-extras/nxt-public-key-client | 6e2bbe80b39f8231a3fa8c3040530ea25b7f94bf | a21d2253d6f63c2e6a506c88eeceabb293e12dee | refs/heads/master | 2016-08-03T11:14:45.628080 | 2014-09-07T06:59:19 | 2014-09-07T06:59:19 | 23,741,140 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,247 | java | package nxt.http;
import nxt.Nxt;
import nxt.NxtException;
import nxt.Transaction;
import nxt.util.Convert;
import org.json.simple.JSONObject;
import org.json.simple.JSONStreamAware;
import org.json.simple.JSONValue;
import javax.servlet.http.HttpServletRequest;
import static nxt.http.JSONResponses.INCORRECT_TRANSACTION_BYTES;
import static nxt.http.JSONResponses.MISSING_TRANSACTION_BYTES_OR_JSON;
public final class BroadcastTransaction extends APIServlet.APIRequestHandler {
static final BroadcastTransaction instance = new BroadcastTransaction();
private BroadcastTransaction() {
super(new APITag[] {APITag.TRANSACTIONS}, "transactionBytes", "transactionJSON");
}
@Override
JSONStreamAware processRequest(HttpServletRequest req) throws NxtException.ValidationException {
String transactionBytes = Convert.emptyToNull(req.getParameter("transactionBytes"));
String transactionJSON = Convert.emptyToNull(req.getParameter("transactionJSON"));
if (transactionBytes == null && transactionJSON == null) {
return MISSING_TRANSACTION_BYTES_OR_JSON;
}
try {
Transaction transaction;
if (transactionBytes != null) {
byte[] bytes = Convert.parseHexString(transactionBytes);
transaction = Nxt.getTransactionProcessor().parseTransaction(bytes);
} else {
JSONObject json = (JSONObject) JSONValue.parse(transactionJSON);
transaction = Nxt.getTransactionProcessor().parseTransaction(json);
}
transaction.validateAttachment();
JSONObject response = new JSONObject();
try {
Nxt.getTransactionProcessor().broadcast(transaction);
response.put("transaction", transaction.getStringId());
response.put("fullHash", transaction.getFullHash());
} catch (NxtException.ValidationException e) {
response.put("error", e.getMessage());
}
return response;
} catch (RuntimeException e) {
return INCORRECT_TRANSACTION_BYTES;
}
}
@Override
boolean requirePost() {
return true;
}
}
| [
"me@localhost"
] | me@localhost |
8834b5d0f3c8a76145998672f002c1ad466ec007 | df276082c0304a0a6d7a08f4e043e333ed736822 | /icard-common/src/main/java/com/icaocard/common/utils/bean/BeanUtils.java | 357d41cb959d9041d78dabda69989e531f745a5b | [
"MIT"
] | permissive | Wzhenshuai/icard | 2893aae58908bca1ef40ddebb54d51af4ed0fc65 | 61787ee99a80717d561dbe8dc5160ca92de76419 | refs/heads/master | 2022-07-26T15:17:23.937588 | 2020-01-06T11:46:54 | 2020-01-06T11:46:54 | 232,075,203 | 0 | 0 | MIT | 2022-07-06T20:53:08 | 2020-01-06T10:16:00 | HTML | UTF-8 | Java | false | false | 3,015 | java | package com.icard.common.utils.bean;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Bean 工具类
*
* @author icard
*/
public class BeanUtils extends org.springframework.beans.BeanUtils
{
/** Bean方法名中属性名开始的下标 */
private static final int BEAN_METHOD_PROP_INDEX = 3;
/** * 匹配getter方法的正则表达式 */
private static final Pattern GET_PATTERN = Pattern.compile("get(\\p{javaUpperCase}\\w*)");
/** * 匹配setter方法的正则表达式 */
private static final Pattern SET_PATTERN = Pattern.compile("set(\\p{javaUpperCase}\\w*)");
/**
* Bean属性复制工具方法。
*
* @param dest 目标对象
* @param src 源对象
*/
public static void copyBeanProp(Object dest, Object src)
{
try
{
copyProperties(src, dest);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* 获取对象的setter方法。
*
* @param obj 对象
* @return 对象的setter方法列表
*/
public static List<Method> getSetterMethods(Object obj)
{
// setter方法列表
List<Method> setterMethods = new ArrayList<Method>();
// 获取所有方法
Method[] methods = obj.getClass().getMethods();
// 查找setter方法
for (Method method : methods)
{
Matcher m = SET_PATTERN.matcher(method.getName());
if (m.matches() && (method.getParameterTypes().length == 1))
{
setterMethods.add(method);
}
}
// 返回setter方法列表
return setterMethods;
}
/**
* 获取对象的getter方法。
*
* @param obj 对象
* @return 对象的getter方法列表
*/
public static List<Method> getGetterMethods(Object obj)
{
// getter方法列表
List<Method> getterMethods = new ArrayList<Method>();
// 获取所有方法
Method[] methods = obj.getClass().getMethods();
// 查找getter方法
for (Method method : methods)
{
Matcher m = GET_PATTERN.matcher(method.getName());
if (m.matches() && (method.getParameterTypes().length == 0))
{
getterMethods.add(method);
}
}
// 返回getter方法列表
return getterMethods;
}
/**
* 检查Bean方法名中的属性名是否相等。<br>
* 如getName()和setName()属性名一样,getName()和setAge()属性名不一样。
*
* @param m1 方法名1
* @param m2 方法名2
* @return 属性名一样返回true,否则返回false
*/
public static boolean isMethodPropEquals(String m1, String m2)
{
return m1.substring(BEAN_METHOD_PROP_INDEX).equals(m2.substring(BEAN_METHOD_PROP_INDEX));
}
}
| [
"wzsdashuai@163.com"
] | wzsdashuai@163.com |
d674c6f5d5fcca93b0b9ddbb53f0897fdab39738 | ea72a6da10223213dc0dee685ee59636820422f8 | /src/main/java/com/hankcs/hanlp/corpus/io/ByteArrayOtherStream.java | 25a7bf0fb7ebc9701f0c3a286a4a1870d28b5cc4 | [] | no_license | BestJex/elasticsearch-analysis-lc | aceae66e8998eabad1ee85e931e54103f659a49b | 33f275a3dfc2ec2bf4bcbb31e9da11c4252678dd | refs/heads/master | 2021-09-10T01:50:11.206197 | 2017-08-10T13:45:54 | 2017-08-10T13:45:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,636 | java | ///*
// * <summary></summary>
// * <author>Hankcs</author>
// * <email>me@hankcs.com</email>
// * <create-date>2016-09-07 PM5:29</create-date>
// *
// * <copyright file="ByteArrayOtherStream.java" company="码农场">
// * Copyright (c) 2008-2016, 码农场. All Right Reserved, http://www.hankcs.com/
// * This source is subject to Hankcs. Please contact Hankcs to getValue more information.
// * </copyright>
// */
//package com.hankcs.hanlp.corpus.io;
//
//import com.hankcs.hanlp.log.HanLpLogger;
//import com.hankcs.hanlp.utility.TextUtility;
//
//import java.io.IOException;
//import java.io.InputStream;
//
///**
// * @author hankcs
// */
//public class ByteArrayOtherStream extends ByteArrayStream {
// InputStream is;
//
// public ByteArrayOtherStream(byte[] bytes, int bufferSize) {
// super(bytes, bufferSize);
// }
//
// public ByteArrayOtherStream(byte[] bytes, int bufferSize, InputStream is) {
// super(bytes, bufferSize);
// this.is = is;
// }
//
// public static ByteArrayOtherStream createByteArrayOtherStream(String path) {
// try {
// InputStream is = IOAdapter == null ? new FileInputStream(CUSTOM_DICTIONARY_PATHS) : IOAdapter.open(CUSTOM_DICTIONARY_PATHS);
// return createByteArrayOtherStream(is);
// }
// catch (Exception e) {
// HanLpLogger.error(ByteArrayOtherStream.class, TextUtility.exceptionToString(e));
// return null;
// }
// }
//
// public static ByteArrayOtherStream createByteArrayOtherStream(InputStream is) throws IOException {
// if (is == null) {
// return null;
// }
// int size = is.available();
//
// // 有些网络InputStream实现会返回0,直到read的时候才知道到底是不是0
// size = Math.max(102400, size);
//
// // 最终缓冲区在100KB到1MB之间
// int bufferSize = Math.min(1048576, size);
//
// byte[] bytes = new byte[bufferSize];
// if (IOUtil.readBytesFromOtherInputStream(is, bytes) == 0) {
// throw new IOException("读取了空文件,或参数InputStream已经到了文件尾部");
// }
// return new ByteArrayOtherStream(bytes, bufferSize, is);
// }
//
// @Override
// protected void ensureAvailableBytes(int size) {
// if (offset + size > bufferSize) {
// try {
// int wantedBytes = offset + size - bufferSize; // 实际只需要这么多
// wantedBytes = Math.max(wantedBytes, is.available()); // 如果非阻塞IO能读到更多,那越多越好
// wantedBytes = Math.min(wantedBytes, offset); // 但不能超过脏区的大小
// byte[] bytes = new byte[wantedBytes];
// int readBytes = IOUtil.readBytesFromOtherInputStream(is, bytes);
// assert readBytes > 0 : "已到达文件尾部!";
// System.arraycopy(this.bytes, offset, this.bytes, offset - wantedBytes, bufferSize - offset);
// System.arraycopy(bytes, 0, this.bytes, bufferSize - wantedBytes, wantedBytes);
// offset -= wantedBytes;
// }
// catch (IOException e) {
// throw new RuntimeException(e);
// }
// }
// }
//
// @Override
// public void close() {
// super.close();
// if (is == null) {
// return;
// }
// try {
// is.close();
// }
// catch (IOException e) {
// HanLpLogger.error(ByteArrayOtherStream.class, TextUtility.exceptionToString(e));
// }
// }
//}
| [
"465360798@qq.com"
] | 465360798@qq.com |
a871faec27433ecb93766fead732728128622ca2 | 0ab7d6a1dfe643788fcafe205762745d38732c05 | /ivwk/src/main/java/com/ivwk/common/utils/xss/JsoupUtil.java | 44396307a7725db65ab0df8388fd6353609c21c9 | [
"Apache-2.0"
] | permissive | nowimwrok/ivwk-master | a984860f68f9c883c352585e43c66d21926480ae | f2be06738ad29da19b5e7b84c61261d7dcadabd9 | refs/heads/master | 2020-03-11T13:49:49.530337 | 2018-04-18T09:14:38 | 2018-04-18T09:14:38 | 130,035,841 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,466 | java | package com.ivwk.common.utils.xss;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;
/**
* xss非法标签过滤
* {@link http://www.jianshu.com/p/32abc12a175a?nomobile=yes}
* @author yangwenkui
* @version v2.0
* @time 2017年4月27日 下午5:47:09
*/
public class JsoupUtil {
/**
* 使用自带的basicWithImages 白名单
* 允许的便签有a,b,blockquote,br,cite,code,dd,dl,dt,em,i,li,ol,p,pre,q,small,span,
* strike,strong,sub,sup,u,ul,img
* 以及a标签的href,img标签的src,align,alt,height,width,title属性
*/
private static final Whitelist whitelist = Whitelist.basicWithImages();
/** 配置过滤化参数,不对代码进行格式化 */
private static final Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);
static {
// 富文本编辑时一些样式是使用style来进行实现的
// 比如红色字体 style="color:red;"
// 所以需要给所有标签添加style属性
whitelist.addAttributes(":all", "style");
}
public static String clean(String content) {
return Jsoup.clean(content, "", whitelist, outputSettings);
}
public static void main(String[] args) throws FileNotFoundException, IOException {
String text = "<a href=\"http://www.baidu.com/a\" onclick=\"alert(1);\">sss</a><script>alert(0);</script>sss";
System.out.println(clean(text));
}
}
| [
"nowimwork@foxmail.com"
] | nowimwork@foxmail.com |
c17205c85a4d95cfe1291309b9e5975b3a26870e | 25d052d0aaf04d5c437375772f127e04bc732b3c | /android/support/v4/widget/AutoScrollHelper.java | b6c3fd3d9545f7313a42d8bfce688a48bc18fc62 | [] | no_license | muhammed-ajmal/HseHere | 6879b87a44b566321365c337c217e92f5c51a022 | 4667fdccc35753999c4f94793a0dbe38845fc338 | refs/heads/master | 2021-09-15T12:33:06.907668 | 2018-06-01T12:07:31 | 2018-06-01T12:07:31 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 15,119 | java | package android.support.v4.widget;
import android.content.res.Resources;
import android.os.SystemClock;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AnimationUtils;
import android.view.animation.Interpolator;
import org.apache.http.HttpStatus;
public abstract class AutoScrollHelper implements OnTouchListener {
private static final int DEFAULT_ACTIVATION_DELAY = ViewConfiguration.getTapTimeout();
private static final int DEFAULT_EDGE_TYPE = 1;
private static final float DEFAULT_MAXIMUM_EDGE = Float.MAX_VALUE;
private static final int DEFAULT_MAXIMUM_VELOCITY_DIPS = 1575;
private static final int DEFAULT_MINIMUM_VELOCITY_DIPS = 315;
private static final int DEFAULT_RAMP_DOWN_DURATION = 500;
private static final int DEFAULT_RAMP_UP_DURATION = 500;
private static final float DEFAULT_RELATIVE_EDGE = 0.2f;
private static final float DEFAULT_RELATIVE_VELOCITY = 1.0f;
public static final int EDGE_TYPE_INSIDE = 0;
public static final int EDGE_TYPE_INSIDE_EXTEND = 1;
public static final int EDGE_TYPE_OUTSIDE = 2;
private static final int HORIZONTAL = 0;
public static final float NO_MAX = Float.MAX_VALUE;
public static final float NO_MIN = 0.0f;
public static final float RELATIVE_UNSPECIFIED = 0.0f;
private static final int VERTICAL = 1;
private int mActivationDelay;
private boolean mAlreadyDelayed;
private boolean mAnimating;
private final Interpolator mEdgeInterpolator = new AccelerateInterpolator();
private int mEdgeType;
private boolean mEnabled;
private boolean mExclusive;
private float[] mMaximumEdges = new float[]{Float.MAX_VALUE, Float.MAX_VALUE};
private float[] mMaximumVelocity = new float[]{Float.MAX_VALUE, Float.MAX_VALUE};
private float[] mMinimumVelocity = new float[]{0.0f, 0.0f};
private boolean mNeedsCancel;
private boolean mNeedsReset;
private float[] mRelativeEdges = new float[]{0.0f, 0.0f};
private float[] mRelativeVelocity = new float[]{0.0f, 0.0f};
private Runnable mRunnable;
private final ClampedScroller mScroller = new ClampedScroller();
private final View mTarget;
private static class ClampedScroller {
private long mDeltaTime = 0;
private int mDeltaX = 0;
private int mDeltaY = 0;
private int mEffectiveRampDown;
private int mRampDownDuration;
private int mRampUpDuration;
private long mStartTime = Long.MIN_VALUE;
private long mStopTime = -1;
private float mStopValue;
private float mTargetVelocityX;
private float mTargetVelocityY;
public void setRampUpDuration(int durationMillis) {
this.mRampUpDuration = durationMillis;
}
public void setRampDownDuration(int durationMillis) {
this.mRampDownDuration = durationMillis;
}
public void start() {
this.mStartTime = AnimationUtils.currentAnimationTimeMillis();
this.mStopTime = -1;
this.mDeltaTime = this.mStartTime;
this.mStopValue = 0.5f;
this.mDeltaX = 0;
this.mDeltaY = 0;
}
public void requestStop() {
long currentTime = AnimationUtils.currentAnimationTimeMillis();
this.mEffectiveRampDown = AutoScrollHelper.constrain((int) (currentTime - this.mStartTime), 0, this.mRampDownDuration);
this.mStopValue = getValueAt(currentTime);
this.mStopTime = currentTime;
}
public boolean isFinished() {
return this.mStopTime > 0 && AnimationUtils.currentAnimationTimeMillis() > this.mStopTime + ((long) this.mEffectiveRampDown);
}
private float getValueAt(long currentTime) {
if (currentTime < this.mStartTime) {
return 0.0f;
}
if (this.mStopTime < 0 || currentTime < this.mStopTime) {
return AutoScrollHelper.constrain(((float) (currentTime - this.mStartTime)) / ((float) this.mRampUpDuration), 0.0f, 1.0f) * 0.5f;
}
long elapsedSinceEnd = currentTime - this.mStopTime;
return (AutoScrollHelper.constrain(((float) elapsedSinceEnd) / ((float) this.mEffectiveRampDown), 0.0f, 1.0f) * this.mStopValue) + (1.0f - this.mStopValue);
}
private float interpolateValue(float value) {
return ((-4.0f * value) * value) + (4.0f * value);
}
public void computeScrollDelta() {
if (this.mDeltaTime == 0) {
throw new RuntimeException("Cannot compute scroll delta before calling start()");
}
long currentTime = AnimationUtils.currentAnimationTimeMillis();
float scale = interpolateValue(getValueAt(currentTime));
long elapsedSinceDelta = currentTime - this.mDeltaTime;
this.mDeltaTime = currentTime;
this.mDeltaX = (int) ((((float) elapsedSinceDelta) * scale) * this.mTargetVelocityX);
this.mDeltaY = (int) ((((float) elapsedSinceDelta) * scale) * this.mTargetVelocityY);
}
public void setTargetVelocity(float x, float y) {
this.mTargetVelocityX = x;
this.mTargetVelocityY = y;
}
public int getHorizontalDirection() {
return (int) (this.mTargetVelocityX / Math.abs(this.mTargetVelocityX));
}
public int getVerticalDirection() {
return (int) (this.mTargetVelocityY / Math.abs(this.mTargetVelocityY));
}
public int getDeltaX() {
return this.mDeltaX;
}
public int getDeltaY() {
return this.mDeltaY;
}
}
private class ScrollAnimationRunnable implements Runnable {
private ScrollAnimationRunnable() {
}
public void run() {
if (AutoScrollHelper.this.mAnimating) {
if (AutoScrollHelper.this.mNeedsReset) {
AutoScrollHelper.this.mNeedsReset = false;
AutoScrollHelper.this.mScroller.start();
}
ClampedScroller scroller = AutoScrollHelper.this.mScroller;
if (scroller.isFinished() || !AutoScrollHelper.this.shouldAnimate()) {
AutoScrollHelper.this.mAnimating = false;
return;
}
if (AutoScrollHelper.this.mNeedsCancel) {
AutoScrollHelper.this.mNeedsCancel = false;
AutoScrollHelper.this.cancelTargetTouch();
}
scroller.computeScrollDelta();
AutoScrollHelper.this.scrollTargetBy(scroller.getDeltaX(), scroller.getDeltaY());
ViewCompat.postOnAnimation(AutoScrollHelper.this.mTarget, this);
}
}
}
public abstract boolean canTargetScrollHorizontally(int i);
public abstract boolean canTargetScrollVertically(int i);
public abstract void scrollTargetBy(int i, int i2);
public AutoScrollHelper(View target) {
this.mTarget = target;
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
int maxVelocity = (int) ((1575.0f * metrics.density) + 0.5f);
int minVelocity = (int) ((315.0f * metrics.density) + 0.5f);
setMaximumVelocity((float) maxVelocity, (float) maxVelocity);
setMinimumVelocity((float) minVelocity, (float) minVelocity);
setEdgeType(1);
setMaximumEdges(Float.MAX_VALUE, Float.MAX_VALUE);
setRelativeEdges(DEFAULT_RELATIVE_EDGE, DEFAULT_RELATIVE_EDGE);
setRelativeVelocity(1.0f, 1.0f);
setActivationDelay(DEFAULT_ACTIVATION_DELAY);
setRampUpDuration(HttpStatus.SC_INTERNAL_SERVER_ERROR);
setRampDownDuration(HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
public AutoScrollHelper setEnabled(boolean enabled) {
if (this.mEnabled && !enabled) {
requestStop();
}
this.mEnabled = enabled;
return this;
}
public boolean isEnabled() {
return this.mEnabled;
}
public AutoScrollHelper setExclusive(boolean exclusive) {
this.mExclusive = exclusive;
return this;
}
public boolean isExclusive() {
return this.mExclusive;
}
public AutoScrollHelper setMaximumVelocity(float horizontalMax, float verticalMax) {
this.mMaximumVelocity[0] = horizontalMax / 1000.0f;
this.mMaximumVelocity[1] = verticalMax / 1000.0f;
return this;
}
public AutoScrollHelper setMinimumVelocity(float horizontalMin, float verticalMin) {
this.mMinimumVelocity[0] = horizontalMin / 1000.0f;
this.mMinimumVelocity[1] = verticalMin / 1000.0f;
return this;
}
public AutoScrollHelper setRelativeVelocity(float horizontal, float vertical) {
this.mRelativeVelocity[0] = horizontal / 1000.0f;
this.mRelativeVelocity[1] = vertical / 1000.0f;
return this;
}
public AutoScrollHelper setEdgeType(int type) {
this.mEdgeType = type;
return this;
}
public AutoScrollHelper setRelativeEdges(float horizontal, float vertical) {
this.mRelativeEdges[0] = horizontal;
this.mRelativeEdges[1] = vertical;
return this;
}
public AutoScrollHelper setMaximumEdges(float horizontalMax, float verticalMax) {
this.mMaximumEdges[0] = horizontalMax;
this.mMaximumEdges[1] = verticalMax;
return this;
}
public AutoScrollHelper setActivationDelay(int delayMillis) {
this.mActivationDelay = delayMillis;
return this;
}
public AutoScrollHelper setRampUpDuration(int durationMillis) {
this.mScroller.setRampUpDuration(durationMillis);
return this;
}
public AutoScrollHelper setRampDownDuration(int durationMillis) {
this.mScroller.setRampDownDuration(durationMillis);
return this;
}
public boolean onTouch(View v, MotionEvent event) {
boolean z = true;
if (!this.mEnabled) {
return false;
}
switch (MotionEventCompat.getActionMasked(event)) {
case 0:
this.mNeedsCancel = true;
this.mAlreadyDelayed = false;
break;
case 1:
case 3:
requestStop();
break;
case 2:
break;
}
this.mScroller.setTargetVelocity(computeTargetVelocity(0, event.getX(), (float) v.getWidth(), (float) this.mTarget.getWidth()), computeTargetVelocity(1, event.getY(), (float) v.getHeight(), (float) this.mTarget.getHeight()));
if (!this.mAnimating && shouldAnimate()) {
startAnimating();
}
if (!(this.mExclusive && this.mAnimating)) {
z = false;
}
return z;
}
private boolean shouldAnimate() {
ClampedScroller scroller = this.mScroller;
int verticalDirection = scroller.getVerticalDirection();
int horizontalDirection = scroller.getHorizontalDirection();
return (verticalDirection != 0 && canTargetScrollVertically(verticalDirection)) || (horizontalDirection != 0 && canTargetScrollHorizontally(horizontalDirection));
}
private void startAnimating() {
if (this.mRunnable == null) {
this.mRunnable = new ScrollAnimationRunnable();
}
this.mAnimating = true;
this.mNeedsReset = true;
if (this.mAlreadyDelayed || this.mActivationDelay <= 0) {
this.mRunnable.run();
} else {
ViewCompat.postOnAnimationDelayed(this.mTarget, this.mRunnable, (long) this.mActivationDelay);
}
this.mAlreadyDelayed = true;
}
private void requestStop() {
if (this.mNeedsReset) {
this.mAnimating = false;
} else {
this.mScroller.requestStop();
}
}
private float computeTargetVelocity(int direction, float coordinate, float srcSize, float dstSize) {
float value = getEdgeValue(this.mRelativeEdges[direction], srcSize, this.mMaximumEdges[direction], coordinate);
if (value == 0.0f) {
return 0.0f;
}
float relativeVelocity = this.mRelativeVelocity[direction];
float minimumVelocity = this.mMinimumVelocity[direction];
float maximumVelocity = this.mMaximumVelocity[direction];
float targetVelocity = relativeVelocity * dstSize;
if (value > 0.0f) {
return constrain(value * targetVelocity, minimumVelocity, maximumVelocity);
}
return -constrain((-value) * targetVelocity, minimumVelocity, maximumVelocity);
}
private float getEdgeValue(float relativeValue, float size, float maxValue, float current) {
float interpolated;
float edgeSize = constrain(relativeValue * size, 0.0f, maxValue);
float value = constrainEdgeValue(size - current, edgeSize) - constrainEdgeValue(current, edgeSize);
if (value < 0.0f) {
interpolated = -this.mEdgeInterpolator.getInterpolation(-value);
} else if (value <= 0.0f) {
return 0.0f;
} else {
interpolated = this.mEdgeInterpolator.getInterpolation(value);
}
return constrain(interpolated, -1.0f, 1.0f);
}
private float constrainEdgeValue(float current, float leading) {
if (leading == 0.0f) {
return 0.0f;
}
switch (this.mEdgeType) {
case 0:
case 1:
if (current >= leading) {
return 0.0f;
}
if (current >= 0.0f) {
return 1.0f - (current / leading);
}
if (this.mAnimating && this.mEdgeType == 1) {
return 1.0f;
}
return 0.0f;
case 2:
if (current < 0.0f) {
return current / (-leading);
}
return 0.0f;
default:
return 0.0f;
}
}
private static int constrain(int value, int min, int max) {
if (value > max) {
return max;
}
if (value < min) {
return min;
}
return value;
}
private static float constrain(float value, float min, float max) {
if (value > max) {
return max;
}
if (value < min) {
return min;
}
return value;
}
private void cancelTargetTouch() {
long eventTime = SystemClock.uptimeMillis();
MotionEvent cancel = MotionEvent.obtain(eventTime, eventTime, 3, 0.0f, 0.0f, 0);
this.mTarget.onTouchEvent(cancel);
cancel.recycle();
}
}
| [
"dev@ajmalaju.com"
] | dev@ajmalaju.com |
cec599a005921e3f64b10132b4648664d0eeec0a | d387d435ed6155a739129297f9bc0edd5c931773 | /be-provider/src/main/java/com/ikentop/biz/provider/mapper/DictionaryMapper.java | 64eef81da7f3c2d897448774d14c59b5f887abcd | [] | no_license | EdwardWangYan/MyTest | 4a52f9338e98f6ae6d9330f3232388db314a2c95 | 54a9ac74bf672e2762acd0462468f13fc6770a22 | refs/heads/master | 2022-10-21T17:23:01.311365 | 2021-03-11T05:06:14 | 2021-03-11T05:06:14 | 130,168,768 | 0 | 0 | null | 2022-10-12T19:53:34 | 2018-04-19T06:27:07 | JavaScript | UTF-8 | Java | false | false | 425 | java | package com.ikentop.biz.provider.mapper;
import com.ikentop.biz.model.entity.Dictionary;
import com.ikentop.biz.provider.model.dto.DictionaryInfo;
import com.ikentop.framework.dao.GenericMapperSupport;
import org.apache.ibatis.annotations.Mapper;
/**
* @author : Huqiao
* @date : 2017/9/4
*/
@Mapper
public interface DictionaryMapper extends GenericMapperSupport<Dictionary> {
DictionaryInfo getDetail(String id);
}
| [
"976452322@qq.com"
] | 976452322@qq.com |
e9b499a681f3e6aee6a423ec1ec2e4f13b24a99c | 3afa28ebae414820866911c863717ce27955c67e | /Basic Instant Messenger Client/src/Client.java | 0ad28f7aeeb457162d27720de328c495ec223f05 | [] | no_license | vivekbhalla/BasicInstantMessenger | 0fbf6553107f77b59808bb89c180073748150934 | a186cf52234fe4cbc26c4aea4c0d48984b340bc8 | refs/heads/master | 2016-09-01T18:14:12.558001 | 2014-06-02T13:16:38 | 2014-06-02T13:16:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,101 | java | import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Client extends JFrame{
private static final long serialVersionUID = 1L;
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private String serverIP;
private Socket connection;
// Constructor
public Client(String host){
super("Client Messenger");
serverIP = host;
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
sendMessage(event.getActionCommand());
userText.setText("");
}
}
);
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(400,250);
setVisible(true);
}
// Connect and Chat
public void startRunning(){
try{
connectToServer();
setupStreams();
whileConnected();
}catch(EOFException eof){
showMessage("\n Client terminated Connection!");
}catch(IOException io){
io.printStackTrace();
}finally{
closeConnection();
}
}
// Connect to the Server
private void connectToServer() throws IOException{
showMessage(" Attempting Connection... \n");
// Here 6789 is the port which is used by the server for incoming requests
connection = new Socket(InetAddress.getByName(serverIP), 6789);
showMessage(" Connecting to " + connection.getInetAddress().getHostName());
}
// Get Stream to Send & Receive Messages
private void setupStreams() throws IOException{
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\n Setup Successful! \n");
}
// While you are connected to the server
private void whileConnected() throws IOException{
typeNow(true);
do{
try{
message = (String) input.readObject();
showMessage("\n" + message);
}catch(ClassNotFoundException cnf){
showMessage("\n Error getting message!");
}
}while(!message.equals("SERVER - END"));
}
// Close Streams & Sockets
private void closeConnection(){
showMessage("\n Closing Connection...\n");
typeNow(false);
try{
output.close();
input.close();
connection.close();
}catch(IOException io){
io.printStackTrace();
}
}
// Send Message to Server
private void sendMessage(String message){
try{
output.writeObject("CLIENT - "+ message);
output.flush();
showMessage("\nCLIENT - " + message);
}catch(IOException io){
chatWindow.append("\n Error, can't send message");
}
}
// Updates ChatWindow
private void showMessage(final String text){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
chatWindow.append(text);
}
}
);
}
// Enable user to type
private void typeNow(final boolean tof){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
userText.setEditable(tof);
}
}
);
}
}
| [
"vivek.rumy@gmail.com"
] | vivek.rumy@gmail.com |
a4b1f96609a39a8f345bd2ce9617e6802118c39c | 496fa86f940a8c77ebe4d98c1facafe09fc61b25 | /ComponsitePrimaryKey/src/main/java/com/supportmycode/dao/Main.java | 09c677f6a5970aaddf8100fbb0e789e7593441c0 | [] | no_license | tienph91/Hibernate | 48db3288209fa436309638c8b948c0d0eed75e3b | 1d78a3ebd12509d6e27bb065e37ccad235bc3cf1 | refs/heads/master | 2022-11-26T09:17:47.311246 | 2020-06-19T10:15:14 | 2020-06-19T10:15:14 | 124,269,055 | 0 | 0 | null | 2022-11-24T08:22:47 | 2018-03-07T17:12:34 | Java | UTF-8 | Java | false | false | 746 | java | package com.supportmycode.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.supportmycode.model.Employee;
import com.supportmycode.model.EmployeeKey;
import com.supportmycode.persistence.HibernateUtil;
public class Main {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
EmployeeKey empKey = new EmployeeKey(2, "AmEx");
Employee emp1 = new Employee(empKey, "Nina", "Mayers", "222");
session.saveOrUpdate(emp1);
session.getTransaction().commit();
session.close();
sf.close();
}
}
| [
"hoangtien.cp@gmail.com"
] | hoangtien.cp@gmail.com |
92a5deca925b3554342d9f4661d227e48bc8a0e1 | d7c5121237c705b5847e374974b39f47fae13e10 | /airspan.netspan/src/main/java/Netspan/NBI_17_0/Status/ArrayOfNlmScanStatus.java | 1dca26d1ee97e5c2e92fb71a68910a8131c237a6 | [] | no_license | AirspanNetworks/SWITModules | 8ae768e0b864fa57dcb17168d015f6585d4455aa | 7089a4b6456621a3abd601cc4592d4b52a948b57 | refs/heads/master | 2022-11-24T11:20:29.041478 | 2020-08-09T07:20:03 | 2020-08-09T07:20:03 | 184,545,627 | 1 | 0 | null | 2022-11-16T12:35:12 | 2019-05-02T08:21:55 | Java | UTF-8 | Java | false | false | 2,081 | java |
package Netspan.NBI_17_0.Status;
import java.util.ArrayList;
import java.util.List;
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 ArrayOfNlmScanStatus complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ArrayOfNlmScanStatus">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="NlmScanStatus" type="{http://Airspan.Netspan.WebServices}NlmScanStatus" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfNlmScanStatus", propOrder = {
"nlmScanStatus"
})
public class ArrayOfNlmScanStatus {
@XmlElement(name = "NlmScanStatus", nillable = true)
protected List<NlmScanStatus> nlmScanStatus;
/**
* Gets the value of the nlmScanStatus property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the nlmScanStatus property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getNlmScanStatus().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link NlmScanStatus }
*
*
*/
public List<NlmScanStatus> getNlmScanStatus() {
if (nlmScanStatus == null) {
nlmScanStatus = new ArrayList<NlmScanStatus>();
}
return this.nlmScanStatus;
}
}
| [
"dshalom@airspan.com"
] | dshalom@airspan.com |
ced23b164d47bfac987691af562a8c32fea0e8af | 723cfefde46782fcb1252bdd92b450abf2cd287c | /Java/20190415_exception/src/net/koreate/www/thorwsexam/ThrowsExample.java | 937e0197229444632618d1a63de38b250551dcde | [] | no_license | cutiler/2019_BusanStudy | 8c577f42b05031d788749062c616d23cb49f8aca | ac3ef3a630ce4efd88516f710b09114160ecf445 | refs/heads/master | 2022-12-22T03:06:45.066051 | 2019-08-02T03:56:54 | 2019-08-02T03:56:54 | 185,716,976 | 0 | 0 | null | 2022-12-16T00:57:15 | 2019-05-09T03:06:51 | HTML | UTF-8 | Java | false | false | 392 | java | package net.koreate.www.thorwsexam;
public class ThrowsExample {
public static void main(String[] args){
try {
findClass("java.lang.String2");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void findClass(String path) throws ClassNotFoundException {
Class clazz = Class.forName(path);
}
}
| [
"50136588+cutiler@users.noreply.github.com"
] | 50136588+cutiler@users.noreply.github.com |
4c96c059c4edc8fbca0f669195968d93e962bdae | b264092156402b73a76d8a98fa639b980940a5b7 | /omdb/src/main/java/com/github/diogochbittencourt/omdb/moviedetail/MovieDetailModule.java | c5b1321193498629d9a7de5d818fcbafcb3dd059 | [] | no_license | diogochbittencourt/omdb-movies-android | fff6f57159228a931aeb12258fc0c319313155ef | f4740f2594810247b486b73136d6e2a79bb12818 | refs/heads/master | 2021-04-29T08:03:02.520642 | 2017-01-09T12:49:32 | 2017-01-09T12:49:32 | 77,972,216 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 520 | java | package com.github.diogochbittencourt.omdb.moviedetail;
import com.github.diogochbittencourt.omdb.di.scopes.PerActivity;
import dagger.Module;
import dagger.Provides;
/**
* Created by Diogo Bittencourt on 08/01/17.
*/
@Module
class MovieDetailModule {
private final MovieDetailContract.View view;
MovieDetailModule(MovieDetailContract.View view) {
this.view = view;
}
@Provides
@PerActivity
MovieDetailContract.View providesMovieDetailContractView() {
return view;
}
} | [
"diogochbittencourt@gmail.com"
] | diogochbittencourt@gmail.com |
37acd58fb3be98509acb5ad4114505caec31ec7e | d5135681dcc08802e4d0121920b34765d8bf1ab9 | /SelHandleFrame.java | 76a913089a92f0b25d81cffe9698e4b74048ca03 | [] | no_license | SaniyaShilledar/Selenium-Scripts | ec805fce165c028828b8d42a5f71491506a0128f | 29fe31965c16c4668b3ab7f694dfa722cf29b347 | refs/heads/master | 2020-05-05T07:49:56.602927 | 2019-04-06T14:00:33 | 2019-04-06T14:00:33 | 179,839,565 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 903 | java | package p1;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SelHandleFrame {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "F:\\Selenium Components\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.freecrm.com/");
driver.findElement(By.name("username")).sendKeys("naveenk");
driver.findElement(By.name("username")).sendKeys("test@123");
driver.findElement(By.xpath("//input[@type='submit']")).click();
Thread.sleep(5000);
driver.switchTo().frame("mainpanel");
Thread.sleep(5000);
driver.findElement(By.xpath("//a[contains(text(),''contacts)]")).click();
Thread.sleep(5000);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
917d5c4e50a38964966e1889c0df3a8ff181ff62 | 647ec12ce50f06e7380fdbfb5b71e9e2d1ac03b4 | /com.tencent.minihd.qq/assets/exlibs.2.jar/classes.jar/dub.java | a6a0c87bbaa5f3503f9497aaf0e179ce56105d11 | [] | no_license | tsuzcx/qq_apk | 0d5e792c3c7351ab781957bac465c55c505caf61 | afe46ef5640d0ba6850cdefd3c11badbd725a3f6 | refs/heads/main | 2022-07-02T10:32:11.651957 | 2022-02-01T12:41:38 | 2022-02-01T12:41:38 | 453,860,108 | 36 | 9 | null | 2022-01-31T09:46:26 | 2022-01-31T02:43:22 | Java | UTF-8 | Java | false | false | 644 | java | import android.app.Dialog;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mobileqq.activity.DetailProfileActivity;
public class dub
implements View.OnClickListener
{
public dub(DetailProfileActivity paramDetailProfileActivity) {}
public void onClick(View paramView)
{
if ((this.a.a != null) && (this.a.a.isShowing()) && (this.a.a.getWindow() != null)) {
this.a.a.dismiss();
}
}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.minihd.qq\assets\exlibs.2.jar\classes.jar
* Qualified Name: dub
* JD-Core Version: 0.7.0.1
*/ | [
"98632993+tsuzcx@users.noreply.github.com"
] | 98632993+tsuzcx@users.noreply.github.com |
98654b027c9b6f67a70df08330eaf061c6f01f24 | b5940eadd2e42e0bb18e922c50d3a3fac1b6c374 | /app/src/main/java/com/example/ramona/planyourtrip/Util/Locatii.java | 7a0b017dd17571470bd8bb881980e0ef3a473672 | [] | no_license | ramonabotezatu25/PlanYourTrip | e54a2e4d5cd527caff11b7be074e5b35b295e599 | d5ec16cc2ed33f842c8729c548b1ece0fa44be00 | refs/heads/master | 2018-10-14T19:29:40.769560 | 2018-07-05T20:47:50 | 2018-07-05T20:47:50 | 117,594,012 | 0 | 0 | null | 2018-07-05T20:47:51 | 2018-01-15T20:49:57 | Java | UTF-8 | Java | false | false | 2,609 | java | package com.example.ramona.planyourtrip.Util;
/**
* Created by Ramona on 4/3/2018.
*/
public class Locatii {
private Integer id;
private String nume;
private Integer categorie;
private Integer categorie2;
private String lat;
private String lon;
private String descriere;
private String atractii;
private String restaurante;
private String activitati;
private String link;
public Locatii() {
}
public Locatii(Integer id, String nume, Integer categorie, Integer categorie2, String lat, String lon, String descriere, String atractii, String restaurante, String activitati, String link) {
this.id = id;
this.nume = nume;
this.categorie = categorie;
this.categorie2 = categorie2;
this.lat = lat;
this.lon = lon;
this.descriere = descriere;
this.atractii = atractii;
this.restaurante = restaurante;
this.activitati = activitati;
this.link = link;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNume() {
return nume;
}
public void setNume(String nume) {
this.nume = nume;
}
public Integer getCategorie() {
return categorie;
}
public void setCategorie(Integer categorie) {
this.categorie = categorie;
}
public Integer getCategorie2() {
return categorie2;
}
public void setCategorie2(Integer categorie2) {
this.categorie2 = categorie2;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getDescriere() {
return descriere;
}
public void setDescriere(String descriere) {
this.descriere = descriere;
}
public String getAtractii() {
return atractii;
}
public void setAtractii(String atractii) {
this.atractii = atractii;
}
public String getRestaurante() {
return restaurante;
}
public void setRestaurante(String restaurante) {
this.restaurante = restaurante;
}
public String getActivitati() {
return activitati;
}
public void setActivitati(String activitati) {
this.activitati = activitati;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
}
| [
"iancu_dansilviu@yahoo.ro"
] | iancu_dansilviu@yahoo.ro |
107e7a55ce93e24bedd8bcb86f130b1f37a54d9d | a840a191c6be38d0ad6bac7e950b38ad302c9bf2 | /src/docs/content/reference/current/http/websocket/code/WsSampleJava.java | 49babf4eeb1339a22115da9cb6163878fb0eaed4 | [
"BSD-3-Clause",
"EPL-1.0",
"MIT",
"MPL-2.0",
"GPL-2.0-only",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | lukjuz/gatling | e89b824587062bda284a4556b77da2589932ce85 | 98ad0d7ef5d52466f948932bca8b0805d920d577 | refs/heads/master | 2022-12-11T01:57:53.828781 | 2022-12-07T08:50:04 | 2022-12-07T08:50:04 | 147,641,096 | 0 | 1 | Apache-2.0 | 2022-12-07T08:50:05 | 2018-09-06T08:20:02 | Scala | UTF-8 | Java | false | false | 6,800 | java | /*
* Copyright 2011-2021 GatlingCorp (https://gatling.io)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import io.gatling.javaapi.core.ScenarioBuilder;
import io.gatling.javaapi.http.HttpProtocolBuilder;
import io.gatling.javaapi.http.WsFrameCheck;
import static io.gatling.javaapi.core.CoreDsl.*;
import static io.gatling.javaapi.http.HttpDsl.http;
import static io.gatling.javaapi.http.HttpDsl.ws;
class WsSampleJava {
{
//#wsName
ws("WS Operation").wsName("myCustomName");
//#wsName
//#wsConnect
exec(ws("Connect WS").connect("/room/chat?username=gatling"));
//#wsConnect
//#subprotocol
exec(ws("Connect WS").connect("/room/chat?username=gatling").subprotocol("custom"));
//#subprotocol
//#onConnected
exec(ws("Connect WS").connect("/room/chat?username=gatling")
.onConnected(
exec(ws("Perform auth")
.sendText("Some auth token"))
.pause(1)
));
//#onConnected
//#close
// close with a 1000 status
exec(ws("Close WS").close());
// close with arbitrary status and reason
exec(ws("Close WS").close(1007, "Invalid payload data"));
//#close
//#send
// send text with a Gatling EL string
exec(ws("Message")
.sendText("{\"text\": \"Hello, I'm #{id} and this is message #{i}!\"}"));
// send text with a function
exec(ws("Message")
.sendText(session -> "{\"text\": \"Hello, I'm " + session.getString("id") + " and this is message " + session.getString("i") + "!\"}"));
// send text with ElFileBody
exec(ws("Message")
.sendText(ElFileBody("filePath")));
// send text with ElFileBody
exec(ws("Message")
.sendText(PebbleStringBody("somePebbleTemplate")));
// send text with ElFileBody
exec(ws("Message")
.sendText(PebbleFileBody("filePath")));
// send bytes with a Gatling EL string referencing a byte array in the Session
exec(ws("Message")
.sendBytes("#{bytes}"));
// send bytes with a function
exec(ws("Message")
.sendBytes(session -> new byte[] { 0, 5, 3, 1 }));
// send bytes with RawFileBody
exec(ws("Message")
.sendBytes(RawFileBody("filePath")));
// send bytes with RawFileBody
exec(ws("Message")
.sendBytes(ByteArrayBody("#{bytes}")));
//#send
//#create-single-check
// with a static name
ws.checkTextMessage("checkName")
.check(regex("hello (.*)").saveAs("name"));
// with a Gatling EL string name
ws.checkTextMessage("#{checkName}")
.check(regex("hello (.*)").saveAs("name"));
// with a function name
ws.checkTextMessage(session -> "checkName")
.check(regex("hello (.*)").saveAs("name"));
//#create-single-check
//#create-multiple-checks
ws.checkTextMessage("checkName")
.check(
jsonPath("$.code").ofInt().is(1).saveAs("code"),
jsonPath("$.message").is("OK")
);
//#create-multiple-checks
//#silent-check
ws.checkTextMessage("checkName")
.check(regex("hello (.*)").saveAs("name"))
.silent();
//#silent-check
//#matching
ws.checkTextMessage("checkName")
.matching(jsonPath("$.uuid").is("#{correlation}"))
.check(jsonPath("$.code").ofInt().is(1));
//#matching
WsFrameCheck.Text wsCheck = null;
WsFrameCheck.Text wsCheck1 = wsCheck;
WsFrameCheck.Text wsCheck2 = wsCheck;
//#check-from-connect
exec(ws("Connect").connect("/foo").await(30).on(wsCheck));
//#check-from-connect
//#check-from-message
exec(ws("Send").sendText("hello").await(30).on(wsCheck));
//#check-from-message
//#check-single-sequence
// expecting 2 messages
// 1st message will be validated against wsCheck1
// 2nd message will be validated against wsCheck2
// whole sequence must complete withing 30 seconds
exec(ws("Send").sendText("hello")
.await(30).on(wsCheck1, wsCheck2));
//#check-single-sequence
//#check-multiple-sequence
// expecting 2 messages
// 1st message will be validated against wsCheck1
// 2nd message will be validated against wsCheck2
// both sequences must complete withing 15 seconds
// 2nd sequence will start after 1st one completes
exec(ws("Send").sendText("hello")
.await(15).on(wsCheck1)
.await(15).on(wsCheck2)
);
//#check-multiple-sequence
//#check-matching
exec(ws("Send").sendText("hello")
.await(1).on(
ws.checkTextMessage("checkName")
.matching(jsonPath("$.uuid").is("#{correlation}"))
.check(jsonPath("$.code").ofInt().is(1))
));
//#check-matching
//#protocol
http
// similar to standard `baseUrl` for HTTP,
// serves as root that will be prepended to all relative WebSocket urls
.wsBaseUrl("url")
// similar to standard `baseUrls` for HTTP,
// serves as round-robin roots that will be prepended
// to all relative WebSocket urls
.wsBaseUrls("url1", "url2")
// automatically reconnect a WebSocket that would have been
// closed by someone else than the client.
.wsReconnect()
// set a limit on the number of times a WebSocket will be
// automatically reconnected
.wsMaxReconnects(5)
// configure auto reply for specific WebSocket text messages.
// Example: `wsAutoReplyTextFrame({ case "ping" => "pong" })`
// will automatically reply with message `"pong"`
// when message `"ping"` is received.
// Those messages won't be visible in any reports or statistics.
.wsAutoReplyTextFrame( text ->
text.equals("ping") ? "pong" : null
)
// enable partial support for Engine.IO v4.
// Gatling will automatically respond
// to server ping messages (`2`) with pong (`3`).
// Cannot be used together with `wsAutoReplyTextFrame`.
.wsAutoReplySocketIo4();
//#protocol
//#chatroom-example
HttpProtocolBuilder httpProtocol = http
.baseUrl("http://localhost:9000")
.acceptHeader("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
.doNotTrackHeader("1")
.acceptLanguageHeader("en-US,en;q=0.5")
.acceptEncodingHeader("gzip, deflate")
.userAgentHeader("Gatling2")
.wsBaseUrl("ws://localhost:9000");
ScenarioBuilder scn = scenario("WebSocket")
.exec(http("Home").get("/"))
.pause(1)
.exec(session -> session.set("id", "Gatling" + session.userId()))
.exec(http("Login").get("/room?username=#{id}"))
.pause(1)
.exec(ws("Connect WS").connect("/room/chat?username=#{id}"))
.pause(1)
.repeat(2, "i").on(
exec(
ws("Say Hello WS")
.sendText("{\"text\": \"Hello, I'm #{id} and this is message #{i}!\"}")
.await(30).on(
ws.checkTextMessage("checkName").check(regex(".*I'm still alive.*"))
)
).pause(1)
)
.exec(ws("Close WS").close());
//#chatroom-example
}
}
| [
"slandelle@gatling.io"
] | slandelle@gatling.io |
e573b1378c43581e0bfb1c71efceb4cbf8078416 | 3bd362088cfb8b141c874b6ba7062bb4911f1d20 | /scr/src/main/java/com/scr/model/SwitchMaintenenceHistoryAmendment.java | eee9f0bc5c18e6f4945def3617324d11f2a14bb4 | [] | no_license | gvrc1881/scr-app | 7259e348d95fd1fb21f7f374caae9ff1f0090c4b | 9f197c6c483fda4ef38e339ec373a0d0c0b18f7b | refs/heads/master | 2022-04-22T00:26:09.044291 | 2020-03-18T09:03:39 | 2020-03-18T09:03:39 | 246,826,129 | 0 | 2 | null | null | null | null | UTF-8 | Java | false | false | 6,704 | java | package com.scr.model;
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
/**
* The persistent class for the switch_maintenence_history_amendment database table.
*
*/
@Entity
@Table(name = "switch_maintenence_history_amendment" , uniqueConstraints={@UniqueConstraint(name = "old_pk_switch_maintenence_history_amendment_uniq", columnNames ={"amendment_seq_id", "data_div"})})
@NamedQuery(name="SwitchMaintenenceHistoryAmendment.findAll", query="SELECT s FROM SwitchMaintenenceHistoryAmendment s")
public class SwitchMaintenenceHistoryAmendment implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Long id;
@Column(name="amendment_seq_id")
private String amendmentSeqId;
@Column(name="created_by")
private String createdBy;
@Column(name="created_stamp")
private Timestamp createdStamp;
@Column(name="created_tx_stamp")
private Timestamp createdTxStamp;
@Column(name="data_div")
private String dataDiv;
private String delete;
@Column(name="field_no_io_close")
private String fieldNoIoClose;
@Column(name="field_no_io_close_done")
private String fieldNoIoCloseDone;
@Column(name="field_no_io_open")
private String fieldNoIoOpen;
@Column(name="field_no_io_open_done")
private String fieldNoIoOpenDone;
@Column(name="io_closed_by")
private String ioClosedBy;
@Column(name="io_closed_date_time")
private Timestamp ioClosedDateTime;
@Column(name="io_closed_date_time_done")
private Timestamp ioClosedDateTimeDone;
@Column(name="io_opened_by")
private String ioOpenedBy;
@Column(name="io_opened_date_time")
private Timestamp ioOpenedDateTime;
@Column(name="io_opened_date_time_done")
private Timestamp ioOpenedDateTimeDone;
@Column(name="is_field_operated")
private String isFieldOperated;
@Column(name="last_updated_stamp")
private Timestamp lastUpdatedStamp;
@Column(name="last_updated_tx_stamp")
private Timestamp lastUpdatedTxStamp;
@Column(name="seq_id")
private String seqId;
@Column(name="tpc_no_io_close")
private String tpcNoIoClose;
@Column(name="tpc_no_io_close_done")
private String tpcNoIoCloseDone;
@Column(name="tpc_no_io_open")
private String tpcNoIoOpen;
@Column(name="tpc_no_io_open_done")
private String tpcNoIoOpenDone;
@Column(name="updated_by")
private String updatedBy;
public SwitchMaintenenceHistoryAmendment() {
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getAmendmentSeqId() {
return this.amendmentSeqId;
}
public void setAmendmentSeqId(String amendmentSeqId) {
this.amendmentSeqId = amendmentSeqId;
}
public String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Timestamp getCreatedStamp() {
return this.createdStamp;
}
public void setCreatedStamp(Timestamp createdStamp) {
this.createdStamp = createdStamp;
}
public Timestamp getCreatedTxStamp() {
return this.createdTxStamp;
}
public void setCreatedTxStamp(Timestamp createdTxStamp) {
this.createdTxStamp = createdTxStamp;
}
public String getDataDiv() {
return this.dataDiv;
}
public void setDataDiv(String dataDiv) {
this.dataDiv = dataDiv;
}
public String getDelete() {
return this.delete;
}
public void setDelete(String delete) {
this.delete = delete;
}
public String getFieldNoIoClose() {
return this.fieldNoIoClose;
}
public void setFieldNoIoClose(String fieldNoIoClose) {
this.fieldNoIoClose = fieldNoIoClose;
}
public String getFieldNoIoCloseDone() {
return this.fieldNoIoCloseDone;
}
public void setFieldNoIoCloseDone(String fieldNoIoCloseDone) {
this.fieldNoIoCloseDone = fieldNoIoCloseDone;
}
public String getFieldNoIoOpen() {
return this.fieldNoIoOpen;
}
public void setFieldNoIoOpen(String fieldNoIoOpen) {
this.fieldNoIoOpen = fieldNoIoOpen;
}
public String getFieldNoIoOpenDone() {
return this.fieldNoIoOpenDone;
}
public void setFieldNoIoOpenDone(String fieldNoIoOpenDone) {
this.fieldNoIoOpenDone = fieldNoIoOpenDone;
}
public String getIoClosedBy() {
return this.ioClosedBy;
}
public void setIoClosedBy(String ioClosedBy) {
this.ioClosedBy = ioClosedBy;
}
public Timestamp getIoClosedDateTime() {
return this.ioClosedDateTime;
}
public void setIoClosedDateTime(Timestamp ioClosedDateTime) {
this.ioClosedDateTime = ioClosedDateTime;
}
public Timestamp getIoClosedDateTimeDone() {
return this.ioClosedDateTimeDone;
}
public void setIoClosedDateTimeDone(Timestamp ioClosedDateTimeDone) {
this.ioClosedDateTimeDone = ioClosedDateTimeDone;
}
public String getIoOpenedBy() {
return this.ioOpenedBy;
}
public void setIoOpenedBy(String ioOpenedBy) {
this.ioOpenedBy = ioOpenedBy;
}
public Timestamp getIoOpenedDateTime() {
return this.ioOpenedDateTime;
}
public void setIoOpenedDateTime(Timestamp ioOpenedDateTime) {
this.ioOpenedDateTime = ioOpenedDateTime;
}
public Timestamp getIoOpenedDateTimeDone() {
return this.ioOpenedDateTimeDone;
}
public void setIoOpenedDateTimeDone(Timestamp ioOpenedDateTimeDone) {
this.ioOpenedDateTimeDone = ioOpenedDateTimeDone;
}
public String getIsFieldOperated() {
return this.isFieldOperated;
}
public void setIsFieldOperated(String isFieldOperated) {
this.isFieldOperated = isFieldOperated;
}
public Timestamp getLastUpdatedStamp() {
return this.lastUpdatedStamp;
}
public void setLastUpdatedStamp(Timestamp lastUpdatedStamp) {
this.lastUpdatedStamp = lastUpdatedStamp;
}
public Timestamp getLastUpdatedTxStamp() {
return this.lastUpdatedTxStamp;
}
public void setLastUpdatedTxStamp(Timestamp lastUpdatedTxStamp) {
this.lastUpdatedTxStamp = lastUpdatedTxStamp;
}
public String getSeqId() {
return this.seqId;
}
public void setSeqId(String seqId) {
this.seqId = seqId;
}
public String getTpcNoIoClose() {
return this.tpcNoIoClose;
}
public void setTpcNoIoClose(String tpcNoIoClose) {
this.tpcNoIoClose = tpcNoIoClose;
}
public String getTpcNoIoCloseDone() {
return this.tpcNoIoCloseDone;
}
public void setTpcNoIoCloseDone(String tpcNoIoCloseDone) {
this.tpcNoIoCloseDone = tpcNoIoCloseDone;
}
public String getTpcNoIoOpen() {
return this.tpcNoIoOpen;
}
public void setTpcNoIoOpen(String tpcNoIoOpen) {
this.tpcNoIoOpen = tpcNoIoOpen;
}
public String getTpcNoIoOpenDone() {
return this.tpcNoIoOpenDone;
}
public void setTpcNoIoOpenDone(String tpcNoIoOpenDone) {
this.tpcNoIoOpenDone = tpcNoIoOpenDone;
}
public String getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
} | [
"venkat.thota89@gmail.com"
] | venkat.thota89@gmail.com |
5d2352d4ecef813c39b635a9c0c3d929a152f996 | fa2d04e6a221437acc99b860f7565d21b0f3f456 | /src/_016_Submission_Details.java | 38ecb47c878fdf17ce5044d0182b45495de98f84 | [] | no_license | ravireddy76/Algorithm | 9f010caa9f6389f6658b73a2f593b7b61a368814 | 7531301fc2e8ac6983e1ec9b4b6e815d71b5ccda | refs/heads/master | 2021-09-10T20:01:01.379434 | 2018-04-01T06:10:02 | 2018-04-01T06:10:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,170 | java | import java.util.Arrays;
/**
*
* Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
*
* For example, given array S = {-1 2 1 -4}, and target = 1.
*
* The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
*
* @author Shengyi
*
*/
public class _016_Submission_Details {
public int threeSumClosest(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return 0;
}
Arrays.sort(nums);
int result = 0;
int distance = Integer.MAX_VALUE;
for (int i = 0; i < nums.length - 2; i++) {
int start = i + 1;
int end = nums.length - 1;
while (start < end) {
int temp = nums[i] + nums[start] + nums[end];
int diff = Math.abs(target - temp);
if (diff < distance) {
distance = diff;
result = temp;
}
if (temp == target) {
return target;
} else if (temp < target) {
start++;
} else {
end--;
}
}
}
return result;
}
}
| [
"Shengyi@DESKTOP-7E5IKQ6"
] | Shengyi@DESKTOP-7E5IKQ6 |
16281dd5adf311a5e2a350add0087f4c5a7d56ab | 7e56eaec6b0dfe3dfbc98427429b369bed582cce | /app/src/main/java/com/hoho/beike/adapter/GongYiAdatpter.java | ec79b7ca26862e812c8f6b42571d19110ae356c1 | [] | no_license | 18516833641/NorthEnvironmenAndroird | 4d86719b956a97c2517073212b3c9fdce1929093 | c6635cae06b3624e59e2b3aa3669002ac3fdec8c | refs/heads/master | 2022-12-18T11:03:06.147551 | 2020-09-16T11:19:20 | 2020-09-16T11:19:20 | 286,713,584 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,304 | java | package com.hoho.beike.adapter;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.hoho.beike.R;
import com.hoho.beike.bean.GongYiListBean;
import java.util.List;
/**
* Description:
* Created by Android Studio.
* User: houjianjiang
* Date: 2020/8/20
* Time: 9:17 PM
*/
public class GongYiAdatpter extends BaseQuickAdapter<GongYiListBean, BaseViewHolder> {
public GongYiAdatpter(@Nullable List<GongYiListBean> data) {
super(R.layout.item_gongyi, data);
}
@Override
protected void convert(@NonNull BaseViewHolder helper, GongYiListBean item) {
String v = "";
if(item.getValue().contains("O2")){
v = item.getValue().replace("02","O₂");
} else if (item.getValue().contains("SO2")){
v = item.getValue().replace("SO2", "SO₂");
} else if (item.getValue().contains("m3")){
v = item.getValue().replace("m3", "m³");
} else if (item.getValue().contains("NOX")){
v = item.getValue().replace("NOX", "NOx");
} else {
v = item.getValue();
}
helper.setText(R.id.tv1, item.getName()).setText(R.id.tv_1, v);
}
}
| [
"zhanglei02@sunline.cn"
] | zhanglei02@sunline.cn |
ecd0c71a80f51b64d60d453a9cef7edcb21ff56c | 507de33128c1ebfc5e7d4bc8ef22a2b020091b49 | /LinkedLabel.java | 0ca9d7d73ea4a1464cc3ee8472ce88e43233329f | [] | no_license | AustL/GreenfootGame | 9607639a1fa1f60a556fbb5efb56aafb1ad7b0f7 | 6a8b6d4ea8dc7897e913f3e30ffa11a26e436667 | refs/heads/master | 2022-12-29T12:47:54.038275 | 2020-10-18T05:01:06 | 2020-10-18T05:01:06 | 283,642,685 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,677 | java | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.function.Supplier;
/**
* Class representing linked labels
*
* @author Austin
* @version 0
*/
public class LinkedLabel extends Label
{
private Supplier<String> supplier;
/**
* Constructor for a label linked to a supplier
*
* @param x Top left coordinate x
* @param y Top left coordinate y
* @param width Width of label
* @param height Height of label
* @param colour Background colour of label
* @param supplier A string supplier that returns a string determined by a lambda function
* @param fontSize Font size of text
* @param textColour Colour of text
*/
public LinkedLabel(int x, int y, int width, int height, Color colour, Supplier<String> supplier, int fontSize, Color textColour) {
super(x, y, width, height, colour, "", fontSize, textColour);
this.supplier = supplier;
createImage();
}
/**
* Draw the label as a rectangle to the screen
* Display the text from the supplier in the centre of the rectangle
*/
protected void createImage() {
GreenfootImage image = new GreenfootImage(width, height);
image.setColor(colour);
image.fillRect(0, 0, width, height);
GreenfootImage textImage = new GreenfootImage(supplier.get(), fontSize, textColour, new Color(0, 0, 0, 0));
image.drawImage(textImage, (getWidth() - textImage.getWidth()) / 2, (getHeight() - textImage.getHeight()) / 2);
setImage(image);
}
}
| [
"21chydra@gmail.com"
] | 21chydra@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.