blob_id stringlengths 40 40 | language stringclasses 1
value | repo_name stringlengths 5 132 | path stringlengths 2 382 | src_encoding stringclasses 34
values | length_bytes int64 9 3.8M | score float64 1.5 4.94 | int_score int64 2 5 | detected_licenses listlengths 0 142 | license_type stringclasses 2
values | text stringlengths 9 3.8M | download_success bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
5433b4254ba50a13f9b9f35aacce1049a71b541d | Java | wanggn/MobileSafe-1 | /app/src/main/java/com/example/ling/mobilesafe/activity/HomeActivity.java | UTF-8 | 9,064 | 1.953125 | 2 | [] | no_license | package com.example.ling.mobilesafe.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.ling.mobilesafe.R;
import com.example.ling.mobilesafe.activity.module0.Setup1Activity;
import com.example.ling.mobilesafe.activity.module0.SetupOverActivity;
import com.example.ling.mobilesafe.activity.module1.BlackNumberActivity;
import com.example.ling.mobilesafe.activity.module7.AToolActivity;
import com.example.ling.mobilesafe.activity.module8.SettingActivity;
import com.example.ling.mobilesafe.utils.ConstantValue;
import com.example.ling.mobilesafe.utils.DialogUtil;
import com.example.ling.mobilesafe.utils.Md5Util;
import com.example.ling.mobilesafe.utils.SpUtil;
import com.example.ling.mobilesafe.utils.ToastUtil;
public class HomeActivity extends AppCompatActivity {
private static final String TAG = "HomeActivity";
private GridView gv_home;
private int[] mDrawableIds;
private String[] mTitleStrs;
private AlertDialog mDialog;
// private MyReceiver receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
initUI();
//准备数据
initData();
}
private void initData() {
mTitleStrs = new String[] {
"手机防盗","通信卫士","软件管理","进程管理",
"流量统计","手机杀毒","缓存清理","高级工具","设置中心"};
mDrawableIds = new int[] {
R.drawable.home_safe,R.drawable.home_callmsgsafe,
R.drawable.home_apps,R.drawable.home_taskmanager,
R.drawable.home_netmanager,R.drawable.home_trojan,
R.drawable.home_sysoptimize,R.drawable.home_tools,
R.drawable.home_settings};
gv_home.setAdapter(new MyAdapter());
gv_home.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
showDialog();
break;
case 1:
Intent intent1 = new Intent(HomeActivity.this, BlackNumberActivity.class);
startActivity(intent1);
break;
case 7:
Intent intent7 = new Intent(HomeActivity.this, AToolActivity.class);
startActivity(intent7);
break;
case 8:
Intent intent8 = new Intent(HomeActivity.this,SettingActivity.class);
startActivity(intent8);
break;
}
}
});
}
private void showDialog() {
if(TextUtils.isEmpty(SpUtil.getString(HomeActivity.this,
ConstantValue.MOBILE_SAFE_PSD,""))){
//显示設置初始密码对话框
showSetPsdDialog();
}else {
//显示确认密码对话框
showConfirmDialog();
}
}
private void showConfirmDialog() {
View view = View.inflate(HomeActivity.this,R.layout.dialog_confirm_psd,null);
final EditText ed_confirm_psd = (EditText) view.findViewById(R.id.ed_confirm_psd);
new AlertDialog.Builder(HomeActivity.this)
.setTitle("设置密码")
.setCancelable(false)
.setView(view)
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DialogUtil.setClosable(dialog,true);
}
})
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DialogUtil.setClosable(dialog,false);
String confirmPsd = ed_confirm_psd.getText().toString();
String psd = SpUtil.getString(HomeActivity.this,
ConstantValue.MOBILE_SAFE_PSD,"");
if (psd.equals(Md5Util.MD5(confirmPsd))){
//密碼相同
Intent intent = new Intent(HomeActivity.this,SetupOverActivity.class);
startActivity(intent);
DialogUtil.setClosable(dialog,true);
dialog.dismiss();
}else{
ToastUtil.show(HomeActivity.this,"密碼錯誤");
}
}
})
.show();
}
private void showSetPsdDialog() {
View view = View.inflate(HomeActivity.this,R.layout.dialog_set_psd,null);
final EditText ed_set_psd = (EditText) view.findViewById(R.id.ed_set_psd);
final EditText ed_confirm_psd = (EditText) view.findViewById(R.id.ed_confirm_psd);
new AlertDialog.Builder(HomeActivity.this)
.setTitle("创建密码")
.setView(view)
.setCancelable(false)
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DialogUtil.setClosable(dialog,true);//可自动关闭
}
})
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String psd = ed_set_psd.getText().toString();
String confirmPsd = ed_confirm_psd.getText().toString();
DialogUtil.setClosable(dialog,false);//不可自动关闭
if (TextUtils.isEmpty(psd) || TextUtils.isEmpty(confirmPsd)){
ToastUtil.show(HomeActivity.this,"请输入密码");
}else {
if (psd.equals(confirmPsd)){
Intent intent = new Intent(HomeActivity.this,Setup1Activity.class);
startActivity(intent);
DialogUtil.setClosable(dialog,true);
dialog.dismiss();
SpUtil.putString(HomeActivity.this, ConstantValue.MOBILE_SAFE_PSD,
Md5Util.MD5(psd));
}else {
ToastUtil.show(HomeActivity.this,"两次密码不一致");
}
}
}
})
.show();
}
private void initUI() {
gv_home = (GridView) findViewById(R.id.gv_home);
}
class MyAdapter extends BaseAdapter{
@Override
public int getCount() {
return mDrawableIds.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return mDrawableIds[position];
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = View.inflate(HomeActivity.this,R.layout.item_gridview,null);
TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
ImageView iv_icon = (ImageView) view.findViewById(R.id.iv_icon);
tv_title.setText(mTitleStrs[position]);
iv_icon.setBackgroundResource(mDrawableIds[position]);
return view;
}
}
////测试
// private void test(){
// IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction("android.intent.action.SCREEN_ON");
// receiver = new MyReceiver();
// registerReceiver(receiver, intentFilter);
// }
////
//// private class MyReceiver extends BroadcastReceiver{
//// @Override
//// public void onReceive(Context context, Intent intent) {
//// Log.d(TAG, "变化了");
//// }
//// }
////
//// @Override
//// protected void onDestroy() {
//// unregisterReceiver(receiver);
//// super.onDestroy();
//// }
}
| true |
c5fd51b03083d6baecae7412bfe349e5a8956335 | Java | aymenlaadhari/GTA | /src/src/converter/NatureJourneeConvertor.java | UTF-8 | 1,019 | 1.953125 | 2 | [] | no_license | package converter;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import com.yesserp.domain.gtaparam.NatureJournee;
import com.yesserp.sessionbean.paramgta.gestionnaturejournee.GestionNatureJourneeLocal;
@ManagedBean
@RequestScoped
public class NatureJourneeConvertor implements Converter {
@EJB
GestionNatureJourneeLocal gestionNatureJourneeLocal;
@Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
NatureJournee natureJournee = null;
if (!arg2.trim().equals(""))
natureJournee = gestionNatureJourneeLocal
.findNatureJourneeByCode(arg2);
return natureJournee;
}
@Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object value) {
if (value == null || value.equals(""))
return "";
else
return String.valueOf(((NatureJournee) value).getCodenj());
}
}
| true |
d1a12d38e226561e9115c29230f87b4cd9c03f66 | Java | BartlomiejSzczotka/ParticleSwarmOptimization | /src/PSO/Coordinate.java | UTF-8 | 1,164 | 3.46875 | 3 | [] | no_license | package PSO;
/**
* Here the locations of the particles are defined.
*/
public class Coordinate {
private double x;
private double y;
public Coordinate(double x, double y) {
this.x = x;
this.y = y;
}
public Coordinate multiply(double multiplier){
x = x * multiplier;
y = y * multiplier;
return new Coordinate(x, y);
}
public double getX() {
return x;
}
public double getY() { return y; }
//Unused methods to compute particles
public Coordinate multiplyCoordinates(Coordinate coordinate){
x = x * coordinate.x;
y = y * coordinate.y;
return new Coordinate(x, y);
}
public Coordinate add(Coordinate coordinate){
x = x + coordinate.x;
y = y + coordinate.y;
return new Coordinate(x, y);
}
public Coordinate subtract(Coordinate coordinate){
x = x - coordinate.x;
y = y - coordinate.y;
return new Coordinate(x, y);
}
@Override
public String toString() {
return " x=" + x + ", y=" + y;
}
}
| true |
3d3288d472b264a61f6a3cedcab8f9cb09a3c347 | Java | amilmshaji/20MCA201-ABHILASH_JOHN-OOPS-LAB | /CO5/CO5Q8/CO5Q8.java | UTF-8 | 1,159 | 3.515625 | 4 | [
"MIT"
] | permissive | //Develop a program to handle Key events.
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class CO5Q8 implements KeyListener
{
Label lb1, lbl2, lb;
TextField tf1;
Frame fr;
String s;
CO5Q8()
{
fr = new Frame("KeyEventListener Example");
lb1= new Label(" Key Events will be displayed based on the actions", Label.CENTER);
lbl2= new Label();
lb= new Label();
tf1 = new TextField(20);
fr.setLayout(new FlowLayout());
fr.add(lb1);
fr.add(tf1);
fr.add(lbl2);
tf1.addKeyListener(this);
fr.setSize(460,250);
fr.setVisible(true);
}
public void keyPressed(KeyEvent ev)
{
lbl2.setText(" Key pressed");
}
public void keyReleased(KeyEvent ev)
{
lbl2.setText("Released");
}
public void keyTyped(KeyEvent ev)
{
lbl2.setText("Key is typed");
fr.setVisible(true);
}
public static void main(String[] args)
{
new CO5Q8();
}
} | true |
47a9d2eaed3cf1ddbb29bf7697bd02f15fb0d335 | Java | PranavVyas/PopularMovies | /app/src/main/java/com/pro/vyas/pranav/popularmovies/asyncTaskUtils/LoadVideosAsyncTask.java | UTF-8 | 2,410 | 2.265625 | 2 | [] | no_license | package com.pro.vyas.pranav.popularmovies.asyncTaskUtils;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.ANRequest;
import com.androidnetworking.common.ANResponse;
import com.pro.vyas.pranav.popularmovies.R;
import com.pro.vyas.pranav.popularmovies.models.DetailMovieModel;
import com.pro.vyas.pranav.popularmovies.models.VideosModel;
import java.util.List;
import static com.pro.vyas.pranav.popularmovies.constantUtils.Constants.videoLoadBaseUrl;
public class LoadVideosAsyncTask extends AsyncTask<Void, Void, DetailMovieModel> {
private static final String TAG = "LoadVideosAsyncTask";
private Context ct;
private String movieId;
private DetailMovieModel movieForVideos;
private LoadTrailerAsyncTaskCallback mCallback;
public LoadVideosAsyncTask(Context ct, LoadTrailerAsyncTaskCallback callback) {
this.ct = ct;
this.mCallback = callback;
}
public void loadMovieId(String movieId) {
this.movieId = movieId;
}
@Override
protected DetailMovieModel doInBackground(Void... Void) {
String KEY_API_KEY = "api_key";
String url = videoLoadBaseUrl + movieId + "/videos";
ANRequest requestMovie = AndroidNetworking.get(url)
.addQueryParameter(KEY_API_KEY, ct.getResources().getString(R.string.API_KEY_TMDB))
.build();
Log.d(TAG, "doInBackground: URL IS :" + url);
ANResponse response = requestMovie.executeForObject(DetailMovieModel.class);
if (response.isSuccess()) {
movieForVideos = (DetailMovieModel) response.getResult();
} else {
//Toast.makeText(ct.getApplicationContext(), "Did not Connect", Toast.LENGTH_SHORT).show();
Log.d(TAG, "doInBackground: Did not connect");
}
List<VideosModel> videos = movieForVideos.getResults();
for (int i = 0; i < videos.size(); i++) {
Log.d(TAG, "onPostExecute: Movie Trailer is " + videos.get(i).getKey());
}
return movieForVideos;
}
@Override
protected void onPostExecute(DetailMovieModel detailMovieModel) {
mCallback.onComplete(detailMovieModel);
}
public interface LoadTrailerAsyncTaskCallback {
void onComplete(DetailMovieModel detailMovieModel);
}
}
| true |
5bc09ad728be96cda4bebf32a841660e431eac71 | Java | hpbaotho/medical | /MedicalCrypto/MedicalCrypto-ejb/src/java/beans/facades/medical/KeyManifestFacadeLocal.java | UTF-8 | 618 | 2.046875 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package beans.facades.medical;
import entities.medical.KeyManifest;
import java.util.List;
import javax.ejb.Local;
/**
*
* @author Piotrek
*/
@Local
public interface KeyManifestFacadeLocal {
void create(KeyManifest keyManifest);
void edit(KeyManifest keyManifest);
void remove(KeyManifest keyManifest);
KeyManifest find(Object id);
List<KeyManifest> findByFamilyStatus(String family, String status);
List<KeyManifest> findAll();
void refresh(KeyManifest toRefresh);
}
| true |
d6879b94e849ddf69b5399be9314cf5f1b6f9606 | Java | fsds12/TripAdviserSemiProject | /TripAdviserSemiProject/src/tripAdviser/travel/product/model/service/TravelProductCommentService.java | UTF-8 | 1,510 | 2.21875 | 2 | [] | no_license | package tripAdviser.travel.product.model.service;
import static common.JDBCTemplate.close;
import static common.JDBCTemplate.commit;
import static common.JDBCTemplate.getConnection;
import static common.JDBCTemplate.rollback;
import java.sql.Connection;
import java.util.List;
import tripAdviser.member.model.vo.Comment;
import tripAdviser.travel.product.model.dao.TravelProductCommentDao;
public class TravelProductCommentService {
private Connection conn;
private TravelProductCommentDao dao = new TravelProductCommentDao();
public int insertComment(Comment c) {
conn = getConnection();
int result = dao.insertComment(conn, c);
if(result > 0) {
commit();
}
else {
rollback();
}
close(conn);
return result;
}
public int modifyComment(Comment c) {
conn = getConnection();
int result = dao.modifyComment(conn, c);
if(result > 0) {
commit();
}
else {
rollback();
}
close(conn);
return result;
}
public int deleteComment(int commentNo) {
conn = getConnection();
int result = dao.deleteComment(conn, commentNo);
if(result > 0) {
commit();
}
else {
rollback();
}
close(conn);
return result;
}
public List<Comment> selectComment(int commentRefTrvNo, int cPage, int numPerPage) {
conn = getConnection();
List<Comment> commentList = dao.selectComment(conn, commentRefTrvNo, cPage, numPerPage);
close(conn);
return commentList;
}
}
| true |
77202d1582257785c55344267580e9f95d1c89d6 | Java | perfeccionista-software/perfeccionista-framework | /pagefactory-mobile-api/src/main/java/io/perfeccionista/framework/pagefactory/elements/MobileTextAutocomplete.java | UTF-8 | 5,032 | 1.820313 | 2 | [
"Apache-2.0"
] | permissive | package io.perfeccionista.framework.pagefactory.elements;
import io.perfeccionista.framework.matcher.method.MobileComponentAvailableMatcher;
import io.perfeccionista.framework.matcher.method.MobileElementPropertyAvailableMatcher;
import io.perfeccionista.framework.matcher.method.MobileElementStateAvailableMatcher;
import io.perfeccionista.framework.matcher.method.MobileGetColorAvailableMatcher;
import io.perfeccionista.framework.matcher.method.MobileGetElementBoundsAvailableMatcher;
import io.perfeccionista.framework.matcher.method.MobileGetLabelAvailableMatcher;
import io.perfeccionista.framework.matcher.method.MobileGetScreenshotAvailableMatcher;
import io.perfeccionista.framework.matcher.method.MobileGetTextAvailableMatcher;
import io.perfeccionista.framework.matcher.method.MobileIsDisplayedAvailableMatcher;
import io.perfeccionista.framework.matcher.method.MobileIsInFocusAvailableMatcher;
import io.perfeccionista.framework.matcher.method.MobileIsOnTheScreenAvailableMatcher;
import io.perfeccionista.framework.matcher.method.MobileIsOpenAvailableMatcher;
import io.perfeccionista.framework.matcher.method.MobileIsPresentAvailableMatcher;
import io.perfeccionista.framework.matcher.element.MobileChildElementMatcher;
import io.perfeccionista.framework.matcher.element.MobileTextAutocompleteMatcher;
import io.perfeccionista.framework.matcher.element.MobileTextDropDownListMatcher;
import io.perfeccionista.framework.matcher.element.MobileTextListMatcher;
import io.perfeccionista.framework.matcher.result.MobileIndexesMatcher;
import io.perfeccionista.framework.matcher.result.MobileMultipleIndexedResultMatcher;
import io.perfeccionista.framework.pagefactory.elements.base.MobileChildElement;
import io.perfeccionista.framework.pagefactory.elements.methods.MobileInputTextAvailable;
import io.perfeccionista.framework.pagefactory.emulator.keys.KeyEventsChain;
import org.jetbrains.annotations.NotNull;
public interface MobileTextAutocomplete extends MobileTextDropDownList,
MobileInputTextAvailable, MobileChildElement {
// Actions
@Override
MobileTextAutocomplete executeAction(@NotNull String name, Object... args);
// Asserts
MobileTextAutocomplete should(@NotNull MobileTextAutocompleteMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileTextDropDownListMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileMultipleIndexedResultMatcher<Integer> matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileTextListMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileIndexesMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileChildElementMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileGetColorAvailableMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileGetElementBoundsAvailableMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileGetScreenshotAvailableMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileIsDisplayedAvailableMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileIsInFocusAvailableMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileIsOnTheScreenAvailableMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileIsPresentAvailableMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileComponentAvailableMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileElementPropertyAvailableMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileElementStateAvailableMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileGetLabelAvailableMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileGetTextAvailableMatcher matcher);
@Override
MobileTextAutocomplete should(@NotNull MobileIsOpenAvailableMatcher matcher);
// DropDown
@Override
MobileTextAutocomplete open();
@Override
MobileTextAutocomplete close();
// InputText
@Override
MobileTextAutocomplete clear();
@Override
MobileTextAutocomplete typeText(@NotNull String keys);
@Override
MobileTextAutocomplete replaceText(@NotNull String keys);
@Override
MobileTextAutocomplete sendKeyEvents(@NotNull KeyEventsChain keyEvents);
// ScrollTo
@Override
MobileTextAutocomplete scrollTo();
// @Override
// MobileTextAutocomplete scrollToHorizontally(@NotNull HorizontalDirection scrollDirection, @NotNull MobileTextListFilterBuilder filterBuilder);
// @Override
// MobileTextAutocomplete scrollToVertically(@NotNull VerticalDirection scrollDirection, @NotNull MobileTextListFilterBuilder filterBuilder);
// Tap
@Override
MobileTextAutocomplete tap();
@Override
MobileTextAutocomplete longTap();
@Override
MobileTextAutocomplete doubleTap();
}
| true |
e2dd86119ac2f59440a94f3cb0e4911aab77e815 | Java | dvraja92/FragmentSample | /app/src/main/java/com/anhad/fleetgaurd/model/LoginResponseModel.java | UTF-8 | 5,269 | 2.15625 | 2 | [] | no_license | package com.anhad.fleetgaurd.model;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by Anhad on 07-01-2017.
*/
public class LoginResponseModel {
@SerializedName("status")
@Expose
private Boolean status;
@SerializedName("Message")
@Expose
private String message;
@SerializedName("response")
@Expose
private Response response;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
public class Response {
@SerializedName("user")
@Expose
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
public class User {
@SerializedName("id")
@Expose
private String id;
@SerializedName("first_name")
@Expose
private String firstName;
@SerializedName("last_name")
@Expose
private String lastName;
@SerializedName("username")
@Expose
private String username;
@SerializedName("full_name")
@Expose
private String fullName;
@SerializedName("email")
@Expose
private String email;
@SerializedName("phone")
@Expose
private String phone;
@SerializedName("password")
@Expose
private String password;
@SerializedName("avatar")
@Expose
private Object avatar;
@SerializedName("secret_key")
@Expose
private Object secretKey;
@SerializedName("role")
@Expose
private String role;
@SerializedName("status")
@Expose
private String status;
@SerializedName("last_login")
@Expose
private String lastLogin;
@SerializedName("last_login_ip")
@Expose
private String lastLoginIp;
@SerializedName("created")
@Expose
private String created;
@SerializedName("modified")
@Expose
private String modified;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Object getAvatar() {
return avatar;
}
public void setAvatar(Object avatar) {
this.avatar = avatar;
}
public Object getSecretKey() {
return secretKey;
}
public void setSecretKey(Object secretKey) {
this.secretKey = secretKey;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getLastLogin() {
return lastLogin;
}
public void setLastLogin(String lastLogin) {
this.lastLogin = lastLogin;
}
public String getLastLoginIp() {
return lastLoginIp;
}
public void setLastLoginIp(String lastLoginIp) {
this.lastLoginIp = lastLoginIp;
}
public String getCreated() {
return created;
}
public void setCreated(String created) {
this.created = created;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
}
}
| true |
a0e89ae0224e1251e145c58e875b692e0aac1637 | Java | yuzhe1997/Leetcode-from-start-to-the-end | /1400~1500/1419. Minimum Number of Frogs Croaking.java | UTF-8 | 1,837 | 3.640625 | 4 | [] | no_license | /*
Given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple “croak” are mixed. Return the minimum number of different frogs to finish all the croak in the given string.
A valid "croak" means a frog is printing 5 letters ‘c’, ’r’, ’o’, ’a’, ’k’ sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of valid "croak" return -1.
Example 1:
Input: croakOfFrogs = "croakcroak"
Output: 1
Explanation: One frog yelling "croak" twice.
Example 2:
Input: croakOfFrogs = "crcoakroak"
Output: 2
Explanation: The minimum number of frogs is two.
The first frog could yell "crcoakroak".
The second frog could yell later "crcoakroak".
Example 3:
Input: croakOfFrogs = "croakcrook"
Output: -1
Explanation: The given string is an invalid combination of "croak" from different frogs.
Example 4:
Input: croakOfFrogs = "croakcroa"
Output: -1
Constraints:
1 <= croakOfFrogs.length <= 10^5
All characters in the string are: 'c', 'r', 'o', 'a' or 'k'.
*/
class Solution {
public int minNumberOfFrogs(String croakOfFrogs) {
int N = croakOfFrogs.length();
if (N % 5 != 0) return -1;
char[] croak = new char[] {'c', 'r', 'o', 'a', 'k'};
int[] count = new int[5];
int res = 0;
for (char c: croakOfFrogs.toCharArray()) {
for (int i = 0; i < 5; i++) {
if (c != croak[i]) continue;
count[i]++;
if (i == 0) {
if (count[4] > 0) count[4]--;
else res++;
}
else if (count[i - 1]-- <= 0) return -1;
break;
}
}
return res;
}
} | true |
f8aa9086c50505fd58494f038e2ae9a88cd165b2 | Java | dotterbear/service-eureka-scheduler | /src/main/java/com/dotterbear/service/eureka/scheduler/service/RibbonService.java | UTF-8 | 913 | 2.125 | 2 | [
"MIT"
] | permissive | package com.dotterbear.service.eureka.scheduler.service;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
@Service
public class RibbonService {
private Logger logger = Logger.getLogger(RibbonService.class);
@Autowired RestTemplate restTemplate;
@HystrixCommand(fallbackMethod = "error")
public String call(String serviceName, int port, String path) {
return restTemplate.getForObject(
"http://" + serviceName + ":" + port + "/" + path, String.class);
}
public String error(String serviceName, int port, String path) {
logger.error("Fail to call service: " + serviceName + ", port: " + port + ", path: " + path);
return "sorry, error ribbon hystrix!";
}
}
| true |
ccadaa4eb4d8a9027854d6d496da9e23ffa67008 | Java | lhbd/ScoreAnalysisSys | /app/src/main/java/com/gdin/analyse/activity/RegisterActivity.java | UTF-8 | 8,155 | 2.0625 | 2 | [] | no_license | package com.gdin.analyse.activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;
import com.gdin.analyse.R;
import com.gdin.analyse.adapter.CompleteTextViewAdapter;
import com.gdin.analyse.present.RegisterPresent;
import com.gdin.analyse.tools.CustomAutoCompleteTextView;
import com.gdin.analyse.view.RegisterView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class RegisterActivity extends AppCompatActivity implements RegisterView {
@BindView(R.id.register)
RelativeLayout register;
@BindView(R.id.register_school)
CustomAutoCompleteTextView registerSchool;
@BindView(R.id.register_grade)
Spinner gradeSpinner;
@BindView(R.id.register_class)
Spinner classSpinner;
@BindView(R.id.radioGroup)
RadioGroup radioGroup;
private final int CONFIRM = 0; //确认返回码
private final int CANCEL = 1; //取消返回码
private RegisterPresent registerPresent;
private Bundle data = new Bundle();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.register_layout);
ButterKnife.bind(this);
initWidget();
this.setFinishOnTouchOutside(false);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
setFocusOnRootLayout();
return false;
}
@OnClick(R.id.register_confirm_btn)
public void onClick() {
returnResult();
}
private void returnResult() {
String schoolName = registerSchool.getText().toString();
if (!registerPresent.inputEffective(schoolName)) {
Toast.makeText(RegisterActivity.this, R.string.register_input_school, Toast.LENGTH_SHORT).show();
return;
}else if(gradeSpinner.getSelectedItemPosition() == 0){
Toast.makeText(RegisterActivity.this, R.string.register_check_grade, Toast.LENGTH_SHORT).show();
return;
}else if(classSpinner.getSelectedItemPosition() == 0){
Toast.makeText(RegisterActivity.this, R.string.register_check_class, Toast.LENGTH_SHORT).show();
return;
}else if (!hasCheckedDegree()) {
Toast.makeText(RegisterActivity.this, R.string.register_check_degree, Toast.LENGTH_SHORT).show();
return;
}
data.putString("schoolName", schoolName);
if (data == null)
return;
Intent intent = getIntent();
intent.putExtras(data);
// 设置该SelectCityActivity结果码,并设置结束之后退回的Activity
RegisterActivity.this.setResult(CONFIRM, intent);
// 结束SelectCityActivity
RegisterActivity.this.finish();
}
private boolean hasCheckedDegree() {
for (int i = 0; i < radioGroup.getChildCount(); i++) {
RadioButton radioButton = (RadioButton) radioGroup.getChildAt(i);
if (radioButton.isChecked()) {
return true;
}
}
return false;
}
private void initWidget() {
registerPresent = new RegisterPresent(this);
registerPresent.initData();
//学校
CompleteTextViewAdapter<String> schoolAdapter = new CompleteTextViewAdapter<>(registerPresent.getSchoolData());
registerSchool.setAdapter(schoolAdapter);
registerSchool.setDropDownVerticalOffset(10);
setFocusOnRootLayout();
//年级
ArrayAdapter<String> gradeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, registerPresent.getGradeData());
gradeSpinner.setAdapter(gradeAdapter);
gradeSpinner.setDropDownVerticalOffset(70);
//班级
ArrayAdapter<String> classAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, registerPresent.getClassData());
classSpinner.setAdapter(classAdapter);
classSpinner.setDropDownVerticalOffset(70);
setSpinnerDropDownWidth(gradeSpinner);
setSpinnerDropDownWidth(classSpinner);
initSpinnerListener();
initRadioGroupListener();
}
//把焦点设置到父view上
private void setFocusOnRootLayout() {
register.setFocusable(true);
register.setFocusableInTouchMode(true);
register.requestFocus();
InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(register.getWindowToken(), 0);//从控件所在的窗口中隐藏
}
//注册一个ViewTreeObserver的监听回调,通过监听绘图,在spinner绘制后再调用setDropDownWidth
private void setSpinnerDropDownWidth(final Spinner spinner) {
ViewTreeObserver vto = spinner.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
spinner.getViewTreeObserver().removeOnGlobalLayoutListener(this);
spinner.setDropDownWidth(spinner.getWidth());
}
});
}
//获取老师/学生权限
private void initRadioGroupListener() {
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int id) {
setFocusOnRootLayout();
if (id == R.id.degree_teacher) {
data.putString("loginType", "t");
} else {
data.putString("loginType", "s");
}
}
});
}
//获取年级班级
private void initSpinnerListener() {
registerSchool.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
data.putInt("loginSchoolId", registerPresent.getSchoolId(position));
setFocusOnRootLayout();
}
});
gradeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id) {
data.putString("gradeName", gradeSpinner.getSelectedItem().toString());
data.putInt("loginGradeId", registerPresent.getGradeId(pos));
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
setFocusOnRootLayout();
}
});
classSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id) {
data.putString("className", classSpinner.getSelectedItem().toString());
data.putInt("loginClassId", registerPresent.getClassId(pos));
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
setFocusOnRootLayout();
}
});
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
RegisterActivity.this.setResult(CANCEL, getIntent());
// 结束SelectCityActivity
RegisterActivity.this.finish();
return false;
}
return super.onKeyDown(keyCode, event);
}
}
| true |
2f9de5c905ebead79bc50c414b07bb0f012710f6 | Java | abate2283/Professional-Core-Java-Programing | /eclipse-workspace/PreqPractice/src/looping/ShortQuizzOnLoop.java | UTF-8 | 661 | 3.140625 | 3 | [] | no_license | package looping;
public class ShortQuizzOnLoop {
public static void main(String[] args) {
}
public static void printCategories(String str) {
String stack =( "We have a large number of inventory of things in our wharehouse") + ("in the category: apparel and slightly" )
+( "more in demand category: makeup along with the category: furniture and ..");
int i = 0;
while(true) {
int whareHouse = stack.indexOf("category:", i);
if(whareHouse == -1) break;
int start = whareHouse +9;
int end = stack.indexOf("catergory:", start);
System.out.println(stack.substring(start, end));
i=end+1;
}
}
}
| true |
01a4d38570f223c5739e223b9f66aa01a6e9220b | Java | rederep/course | /src/test/java/PasswordTest.java | UTF-8 | 359 | 2 | 2 | [] | no_license | import org.junit.Test;
import service.Password;
import static org.junit.Assert.assertEquals;
public class PasswordTest {
@Test
public void passwordCheck(){
try {
boolean result = Password.check("123","5WCDh7SLn+oY1PJqnKfL3yfi9EyPZOdyKHRQFh80HmI=$pJKsxaV+ExQ8+cMHzDLqxL/GxMppJZq4sy6pGZ4qR6c=");
assertEquals(true,result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
148ce1c7b19ae49f54f59b39046edf164d5d10dd | Java | wpan1/SWENProj2 | /core/src/com/unimelb/swen30006/partc/iplanning/WorldConverter.java | UTF-8 | 6,527 | 2.8125 | 3 | [] | no_license | package com.unimelb.swen30006.partc.iplanning;
import java.awt.geom.Point2D;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.XmlReader;
import com.badlogic.gdx.utils.XmlReader.Element;
import com.unimelb.swen30006.partc.core.MapReader;
import com.unimelb.swen30006.partc.core.World;
import com.unimelb.swen30006.partc.core.objects.WorldObject;
import com.unimelb.swen30006.partc.roads.Intersection;
import com.unimelb.swen30006.partc.roads.Road;
public class WorldConverter {
// Private variables for storing state and where to get data from
private String fileName;
// Private data variable for minimum road distance
private final float MAX_ROAD_DISTANCE = 50;
// Private data structures for loading things
private ArrayList<Road> roads;
private HashMap<String, Intersection> intersections;
private ArrayList<Vertex> vertexMap;
public WorldConverter(String file){
this.fileName = file;
this.intersections = new HashMap<String, Intersection>();
this.vertexMap = new ArrayList<Vertex>();
initialise();
}
/**
* Getter for world map
* @return world map
*/
public ArrayList<Vertex> getMap(){
return this.vertexMap;
}
/**
* Initialise the converted world
*/
private void initialise(){
try {
// Build the doc factory
FileHandle file = Gdx.files.internal(fileName);
XmlReader reader = new XmlReader();
Element root = reader.parse(file);
// Setup data structures
this.roads = new ArrayList<Road>();
// Process Intersections
Element intersections = root.getChildByName("intersections");
Array<Element> intersectionList = intersections.getChildrenByName("intersection");
for(Element e : intersectionList){
processIntersection(e);
}
// Process Roads
Element roads = root.getChildByName("roads");
Array<Element> roadList = roads.getChildrenByName("road");
for(Element e : roadList){
this.roads.add(processRoad(e));
}
/* Add intersections that are incorrectly labeled in the xml file
* All intersections that have x coordinate 480 do not have
* roads specified connecting to intersections with coordinate
* x of 630, even though they should be.
*/
for (Vertex start : vertexMap){
if (start.point.x == 480.0){
for (Vertex end : vertexMap){
if (end.point.x == 630 && end.point.y == start.point.y){
start.connections.add(end);
end.connections.add(start);
}
}
}
}
} catch (Exception e){
e.printStackTrace();
System.exit(0);
}
}
/**
* Processes intersection
* @param intersectionElement Intersection element
*/
private void processIntersection(Element intersectionElement){
// Retrieve all the data
String roadID = intersectionElement.get("intersection_id");
float x_pos = intersectionElement.getFloat("start_x");
float y_pos = intersectionElement.getFloat("start_y");
float width = intersectionElement.getFloat("width");
float height = intersectionElement.getFloat("height");
// Create the intersection
Intersection i = new Intersection(new Point2D.Double(x_pos, y_pos), width, height);
this.intersections.put(roadID, i);
}
/**
* Adds intersection to graph structure
* @param startElement Starting road element
* @param endElement Ending road element
*/
private void addIntToGraph(Element startElement, Element endElement){
// Create start intersection
String startID = startElement.get("id");
Intersection startInt = this.intersections.get(startID);
Vertex startVer = null;
// Check if vertex is initialised
for (Vertex vertex : this.vertexMap){
if (vertex.point.equals(startInt.pos)){
startVer = vertex;
}
}
// If not inistialised, create new vertex
if (startVer == null){
startVer = new Vertex(startInt.pos, startID);
vertexMap.add(startVer);
}
// Create end intersection
String endID = endElement.get("id");
Intersection endInt = this.intersections.get(endID);
Vertex endVer = null;
// Check if vertex is initialised
for (Vertex vertex : this.vertexMap){
if (vertex.point.equals(endInt.pos)){
endVer = vertex;
}
}
// If not inistialised, create new vertex
if (endVer == null){
endVer = new Vertex(endInt.pos, endID);
vertexMap.add(endVer);
}
for (Vertex vertex : vertexMap){
// Add vertex to the start vertex in graph
if (vertex.point.equals(startInt.pos)){
if (!vertex.findVertex(endVer)){
vertex.connections.add(endVer);
}
}
// Add vertex to the end vertex in graph
if (vertex.point.equals(endInt.pos)){
if (!vertex.findVertex(startVer)){
vertex.connections.add(startVer);
}
}
}
}
/**
* Processes road from xml element
* @param roadElement xml element of road
* @return Returns a road
*/
private Road processRoad(Element roadElement){
// Retrieve data
float startX = roadElement.getFloat("start_x");
float startY = roadElement.getFloat("start_y");
float endX = roadElement.getFloat("end_x");
float endY = roadElement.getFloat("end_y");
float width = roadElement.getFloat("width");
int numLanes = roadElement.getInt("num_lanes");
// Create data types
Point2D.Double startPos = new Point2D.Double(startX, startY);
Point2D.Double endPos = new Point2D.Double(endX, endY);
// Create the road
Road r = new Road(startPos, endPos, width, numLanes, new int[]{0,0});
// Register the intersections
Element intersection = roadElement.getChildByName("intersections");
Element startIntersection = intersection.getChildByName("start");
Element endIntersection = intersection.getChildByName("end");
if (startIntersection != null && endIntersection != null){
addIntToGraph(startIntersection, endIntersection);
}
// Return road
return r;
}
/**
* Finds the closest road to a point and returns this road. Does not consider actual travel distance
* to a road, purely the direct distance
* @param pos the position to check from
* @return the closest road to that position, of null if none are within MAX_ROAD_DISTANCE
*/
public Road closestRoad(Point2D.Double pos){
float minDist = Float.MAX_VALUE;
Road minRoad = null;
for(Road r: this.roads){
float tmpDist = r.minDistanceTo(pos);
if(tmpDist < minDist){
minDist = tmpDist;
minRoad = r;
}
}
return (minDist < MAX_ROAD_DISTANCE) ? minRoad : null;
}
}
| true |
8557c8d9b09958d92fe32822a4ca0ad5f5bdba93 | Java | ViniciusLippel/POOII-Generics | /src/q3/ProdutoX.java | UTF-8 | 1,293 | 2.71875 | 3 | [] | no_license | package q3;
import java.time.LocalDate;
public class ProdutoX {
private int id;
private double preco;
private String fabricante;
private LocalDate dtFabricacao;
public ProdutoX() {
}
public ProdutoX(int id, double preco, String fabricante, LocalDate dtFabricacao) {
super();
this.id = id;
this.preco = preco;
this.fabricante = fabricante;
this.dtFabricacao = dtFabricacao;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPreco() {
return preco;
}
public void setPreco(double preco) {
this.preco = preco;
}
public String getFabricante() {
return fabricante;
}
public void setFabricante(String fabricante) {
this.fabricante = fabricante;
}
public LocalDate getDtFabricacao() {
return dtFabricacao;
}
public void setDtFabricacao(LocalDate dtFabricacao) {
this.dtFabricacao = dtFabricacao;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ProdutoX [id=");
builder.append(id);
builder.append(", preco=");
builder.append(preco);
builder.append(", fabricante=");
builder.append(fabricante);
builder.append(", dtFabricacao=");
builder.append(dtFabricacao);
builder.append("]");
return builder.toString();
}
}
| true |
ac7451fbf3981b6a888ddf91462270de7bbc5542 | Java | rodrigolsoares/exemplo-micro-service-spring-boot | /src/main/java/com/micro/service/resources/ParcelaResource.java | UTF-8 | 1,077 | 2.015625 | 2 | [] | no_license | package com.micro.service.resources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.micro.service.rule.CalculoParcelaRule;
import com.micro.service.rule.ValidaParametrosRule;
import com.micro.service.vo.Requisicao;
@RestController
@RequestMapping(value="/parcelas")
public class ParcelaResource {
Logger LOG = LoggerFactory.getLogger(ParcelaResource.class);
@Autowired
private CalculoParcelaRule calculo;
@Autowired
private ValidaParametrosRule validaParametrosRule;
@GetMapping(produces = "application/json")
public ResponseEntity<?> gerarParcelas(Requisicao requisicao){
LOG.info("Realizando a requisição");
validaParametrosRule.validar(requisicao);
return ResponseEntity.ok().body(calculo.executar(requisicao));
}
}
| true |
8c9caccbe2781db478dc160e03974689420aa1e1 | Java | uk-gov-mirror/UKHomeOffice.eba-envbuild-tool | /eba-platform/environment-build/src/main/java/com/ipt/ebsa/environment/build/execute/BuildNode.java | UTF-8 | 965 | 2.28125 | 2 | [] | no_license | package com.ipt.ebsa.environment.build.execute;
import java.util.ArrayList;
import java.util.List;
import com.ipt.ebsa.environment.data.model.ParameterisedNode;
public class BuildNode {
private ParameterisedNode node;
private BuildContext buildContext;
private List<BuildNode> children = new ArrayList<>();
private BuildNode parent;
public ParameterisedNode getNode() {
return node;
}
public void setNode(ParameterisedNode node) {
this.node = node;
}
public String getId() {
return node.getId();
}
public BuildContext getBuildContext() {
return buildContext;
}
public void setBuildContext(BuildContext buildContext) {
this.buildContext = buildContext;
}
public List<BuildNode> getChildren() {
return children;
}
public void setChildren(List<BuildNode> children) {
this.children = children;
}
public void setParent(BuildNode parent) {
this.parent = parent;
}
public BuildNode getParent() {
return parent;
}
}
| true |
e11d3ad018f9dd0e5e3d1d9ab921f319c708376e | Java | yangmingguang/LY | /src/com/yj/ecard/publics/http/model/request/CrashRequest.java | UTF-8 | 737 | 2.375 | 2 | [] | no_license | /**
* @Title: CrashRequest.java
* @Package com.yj.ecard.publics.http.model.request
* @Description: TODO(用一句话描述该文件做什么)
* @author YangMingGuang
* @date 2015-6-26 下午11:40:37
* @version V1.0
*/
package com.yj.ecard.publics.http.model.request;
/**
* @ClassName: CrashRequest
* @Description: TODO(这里用一句话描述这个类的作用)
* @author YangMingGuang
* @date 2015-6-26 下午11:40:37
*
*/
public class CrashRequest {
public String content;
/**
* @return content
*/
public String getContent() {
return content;
}
/**
* @param content 要设置的 content
*/
public void setContent(String content) {
this.content = content;
}
}
| true |
725489ee9841a5bf4decb53dbc510bb8088c5d8b | Java | Dirt-Craft/DirtRestrict | /src/main/java/net/dirtcraft/dirtrestrict/Configuration/Serializers/ItemKeySerializer.java | UTF-8 | 1,971 | 2.109375 | 2 | [] | no_license | package net.dirtcraft.dirtrestrict.Configuration.Serializers;
import com.google.common.reflect.TypeToken;
import cpw.mods.fml.common.registry.GameRegistry;
import net.dirtcraft.dirtrestrict.Configuration.DataTypes.ItemKey;
import net.dirtcraft.dirtrestrict.Utility.CommandUtils;
import net.minecraft.item.Item;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
@SuppressWarnings("UnstableApiUsage")
public class ItemKeySerializer implements TypeSerializer<ItemKey> {
@Nullable
@Override
public ItemKey deserialize(@NonNull TypeToken<?> type, @NonNull ConfigurationNode value) throws ObjectMappingException {
if (value.getString() == null || value.getString().equalsIgnoreCase("")) return null;
final String[] key = value.getString().split(":");
final String modId = key[0];
final Byte meta = CommandUtils.parseByte(key[key.length -1]).orElse(null);
final String itemId;
if ((key.length == 3 && meta != null) || (key.length == 2 && meta == null)){
final String[] itemIdArr = new String[key.length - (meta == null ? 1 : 2)];
System.arraycopy(key, 1, itemIdArr, 0, key.length - (meta == null? 1 : 2));
itemId = String.join(":", itemIdArr);
} else {
itemId = key[1];
}
Item item = GameRegistry.findItem(modId, itemId);
return new ItemKey(item, meta);
}
@Override
public void serialize(@NonNull TypeToken<?> type, @Nullable ItemKey obj, @NonNull ConfigurationNode value) throws ObjectMappingException {
if (obj == null || obj.item == 0 || Item.getItemById(obj.item) == null) return;
else value.setValue(obj.getUniqueIdentifier());
}
}
| true |
cf98d9c50c2aa2a722b3af0867a0b0955971d6da | Java | vitalik94/JD1_Unit01 | /cycle01/main/Task31.java | UTF-8 | 1,318 | 3.671875 | 4 | [] | no_license | package by.htp.cycle01.main;
import java.util.Scanner;
/* Компьютер генерирует пять чисел в диапазоне от 1 до 15 включительно.
* Человек пытается их угадать. Программа должна выводить угаданные и
* неугаданные числа из тех, что сгенерировала программа,
* а также ошибочные числа пользователя.
*/
public class Task31 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
int m;
int a;
a = 1;
System.out.println("Введите пять чисел от 1 до 15:");
while (a <= 5) {
n = (int) (1 + Math.random() * 15);
m = sc.nextInt();
if (n == m & m > 0 & m <= 15) {
System.out.println("n = " + n + "; m = " + m);
System.out.println("Вы угадали число");
} else if (n != m & m > 0 & m <= 15) {
System.out.println("n = " + n + "; m = " + m);
System.out.println("Вы неугадали число");
} else if (m < 1 | m > 15) {
System.out.println("Введено неверное число");
a = a - 1;
}
a = a + 1;
}
}
}
| true |
1636f6e9bd79f99d0bcaef5070cf0914f301d0ce | Java | Anumanthu/SELENIUM | /src/webdrivertechniques/FramesExamples.java | UTF-8 | 2,913 | 2.984375 | 3 | [] | no_license | package src.webdrivertechniques;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import java.util.concurrent.TimeUnit;
public class FramesExamples {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\akindint\\Desktop\\Selenium Learning\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
// WebDriver driver=new FirefoxDriver();
driver.get("https://jqueryui.com/droppable/");
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
Thread.sleep(2000);
// 1.Css Selector tagname.classname example----- '.' represents class
// 1.Css Selector tagname#id example---- '#' represents id
WebElement e = driver.findElement(By.cssSelector("iframe.demo-frame"));
// Finding how many frames are available
int count = driver.findElements(By.tagName("iframe")).size();//we can find using tag 'frameset' also
//int count1 = driver.findElements(By.tagName("frameset")).size();
System.out.println(count);
// Css Selector tagname[class='value'] regular formula
// driver.findElement(By.cssSelector("iframe[class='demo-frame']"));
// driver.switchTo().frame(e); //passing weblement to as a argument instead of
// index
driver.switchTo().frame(0);// only one frame available 0 means 1st frame 1 means 2nd frame like that
// driver.findElement(By.cssSelector("div#draggable")).click();
WebElement source = driver.findElement(By.cssSelector("div#draggable"));
WebElement target = driver.findElement(By.cssSelector("div#droppable"));
Actions ac = new Actions(driver);
// ***********VVERY IMP: we can do Drag and drop element in 2 ways as shown below****************
//ac.dragAndDrop(source, target).build().perform();
ac.clickAndHold(source).moveToElement(target).release().build().perform();
driver.switchTo().defaultContent();//it will come to normal window from frame
//driver.switchTo().parentFrame(); //This will also do the same as above
//VVV IMP Difference between driver.switchTo().defaultContent() and driver.switchTo().parentFrame()
/*
Scenario : When there are multiple frames and some of them are nested.
iframeMain(Main HTML page)
iframeParent
iframechild
Assume you are in ifrmaechild :
When you do driver.switchTo().parentFrame(); : you will go to iframeParent .
But when you do driver.switchTo().defaultContent(); : you will go to main HTML of page.
Note that in this case you will not go to iframeMain .
*/
}
}
| true |
7cbf821e1c628e5500af16d08407448074adb21d | Java | mhedbiamin/Valomnia-connector | /src/main/java/org/mule/modules/valomnia/entities/Price.java | UTF-8 | 2,277 | 1.984375 | 2 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | /**
* (C) 2016 ApptivIT �. This software is protected by international copyright. Any use of this software is subject to Valomnia User account
* through a sales contract between you and ApptivIT �. If such a user account Valomnia is not in place,
* you can not use the software.
* a copy of Valomnia GENERAL TERMS AND CONDITIONS has-been included with this distribution in the file LICENSE.md
*/
package org.mule.modules.valomnia.entities;
public class Price {
private String priceListReference;
private String itemReference;
private String unitReference;
private String value;
private Object unitPrice;
private Object marginRate;
/**
*
* @return The priceListReference
*/
public String getPriceListReference() {
return priceListReference;
}
/**
*
* @param priceListReference
* The priceListReference
*/
public void setPriceListReference(String priceListReference) {
this.priceListReference = priceListReference;
}
/**
*
* @return The itemReference
*/
public String getItemReference() {
return itemReference;
}
/**
*
* @param itemReference
* The itemReference
*/
public void setItemReference(String itemReference) {
this.itemReference = itemReference;
}
/**
*
* @return The unitReference
*/
public String getUnitReference() {
return unitReference;
}
/**
*
* @param unitReference
* The unitReference
*/
public void setUnitReference(String unitReference) {
this.unitReference = unitReference;
}
/**
*
* @return The value
*/
public String getValue() {
return value;
}
/**
*
* @param value
* The value
*/
public void setValue(String value) {
this.value = value;
}
/**
*
* @return The unitPrice
*/
public Object getUnitPrice() {
return unitPrice;
}
/**
*
* @param unitPrice
* The unitPrice
*/
public void setUnitPrice(Object unitPrice) {
this.unitPrice = unitPrice;
}
/**
*
* @return The marginRate
*/
public Object getMarginRate() {
return marginRate;
}
/**
*
* @param marginRate
* The marginRate
*/
public void setMarginRate(Object marginRate) {
this.marginRate = marginRate;
}
/**
*
* @return The organization
*/
}
| true |
3b8983f987daf21b44dd756e2d7034abadde0069 | Java | yeongyeonkim/SSAFY_Web | /MyMVCProject/JavaResources/src/com/algo/Algo.java | UTF-8 | 338 | 2.703125 | 3 | [] | no_license | package com.algo;
public class Algo {
int num1, num2;
public Algo(String num1, String num2) {
this.num1 = Integer.parseInt(num1);
this.num2 = Integer.parseInt(num2);
}
public int doJob() {
//...ㅇㄱㄹㅈ
return num1 + num2;
}
public int doJob2() {
//...ㅇㄱㄹㅈ
return num1 + num2;
}
}
| true |
a7b9607cee93230800f5ef6523d12ddd6bd2afc8 | Java | jordanmor/vegas-dice-game | /src/main/java/com/tts/vegasdicegame/controller/GameController.java | UTF-8 | 1,134 | 2.453125 | 2 | [] | no_license | package com.tts.vegasdicegame.controller;
import com.tts.vegasdicegame.model.GameResponse;
import com.tts.vegasdicegame.service.GameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GameController {
@Autowired
private GameService gameService;
@GetMapping
public String welcomeResponse() {
return "Welcome to the Vegas Dice Game API!";
}
@CrossOrigin
@GetMapping(value = "/game")
public GameResponse playGame(@RequestParam(required = false) String action) {
return gameService.playGame(action);
}
// Setting a new bet amount is best served on a separate path,
// since there is no need to return a gameResponse
@CrossOrigin
@GetMapping(value = "/change-bet")
public void changeBetAmount(@RequestParam int bet) {
gameService.changeBetAmount(bet);
}
}
| true |
eb8a2cab0f665ecb236a9d7a266168a3a12a4e0b | Java | ElblagPWSZ/MyClinic | /MyClinic/src/java/dao/PatientDB.java | UTF-8 | 2,070 | 2.546875 | 3 | [] | no_license | /*
* 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.util.List;
import model.Doctor;
import model.Entry;
import model.Patient;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
/**
*
* @author Student
*/
public class PatientDB {
public static List<Patient> getPatients()
{
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
try {
Criteria criteria = session.createCriteria(Patient.class).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List<Patient> list = criteria.list();
return list;
} finally {
session.close();
}
}
public static void save(Patient d)
{
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Integer id = (Integer) session.save(d);
d.setId(id);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
}
/*
public static void update(Entry entry)
{
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.update(entry);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw e;
} finally {
session.close();
}
}*/
}
| true |
feac53ebb6ced9b5b3ee7566d865e93bf0ccd9dc | Java | forachange/thrift-all | /thrift-spring/src/main/java/com/yangyang/thrift/service/UserServiceImpl.java | UTF-8 | 1,012 | 2.1875 | 2 | [] | no_license | package com.yangyang.thrift.service;
import com.yangyang.thrift.api.UserRequest;
import com.yangyang.thrift.api.UserResponse;
import com.yangyang.thrift.api.UserService;
import org.apache.thrift.TException;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* Created by chenshunyang on 2016/11/1.
*/
@Service
public class UserServiceImpl implements UserService.Iface{
@Override
public UserResponse userInfo(UserRequest request) throws TException {
try{
UserResponse urp=new UserResponse();
if(request.id.equals("10000")){
urp.setCode("0");
Map<String,String> params= new HashMap<String,String>();
params.put("name", "csy");
urp.setParams(params);
}
System.out.println("接收参数是:id="+request.id);
return urp;
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
| true |
553b909f475e45edf8f213bf70a7595bf7064668 | Java | luisenriquelo/MQST | /src/java/Sockets/Server.java | UTF-8 | 1,387 | 2.90625 | 3 | [] | no_license | /*
package Sockets;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
public class Server extends WebSocketServer{
Scanner src = new Scanner(System.in);
public InetSocketAddress var;
public Server(int puerto) throws UnknownHostException {
super(new InetSocketAddress(puerto));
System.out.println("Esperando conexiones en el puerto " + puerto);
}
@Override
public void onOpen(WebSocket ws, ClientHandshake ch) {
ws.send("Buenas tardes, ¿en qué puedo ayudarle?");
System.out.println("Se ha iniciado una nueva conexión");
}
@Override
public void onClose(WebSocket ws, int i, String string, boolean bln) {
System.out.println("Se ha cerrado la conexión");
}
@Override
public void onMessage(WebSocket ws, String mensaje) {
System.out.println(mensaje);
System.out.println("Escribe un mensaje al cliente");
String msjServer = src.nextLine();
ws.send(msjServer);
}
@Override
public void onError(WebSocket ws, Exception e) {
System.out.println("Error de conexión");
e.printStackTrace();
}
}
*/ | true |
6f6af246fbd55718f6e61458a75513b86c7f55eb | Java | pancara/pointline | /pointline-system-ejb/src/main/java/id/hardana/ejb/system/mdb/MailSystemType.java | UTF-8 | 859 | 2.234375 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package id.hardana.ejb.system.mdb;
/**
*
* @author Trisna
*/
public enum MailSystemType {
MERCHANT_REGISTRATION(0, "Merchant Code"),
PERSONAL_FORGET_PASSWORD(1, "Reset Password"),
OP_MERCHANT_FORGET_PASSWORD(2, "Reset Password"),
GROUP_MERCHANT_REGISTRATION(3, "Group Code");
;
private int mailTypeId;
private String mailType;
private String subject;
private MailSystemType(int mailTypeId, String subject) {
this.mailTypeId = mailTypeId;
this.mailType = name();
this.subject = subject;
}
public int getMailTypeId() {
return mailTypeId;
}
public String getMailType() {
return mailType;
}
public String getSubject() {
return subject;
}
}
| true |
e0438443c75d1179b1f262a3a18ca106a78fdef5 | Java | yhm2046/MyApplication | /app/src/main/java/com/example/myapplication/io/SvStatus.java | UTF-8 | 1,996 | 2.53125 | 3 | [] | no_license | package com.example.myapplication.io;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
/**
* 卫星类,2021.9.4 Saturday,Serializable序列化可以用广播传输
*/
public class SvStatus implements Serializable {
int b;
int b1;
int b2;
float c;
float d;
float e;
float f;
public SvStatus(){}
public SvStatus(int b, int b1, int b2,
float c, float d, float e, float f) {
this.b=b;
this.b1=b1;
this.b2=b2;
this.c=c;
this.d=d;
this.e=e;
this.f=f;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
public int getB1() {
return b1;
}
public void setB1(int b1) {
this.b1 = b1;
}
public int getB2() {
return b2;
}
public void setB2(int b2) {
this.b2 = b2;
}
public float getC() {
return c;
}
public void setC(float c) {
this.c = c;
}
public float getD() {
return d;
}
public void setD(float d) {
this.d = d;
}
public float getE() {
return e;
}
public void setE(float e) {
this.e = e;
}
public float getF() {
return f;
}
public void setF(float f) {
this.f = f;
}
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel dest, int flags) {
// dest.writeInt(b);
// }
// protected SvStatus(Parcel in){
// b=in.readInt();
// }
// public static final Creator<SvStatus>CREATOR =new Creator<SvStatus>() {
// @Override
// public SvStatus createFromParcel(Parcel source) {
// return new SvStatus(source);
// }
//
// @Override
// public SvStatus[] newArray(int size) {
// return new SvStatus[size];
// }
// };
}
| true |
afe491398237dd2530ef4e6568e2da74cee9dde5 | Java | MR-TY/esys-nowo | /esys-nowo/src/main/java/com/qfedu/scene/dao/impl/SiteDao.java | UTF-8 | 421 | 1.710938 | 2 | [] | no_license | package com.qfedu.scene.dao.impl;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import com.qfedu.common.dao.impl.BaseDao;
import com.qfedu.scene.dao.ISiteDao;
import com.qfedu.scene.entity.Site;
@Repository
public class SiteDao extends BaseDao<Site> implements ISiteDao {
private final static Logger LOG = LogManager.getLogger(SiteDao.class);
}
| true |
252edfc75ab4acd12b29728352082e5e198b29cd | Java | Navkash/NEXUS | /app/src/main/java/com/nexus/navkashkrishna/nexusdemo/Adapters/TeamAdapter.java | UTF-8 | 5,040 | 2.09375 | 2 | [] | no_license | package com.nexus.navkashkrishna.nexusdemo.Adapters;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.core.utilities.Utilities;
import com.nexus.navkashkrishna.nexusdemo.Modals.Team;
import com.nexus.navkashkrishna.nexusdemo.ProfileActivity;
import com.nexus.navkashkrishna.nexusdemo.R;
import com.squareup.picasso.Callback;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import static com.nexus.navkashkrishna.nexusdemo.ProfileActivity.FIREBASE_REF_USERS;
public class TeamAdapter extends RecyclerView.Adapter<TeamAdapter.TeamViewHolder>{
public static final int SQUA_PLACEHOLDER = 1;
Context context;
List<Team> mData;
private FirebaseUser mUser;
public TeamAdapter(Context context,List<Team> mData){
this.context=context;
this.mData=mData;
}
@NonNull
@Override
public TeamViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
View view=LayoutInflater.from(context).inflate(R.layout.team_item,parent,false);
return new TeamAdapter.TeamViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull TeamViewHolder viewHolder, int i) {
final Team team = mData.get(i);
// mUser = FirebaseAuth.getInstance().getCurrentUser();
// setPicassoImage(context, mUser.getPhotoUrl().toString(), viewHolder.circleImageView, SQUA_PLACEHOLDER);
// setPicassoImage(context, mData.get(i).getImageSrc(), viewHolder.circleImageView, SQUA_PLACEHOLDER);
viewHolder.nameTextView.setText(team.getName());
viewHolder.desgTextView.setText(team.getDesg());
viewHolder.circleImageView.setImageResource(team.getImage());
viewHolder.phoneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:+91"+team.getPhone()));
context.startActivity(intent);
}
});
viewHolder.whatsAppButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String userName = ""+ FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
String url = "https://api.whatsapp.com/send?phone=91" + team.getWhatsApp() + "&text=Hey! I'm "+userName+".";
intent.setData(Uri.parse(url));
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return mData.size();
}
public class TeamViewHolder extends RecyclerView.ViewHolder {
ImageButton phoneButton,whatsAppButton;
TextView nameTextView,desgTextView;
ImageView circleImageView;
public TeamViewHolder( View itemView) {
super(itemView);
phoneButton=itemView.findViewById(R.id.phone_button);
whatsAppButton=itemView.findViewById(R.id.whatsApp_button);
nameTextView=itemView.findViewById(R.id.team_name);
desgTextView=itemView.findViewById(R.id.team_description);
circleImageView=itemView.findViewById(R.id.team_pic);
}
}
public static void setPicassoImage(final Context context, final String imgSrc, final ImageView iv, final int FLAG){
if (FLAG == SQUA_PLACEHOLDER){
Picasso.with(context).load(imgSrc).placeholder(R.drawable.placeholder_square).fit().networkPolicy(NetworkPolicy.OFFLINE).into(iv, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Picasso.with(context).load(imgSrc).placeholder(R.drawable.placeholder_square).fit().into(iv);
}
});
} else {
Picasso.with(context).load(imgSrc).placeholder(R.drawable.placeholder_square).fit().networkPolicy(NetworkPolicy.OFFLINE).into(iv, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError() {
Picasso.with(context).load(imgSrc).placeholder(R.drawable.placeholder_square).fit().into(iv);
}
});
}
}
}
| true |
dfee832769f424b0331c44e0fe3f88ce0f07e137 | Java | akhonabhokani/BodyPingPong | /src/tests/BarPostionsTest.java | UTF-8 | 1,711 | 2.640625 | 3 | [
"BSD-3-Clause"
] | permissive | /*
* BarPostionsTest.java
*
* Created on May 11, 2006, 11:43 AM
*
* To change this template, choose Tools | Template Manager and locate the
* template. Click the Open in Editor button.
* You can then make changes to the template in the Source Editor.
*/
package tests;
import za.co.meraka.components.BarPositions;
/** $Id: BarPostionsTest.java, v 1.0 May 11, 2006 11:43 AM Akhona Exp $
*
* @author Akhona
* @version $Revision: 1.0 $
*/
public class BarPostionsTest {
/** Creates a new instance of BarPostionsTest */
public BarPostionsTest() {
}
public static void main(String[] args) {
System.out.println("Testing class za.co.meraka.components.BarPositions");
assert BarPositions.HORIZONTAL_BAR_POSITIONS_START_X1 != 5;
assert BarPositions.HORIZONTAL_BAR_POSITIONS_START_X2 == 1019;
assert BarPositions.VERTICAL_BAR_POSITIONS_START_Y1 == 5;
assert BarPositions.VERTICAL_BAR_POSITIONS_START_Y2 == 763;
short hBarPosStartY = 300, vBarPosStartX = 300;
assert BarPositions.horizontalBarYpositions[0] == hBarPosStartY;
assert BarPositions.verticalBarXpositions[0] == vBarPosStartX;
for(int i=1; i<60; i++){
short gap = 3;//pixels
assert BarPositions.horizontalBarYpositions[i] ==
BarPositions.horizontalBarYpositions[i-1] + gap;
assert BarPositions.verticalBarXpositions[i] ==
BarPositions.verticalBarXpositions[i-1] + gap;
}
System.out.println("Finished testing for class za.co.meraka.components.BarPositions");
}
}
| true |
958a76e29222bd20eb5f9b764f1bb215dfe2a3f8 | Java | malcolmwells/apcs-hw | /10-LinkedListIterable/MyLLIterator.java | UTF-8 | 361 | 2.84375 | 3 | [] | no_license | import java.util.*;
import java.io.*;
public class MyLLIterator<E> implements Iterator<E>{
private Node<E> h;
public MyLLIterator(Node<E> h){
this.h = h;
}
public boolean hasNext(){
return h.getNext() != null;
}
public E next(){
E x = h.getData();
h = h.getNext();
return x;
}
public void remove(){
h = h.getNext();
}
} | true |
b93842828b50685a001b6c726310fc28f4d6fdb7 | Java | dragonxu/street_light_yancheng | /resource/src/main/java/com/exc/street/light/resource/entity/sl/LampStrategyAction.java | UTF-8 | 2,708 | 1.9375 | 2 | [] | no_license | /**
* @filename:LampStrategyAction 2020-08-26
* @project sl V1.0
* Copyright(c) 2020 xiezhipeng Co. Ltd.
* All right reserved.
*/
package com.exc.street.light.resource.entity.sl;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
/**
* @Description:TODO(实体类)
*
* @version: V1.0
* @author: xiezhipeng
*
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class LampStrategyAction extends Model<LampStrategyAction> {
private static final long serialVersionUID = 1598412286275L;
@TableId(value = "id", type = IdType.AUTO)
@ApiModelProperty(name = "id" , value = "策略动作表")
private Integer id;
@ApiModelProperty(name = "isOpen" , value = "策略动作类型(1:开灯,0:关灯)")
private Integer isOpen;
@ApiModelProperty(name = "brightness" , value = "亮度,默认0")
private Integer brightness;
@ApiModelProperty(name = "executionTime" , value = "执行时间(时分秒)")
private String executionTime;
@ApiModelProperty(name = "startDate" , value = "开始时间(年月日)")
private String startDate;
@ApiModelProperty(name = "endDate" , value = "结束时间(年月日)")
private String endDate;
@ApiModelProperty(name = "weekValue" , value = "周控制值1-7:周日到周六循环执行")
private Integer weekValue;
@ApiModelProperty(name = "strategyId" , value = "策略id")
private Integer strategyId;
@ApiModelProperty(name = "cron" , value = "cron表达式")
private String cron;
@ApiModelProperty(name = "lightModeId" , value = "亮灯方式id")
private Integer lightModeId;
@ApiModelProperty(name = "deviation" , value = "偏移值(分钟)")
private Integer deviation;
@ApiModelProperty(name = "deviceTypeId" , value = "设备类型id")
private Integer deviceTypeId;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
@ApiModelProperty(name = "createTime" , value = "创建时间")
private Date createTime;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
@ApiModelProperty(name = "updateTime" , value = "修改时间")
private Date updateTime;
@Override
protected Serializable pkVal() {
return this.id;
}
}
| true |
5910132e9a414a33479e27adde0ef7d324886e42 | Java | xiaobiao123/spring-mongodb-redis | /src/test/java/model/T1mediator/mediator1/AbstractColleague.java | UTF-8 | 673 | 3.359375 | 3 | [] | no_license | package model.T1mediator.mediator1;
//抽象同事类
abstract class AbstractColleague {
protected AbstractMediator mediator;
/**
* 既然有中介者,那么每个具体同事必然要与中介者有联系,
* 否则就没必要存在于 这个系统当中,这里的构造函数相当
* 于向该系统中注册一个中介者,以取得联系
*/
public AbstractColleague(AbstractMediator mediator) {
this.mediator = mediator;
}
// 在抽象同事类中添加用于与中介者取得联系(即注册)的方法
public void setMediator(AbstractMediator mediator) {
this.mediator = mediator;
}
} | true |
c10f72403f32611a24e497cf6a5e605325e5ee8f | Java | tigersshi/SchoolExAndroid | /app/src/main/java/com/landscape/schoolexandroid/enums/CardType.java | UTF-8 | 1,030 | 2.765625 | 3 | [] | no_license | package com.landscape.schoolexandroid.enums;
/**
* Created by landscape on 2016/7/3.
*/
public enum CardType {
SINGLE_CHOOSE(1)/*选择题*/,
PACK(2)/*填空题*/,
EXPLAIN(3)/*解答题*/,
DECIDE(4)/*判断题*/,
MULTI_CHOOSE(5)/*多选题*/,
LISTEN_SINGLE_CHOOSE(12)/*听力单选题*/,
LISTEN_PACK(13)/*听力填空题*/,
NONE(0);
int code = 0;
public int getCode() {
return code;
}
CardType(int code) {
this.code = code;
}
public static CardType getType(int code) {
switch (code) {
case 1:
return SINGLE_CHOOSE;
case 2:
return PACK;
case 3:
return EXPLAIN;
case 4:
return DECIDE;
case 5:
return MULTI_CHOOSE;
case 12:
return LISTEN_SINGLE_CHOOSE;
case 13:
return LISTEN_PACK;
default:
return NONE;
}
}
}
| true |
318bf85f91d60cb9ed362af7ac5b7f106ed582c3 | Java | 86gumball/POO | /FichasTP/Ficha4/FBPostComparator.java | UTF-8 | 318 | 2.484375 | 2 | [
"MIT"
] | permissive | import java.util.Comparator;
public class FBPostComparator implements Comparator<FBPost> {
public int compare(FBPost p1, FBPost p2) {
int n1 = p1.getComentarios().size();
int n2 = p2.getComentarios().size();
if (n1 < n2) return 1;
if (n1 > n2) return -1;
return 0;
}
}
| true |
a6a07ef87dfbf98267d3d7f9aec02f02ebdb76ad | Java | shuangge-jb/dormitory | /src/main/java/com/dormitory/controller/student/StudentPostcardController.java | UTF-8 | 2,005 | 2.078125 | 2 | [] | no_license | package com.dormitory.controller.student;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.dormitory.controller.PostcardController;
import com.dormitory.dto.PostcardDTO;
import com.dormitory.entity.Dormitory;
import com.dormitory.entity.Postcard;
import com.dormitory.entity.Student;
import com.dormitory.service.DormitoryService;
import com.dormitory.service.StudentService;
@Controller
@RequestMapping(value = "/student")
public class StudentPostcardController extends PostcardController {
@Resource
private StudentService studentService;
@Resource
private DormitoryService dormitoryService;
@RequestMapping(value = "listPostcardByStudentId.do")
public ModelAndView listPostcardByStudentId(@RequestParam("studentId") Long studentId,
@RequestParam("pageIndex") Integer pageIndex, @RequestParam("pageSize") Integer pageSize) {
ModelAndView modelAndView = new ModelAndView();
Student student = studentService.get(studentId);
Dormitory dormitory = dormitoryService.get(student.getDormitoryId());
Integer buildingId = dormitory.getBuildingId();
List<PostcardDTO> list = postcardService.listByBuildingId(buildingId, pageIndex, pageSize);
Integer total = postcardService.getSizeByBuildingId(buildingId);
Integer totalPage = getTotalPages(total, pageSize);
modelAndView.addObject("data", list);
modelAndView.addObject("total", total);
modelAndView.addObject("totalPages", totalPage);
modelAndView.addObject("pageIndex", pageIndex);
modelAndView.addObject("pageSize", pageSize);
modelAndView.setViewName("studentAnnoucment/myPostCard");
return modelAndView;
}
}
| true |
c5c89456458d46aa781608f759a02e4905d5b5f2 | Java | wjt2487/mxjApp | /src/cn/mxj/mxjapp/util/StringUtils.java | UTF-8 | 3,840 | 3.234375 | 3 | [] | no_license | package cn.mxj.mxjapp.util;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils {
private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
private static final String DEFAULT_DATETIME_PATTERN = "yyyy-MM-dd hh:mm:ss";
public final static String EMPTY = "";
/**
* 格式化日期字符串
*
* @param date
* @param pattern
* @return
*/
public static String formatDate(Date date, String pattern) {
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.format(date);
}
/**
* 格式化日期字符串
*
* @param date
* @return 例如2011-3-24
*/
public static String formatDate(Date date) {
return formatDate(date, DEFAULT_DATE_PATTERN);
}
/**
* 获取当前时间 格式为yyyy-MM-dd 例如2011-07-08
*
* @return
*/
public static String getDate() {
return formatDate(new Date(), DEFAULT_DATE_PATTERN);
}
/**
* 获取当前时间
*
* @return
*/
public static String getDateTime() {
return formatDate(new Date(), DEFAULT_DATETIME_PATTERN);
}
/**
* 将String型格式化,比如想要将2011-11-11格式化成2011年11月11日,就StringPattern("2011-11-11","yyyy-MM-dd","yyyy年MM月dd日").
* @param date String 想要格式化的日期
* @param oldPattern String 想要格式化的日期的现有格式
* @param newPattern String 想要格式化成什么格式
* @return String
*/
public static String stringDatePattern(String date, String oldPattern, String newPattern) {
if (date == null || oldPattern == null || newPattern == null)
return "";
SimpleDateFormat oldSimpleDateFormat = new SimpleDateFormat(oldPattern) ; // 实例化模板对象
SimpleDateFormat newSimpleDateFormat = new SimpleDateFormat(newPattern) ; // 实例化模板对象
Date temp = null ;
try{
temp = oldSimpleDateFormat.parse(date) ; // 将给定的字符串中的日期提取出来
}catch(Exception e){ // 如果提供的字符串格式有错误,则进行异常处理
e.printStackTrace() ; // 打印异常信息
}
return newSimpleDateFormat.format(temp);
}
/**
* 格式化日期时间字符串
*
* @param date
* @return 例如2011-11-30 16:06:54
*/
public static String formatDateTime(Date date) {
return formatDate(date, DEFAULT_DATETIME_PATTERN);
}
public static String join(final ArrayList<String> array, String separator) {
StringBuffer result = new StringBuffer();
if (array != null && array.size() > 0) {
for (String str : array) {
result.append(str);
result.append(separator);
}
result.delete(result.length() - 1, result.length());
}
return result.toString();
}
public static boolean isEmpty(String str) {
return str == null || str.length() == 0;
}
public static boolean isNotEmpty(String str) {
return str != null && str.length() != 0;
}
/**
* 手机号码的验证,严格验证
* @param mobiles 要验证的手机号码
* @return
*/
public static boolean isMobileNO(String mobiles){
Pattern p = Pattern.compile("^((1[3|4|5|7|8][0-9]))\\d{8}$");
Matcher m = p.matcher(mobiles);
return m.matches();
}
/**
* E_mail的验证
* @param email 要验证的email
* @return
*/
public static boolean isEmail(String email){
String str="^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
Pattern p = Pattern.compile(str);
Matcher m = p.matcher(email);
return m.matches();
}
}
| true |
8061677e6c0d0215acb9965cc00fa0ef64361f9b | Java | joshimoo/ImageMatch | /src/main/java/com/sleepycoders/imagematch/metric/IMetric.java | UTF-8 | 210 | 2.0625 | 2 | [
"MIT"
] | permissive | package com.sleepycoders.imagematch.metric;
import com.sleepycoders.imagematch.image.Image;
/**
* @author Joshua Moody (joshimoo@hotmail.de)
*/
public interface IMetric {
float calculate(final Image a, final Image b);
}
| true |
02903fcf707412631a7626898891104cadb6eb8a | Java | ibakuyua/KAYB_SIM | /src/Utilitaires/PontBrownien.java | UTF-8 | 3,638 | 3.390625 | 3 | [] | no_license | package Utilitaires;
/**
* \file Utilitaires.PontBrownien.java
* \brief Implementation of the utilitary PontBrownien
* \author Ibakuyumcu Arnaud
* \author Voong Kwan
* \author Ayutaya Rattanatray
* \author Ruimy Benjamin
* \version 1.0
* \date 10 April 2016
*/
import java.util.Random;
/**
* \class Utilitaires.PontBrownien
* \brief Permit to simulate a Brownian Motion for assets value
*/
public class PontBrownien{
private final static double[] s0 = spotValue(); /**<Values of each asset at 14 April morning*/
/**
* \fn double[][] simuler(int nbreTour, int nbreAction)
* \brief Permit to simulate the price of an asset
*
* \param int nbreTour : Number of step in the game
* \param int nbreAction : Number of asset in the market
*
* \return double[nbreAction][nbreTour] : Price of each share at each step
*/
public static double [][] simuler(int nbreTour, int nbreAction){
double[][] r = new double[nbreAction][nbreTour];
for (int i = 0; i<nbreAction; i++){
// Traitement de chaque action
// Initialisation des deux extrémités
r[i][0] = s0[i];
r[i][nbreTour-1] = s0[i] + normal(0,2.5*nbreTour);
recPB(0,nbreTour-1,r,i);
}
return r;
}
/**
* \fn double normal(double m, double v)
* \brief Simulation of a N(m,v)
* \param double m : Mean
* \param double v : Variance
*
* \return double FN(m,v)
*/
private static double normal(double m, double v){
Random rand = new Random();
double r = rand.nextGaussian();
return m + Math.sqrt(v)*r;
}
/**
* \fn void recPB(int ta, int tb, double[][] r, int i )
* \brief Recursion function for the simulation of a Brownian motion
*
* \param int ta : Left time
* \param int tb : Right time
* \param double[][] r : The matrix to fill
* \param int i : The current share
*/
private static void recPB(int ta, int tb, double[][] r, int i ){
//S'il reste un temps à remplir entre ta et tb (condition d'arret de recursion)
if(tb-ta > 1){
int ti = (ta+tb)/2;
// Remplissage du point du milieu par pont brownien
double m= r[i][ta] + (((double)ti-(double)ta)/((double)tb-(double)ta))*(r[i][tb]-r[i][ta]);
double v= (((double)tb-(double)ti)*((double)ti-(double)ta))/((double)tb-(double)ta);
r[i][ti] = normal(m,v);
// Parcours à gauche
recPB(ta,ti,r,i);
// Parcours à droite
recPB(ti,tb,r,i);
}
}
/**
* \fn double[] spotValue()
* \brief Fill the field s0
*
* \return double[] : Price of each asset at t=0
*/
private static double[] spotValue(){
double [] r = new double[48];
r[0] = 57;
r[1] = 75.64; r[2] = 22.17; r[3] = 30.68; r[4] = 82.10; r[5] = 71.03; r[6] = 15.06; r[7] = 61.28;
r[8] = 77.21; r[9] = 56.56; r[10] = 34.17; r[11] = 93.27; r[12] = 104.70; r[13] = 26.58; r[14] = 11.35;
r[15] = 75.13; r[16] = 116.33; r[17] = 25.04; r[18] = 40.84; r[19] = 141.79; r[20] = 28.5; r[21] = 54.81;
r[22] = 112.55; r[23] = 49.1; r[24] = 52.85; r[25] = 28.86;
r[26] = 72.53; r[27] = 102.86;
r[28] = 92.79; r[29] = 113.32; r[30] = 61.34; r[31] = 31.19; r[32] = 83.34; r[33] = 45.94; r[34] = 666.83;
r[35] = 545.34; r[36] = 142.04; r[37] =7.47; r[38] = 99.41; r[39] = 18.92; r[40] = 12.86; r[41] = 51.19;
r[42] = 80.04; r[43] = 172.06; r[44] = 42.5; r[45] = 64.69; r[46] = 240.98; r[47] = 70.68;
return r;
}
}
| true |
cf814644936929e01ab8d1fa405f4b6e578e35af | Java | julivanmeridius/posgraduacao_puc | /api-vendas-backend/src/main/java/br/com/puc/exception/PessoaInexistenteOuInativaException.java | UTF-8 | 321 | 1.742188 | 2 | [] | no_license | package br.com.puc.exception;
/**
* <strong>Descricao: </strong>
* Trabalho de Conclusao de Curso - Especializacao PUC MINAS
* Curso: Arquitetura de Solucoes
*
* @author Julivan Barbosa da Silva
*
*/
public class PessoaInexistenteOuInativaException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
| true |
dd6c5d071ccebcb109279795a3d96f8c0c5971a7 | Java | XClouded/avp | /agp-core/src/main/java/com/lvsint/settlement/NamedBet.java | UTF-8 | 7,395 | 2.5625 | 3 | [] | no_license | package com.lvsint.settlement;
import java.math.BigDecimal;
import java.math.MathContext;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import com.lvsint.abp.TxJournal;
import com.lvsint.abp.TxJournalFactory;
import com.lvsint.abp.server.settlement.bet.SettlementBet;
import com.lvsint.util.LVSLogger;
/**
* A base class for combinations of accumulator bets, such as a Trixie.
*
* @author hastier
* @created 24 September 2001
* @see com.lvsint.settlement.Bet
* @see com.lvsint.settlement.TrixieBet
* @version 1.00
*/
public class NamedBet implements Bet {
private static final Logger LOG = LVSLogger.getLVSLogger(NamedBet.class);
/**
* Description of the Field
*/
protected List<AbstractBetItem> betItems = new ArrayList<AbstractBetItem>();
/**
* Description of the Field
*/
protected double stake = 0;
private boolean voidBet = false;
private boolean loseBet = false;
/**
* a new NamedBet. The stake we refer to is the stake used on each bet that the named bet contains. I.e. in a Trixie
* there are 4 individual accumulator bets - a b c, a b, a c, b c. This means that the total stake placed on the
* Trixie as a whole is this individual stake multiplied by 4.
*
* @param stake the stake used for individual bets. The total stake on the whole named bet is the number of
* individual bets it contains multiplied by this stake.
*/
public NamedBet(double stake) {
this.stake = stake;
}
/**
* adds a new bet, usually an accumulator, to the named bet. I.e. in a Trixie you would add the following four
* accumulators one by one: a b c a b a c b c
*
* @param betItem an individual accumulator bet
*/
public void add(AbstractBetItem betItem) {
betItems.add(betItem);
}
/**
* adds a list of bet items to a named bet in one go.
*
* @param betItems the list of bet items
*/
public void setBetItemList(List<AbstractBetItem> betItems) {
if (betItems != null) {
this.betItems = betItems;
} else {
betItems = new ArrayList<AbstractBetItem>();
}
}
/**
* Returns winnings or losses excluding stake - ROUNDED to 2dps.
*
* @return Description of the Returned Value
*/
@Override
public double calculateProfitExcludingStake() {
double totalNetWinLoss = calculateNetWinLossUnRounded();
return totalNetWinLoss;
}
/**
* Returns winnings or losses including stake.
*
* @return Description of the Returned Value
*/
@Override
public double calculateProfitIncludingStake() {
double totalReturn = calculateNetWinLossUnRounded();
totalReturn += (stake * betItems.size());
// This must be called after we calculate/populate TxJournal entries.
modifyBetItemsToIncludeStakeOnTxJournals();
return totalReturn;
}
/**
* Returns winnings or losses including stake but unrounded
*
* @return Description of the Returned Value
*/
public double calculateReturnUnrounded() {
double totalReturn = calculateNetWinLossUnRounded();
totalReturn += (stake * betItems.size());
// This must be called after we calculate/populate TxJournal entries.
modifyBetItemsToIncludeStakeOnTxJournals();
return totalReturn;
}
public double calculateNetWinLossUnRounded() {
BigDecimal totalNetWinLoss = BigDecimal.ZERO;
int voidBetItemCount = 0;
int loseBetItemCount = 0;
if (betItems == null) {
return 0.0D;
}
for (AbstractBetItem betItem : betItems) {
double payoutExcludingStake = betItem.calculatePayoutExcludingStake(stake, false, false, false);
BigDecimal payout = BigDecimal.valueOf(payoutExcludingStake);
totalNetWinLoss = totalNetWinLoss.add(payout, MathContext.UNLIMITED);
if (LOG.isDebugEnabled()) {
LOG.debug("ABP-12165 - Bet item [priceExcludingStake=" + betItem.priceExcludingStake
+ "] - Bet item payout = " + payout + " - Bet Total Net Win Loss = " + totalNetWinLoss);
}
if (betItem.isVoid()) {
voidBetItemCount++;
}
if (betItem.isLoser()) {
loseBetItemCount++;
}
}
voidBet = voidBetItemCount == betItems.size();
loseBet = loseBetItemCount == betItems.size();
return totalNetWinLoss.doubleValue();
}
@Override
public boolean isVoid() {
return voidBet;
}
@Override
public boolean isLose() {
return loseBet;
}
@Override
public List<TxJournal> calculateNewTxJournals(SettlementBet settlementBet) {
List<TxJournal> calculatedTxJournals = new ArrayList<TxJournal>();
if (betItems != null) {
for (AbstractBetItem betItem : betItems) {
// we do not write TxJournal entries for non-winning bet items.
if (!betItem.isWinner()) {
continue;
}
// We need to check at this level whether any of the subbets are not winners,
// if so then we do not write TxJournal entry for it.
// In normal circumstances the status 'R' i.e. unresolved should have been saved on the betItem,
// however the existing code in production does not take UNRESOLVED into account
// (i.e. if any subbet component is Loser then mark the betItem as loser,
// otherwise mark it as winner - no UNRESOLVED status involved).
List<AbstractBetItem> subBetItems = betItem.getSubBetItems();
if (subBetItems != null && !subBetItems.isEmpty()) {
if (!areAllSubBetsWinners(subBetItems)) {
continue;
}
}
// We need to populate each individual txJournal's due to the fact that AbstractBetItem
// does not have SettlementBet context
TxJournal txJournal = betItem.getTxJournal();
TxJournalFactory.populateBetItemTxJournal(txJournal, settlementBet);
calculatedTxJournals.add(betItem.getTxJournal());
}
}
return calculatedTxJournals;
}
private static boolean areAllSubBetsWinners(List<AbstractBetItem> subBetItems) {
for (AbstractBetItem subBetItem : subBetItems) {
if (!subBetItem.isWinner()) {
return false;
}
}
return true;
}
private void modifyBetItemsToIncludeStakeOnTxJournals() {
BigDecimal bigDecimalStake = new BigDecimal(stake);
for (AbstractBetItem betItem : betItems) {
TxJournal associatedTxJournal = betItem.getTxJournal();
// TxJournal might be null because the bet is a loser,
// and we do not create TxJournal(s) for losing bets.
if (associatedTxJournal != null) {
BigDecimal creditIncludingStake = associatedTxJournal.getCredit().add(bigDecimalStake);
betItem.getTxJournal().setCredit(creditIncludingStake);
}
}
}
} | true |
d6a878aa6f5f507e0d5895dc2b3311e543f8b0e6 | Java | javanibble/java-algorithms | /src/main/java/com/javanibble/algorithm/sequence/sort/CountingSort.java | UTF-8 | 2,047 | 4.125 | 4 | [
"MIT"
] | permissive | package com.javanibble.algorithm.sequence.sort;
/**
* The CountingSort class implements the Counting Sort algorithm for sorting an array of integers. Counting
* Sort is an integer sorting algorithm. Counting Sort are unlike other sorting algorithms in that it makes
* certain assumptions about the data. It counts the number of objects with a distinct key value, and use
* arithmetic to determine the position of each key. This algorithm does not make use of comparisons to sort
* the values. In simplistic terms, the algorithm counts the number of occurrences of each value in order to
* sort it.
*/
public final class CountingSort {
public void sort(int[] collection) {
if (collection != null) {
int maxValue = findMaxValue(collection);
countingSort(collection, maxValue);
} else {
throw new IllegalArgumentException("Input parameter for array to sort is null.");
}
}
private void countingSort(int[] collection, int maxValue) {
int[] countArray = countOccurrences(collection, maxValue);
reconstructArray(collection, countArray, maxValue);
}
private int findMaxValue(int[] collection) {
int highest = collection[0];
for (int index = 1; index < collection.length; index ++) {
if (collection[index] > highest) {
highest = collection [index];
}
}
return highest;
}
private int[] countOccurrences(int[] collection, int maxValue) {
int[] tempArray = new int[maxValue + 1];
for (int i = 0; i < collection.length; i++) {
int key = collection[i];
tempArray[key]++;
}
return tempArray;
}
private void reconstructArray(int[] collection, int[] countArray, int maxValue) {
int j = 0;
for (int i = 0; i <= maxValue; i++) {
while (countArray[i] > 0) {
collection[j++] = i;
countArray[i]--;
}
}
}
}
| true |
70d1632d16106fa561f79c48c696925d46807a13 | Java | Queliath/BookHouse | /OnlineLibaryBackServer/src/java/businessLogicWS/BusinessLogic.java | UTF-8 | 13,395 | 2.4375 | 2 | [] | no_license | /*
* 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 businessLogicWS;
import dao.AdminDao;
import dao.BookDao;
import dao.CommentDao;
import dao.PurchaseDao;
import dao.RatingDao;
import dao.SectionDao;
import dao.UserDao;
import entity.Admin;
import entity.Book;
import entity.Comment;
import entity.Purchase;
import entity.Rating;
import entity.Section;
import entity.User;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.TreeSet;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.WebParam;
/**
*
* @author Владислав
*/
@WebService(serviceName = "BusinessLogic")
public class BusinessLogic {
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getAllSections")
public List<Section> getAllSections() {
return SectionDao.getAllSections();
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getSectionById")
public Section getSectionById(@WebParam(name = "id") Integer id) {
return SectionDao.getSectionById(id);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getBooksBySection")
public List<Book> getBooksBySection(@WebParam(name = "sectionId") Integer sectionId) {
return BookDao.getBooksBySection(sectionId);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getBookById")
public Book getBookById(@WebParam(name = "id") Integer id) {
return BookDao.getBookById(id);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getCommentsByBook")
public List<Comment> getCommentsByBook(@WebParam(name = "bookId") Integer bookId) {
return CommentDao.getCommentsByBook(bookId);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getAverageRatingByBook")
public Double getAverageRatingByBook(@WebParam(name = "bookId") Integer bookId) {
return RatingDao.getAverageRatingByBook(bookId);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getUserById")
public User getUserById(@WebParam(name = "id") Integer id) {
return UserDao.getUserById(id);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "addComment")
public Boolean addComment(@WebParam(name = "bookId") Integer bookId, @WebParam(name = "userId") Integer userId, @WebParam(name = "content") String content, @WebParam(name = "date") Date date) {
Comment comment = new Comment(bookId, userId, content, date);
return CommentDao.addComment(comment);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "login")
public User login(@WebParam(name = "email") String email, @WebParam(name = "password") String password) {
List<User> users = UserDao.getAllUsers();
for(User user : users)
if(email.equals(user.getEmail()) && password.equals(user.getPassword()))
return user;
List<Admin> admins = AdminDao.getAllAdmins();
for(Admin admin : admins)
if(email.equals(admin.getEmail()) && password.equals(admin.getPassword()))
return new User(email, password, "admin", "admin");
return null;
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "registry")
public Boolean registry(@WebParam(name = "email") String email, @WebParam(name = "password") String password, @WebParam(name = "firstName") String firstName, @WebParam(name = "secondName") String secondName) {
User user = new User(email, password, firstName, secondName);
return UserDao.addUser(user);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getCommentsByUser")
public List<Comment> getCommentsByUser(@WebParam(name = "userId") Integer userId) {
return CommentDao.getCommentsByUser(userId);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getPurchasesByUser")
public List<Purchase> getPurchasesByUser(@WebParam(name = "userId") Integer userId) {
return PurchaseDao.getPurchasesByUser(userId);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "addPurchase")
public Boolean addPurchase(@WebParam(name = "cardNumber") String cardNumber, @WebParam(name = "securityNumber") String securityNumber, @WebParam(name = "bookId") Integer bookId, @WebParam(name = "userId") Integer userId) {
Purchase purchase = new Purchase(bookId, userId, cardNumber, securityNumber, "test", "test", "test");
return PurchaseDao.addPurchase(purchase);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "addRating")
public Boolean addRating(@WebParam(name = "value") Integer value, @WebParam(name = "userId") Integer userId, @WebParam(name = "bookId") Integer bookId) {
Rating rating = new Rating(bookId, userId, value);
return RatingDao.addRating(rating);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getAllBooks")
public List<Book> getAllBooks() {
return BookDao.getAllBooks();
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getBooksByKeyword")
public List<Book> getBooksByKeyword(@WebParam(name = "keyword") String keyword) {
return BookDao.getBooksByKeyword(keyword);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getRatingsByUser")
public List<Rating> getRatingsByUser(@WebParam(name = "userId") Integer userId) {
return RatingDao.getRatingsByUser(userId);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "addSection")
public Boolean addSection(@WebParam(name = "name") String name, @WebParam(name = "description") String description, @WebParam(name = "image") String image) {
Section section = new Section(name, description, image);
return SectionDao.addSection(section);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "updateSection")
public Boolean updateSection(@WebParam(name = "name") String name, @WebParam(name = "description") String description, @WebParam(name = "image") String image, @WebParam(name = "id") Integer id) {
Section section = getSectionById(id);
section.setName(name);
section.setDescription(description);
section.setImage(image);
return SectionDao.updateSection(section);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "deleteSection")
public Boolean deleteSection(@WebParam(name = "id") Integer id) {
Section section = getSectionById(id);
return SectionDao.deleteSection(section);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "addBook")
public Boolean addBook(@WebParam(name = "title") String title, @WebParam(name = "description") String description, @WebParam(name = "preview") String preview, @WebParam(name = "numberOfPages") int numberOfPages, @WebParam(name = "price") int price, @WebParam(name = "year") int year, @WebParam(name = "image") String image, @WebParam(name = "fileName") String fileName, @WebParam(name = "dateOfPublication") Date dateOfPublication, @WebParam(name = "section") Integer section, @WebParam(name = "author") String author) {
Book book = new Book(section, title, description, preview, numberOfPages, price, fileName, author, year, dateOfPublication, image);
return BookDao.addBook(book);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "updateBook")
public Boolean updateBook(@WebParam(name = "id") Integer id, @WebParam(name = "title") String title, @WebParam(name = "description") String description, @WebParam(name = "preview") String preview, @WebParam(name = "numberOfPages") int numberOfPages, @WebParam(name = "price") int price, @WebParam(name = "year") int year, @WebParam(name = "image") String image, @WebParam(name = "fileName") String fileName, @WebParam(name = "dateOfPublication") Date dateOfPublication, @WebParam(name = "section") Integer section, @WebParam(name = "author") String author) {
Book book = getBookById(id);
book.setAuthor(author);
book.setDateOfPublicaion(dateOfPublication);
book.setDescription(description);
book.setFileName(fileName);
book.setImage(image);
book.setNumberOfPages(numberOfPages);
book.setPreview(preview);
book.setPrice(price);
book.setSection(section);
book.setTitle(title);
book.setYear(year);
return BookDao.updateBook(book);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "deleteBook")
public Boolean deleteBook(@WebParam(name = "id") Integer id) {
Book book = getBookById(id);
return BookDao.deleteBook(book);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getTopBooksByRating")
public List<Book> getTopBooksByRating() {
List<Book> allBooks = getAllBooks();
Comparator<Book> comp = (book1, book2) -> {
Double rating1 = RatingDao.getAverageRatingByBook(book1.getId()), rating2 = RatingDao.getAverageRatingByBook(book2.getId());
return rating2.compareTo(rating1);
};
TreeSet<Book> sortedBooks = new TreeSet<>(comp);
for(Book book: allBooks)
sortedBooks.add(book);
return new ArrayList(sortedBooks);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getTopBooksByComment")
public List<Book> getTopBooksByComment() {
List<Book> allBooks = getAllBooks();
Comparator<Book> comp = (book1, book2) -> {
Integer numberOfComments1 = CommentDao.getCommentsByBook(book1.getId()).size(), numberOfComments2 = CommentDao.getCommentsByBook(book2.getId()).size();
return numberOfComments2.compareTo(numberOfComments1);
};
TreeSet<Book> sortedBooks = new TreeSet<>(comp);
for(Book book: allBooks)
sortedBooks.add(book);
return new ArrayList(sortedBooks);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getTopBooksByPurchases")
public List<Book> getTopBooksByPurchases() {
List<Book> allBooks = getAllBooks();
Comparator<Book> comp = (book1, book2) -> {
Integer numberOfPurchases1 = PurchaseDao.getPurchasesByBook(book1.getId()).size(), numberOfPurchases2 = PurchaseDao.getPurchasesByBook(book2.getId()).size();
return numberOfPurchases2.compareTo(numberOfPurchases1);
};
TreeSet<Book> sortedBooks = new TreeSet<>(comp);
for(Book book: allBooks)
sortedBooks.add(book);
return new ArrayList(sortedBooks);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getPurchasesByBook")
public List<Purchase> getPurchasesByBook(@WebParam(name = "bookId") Integer bookId) {
return PurchaseDao.getPurchasesByBook(bookId);
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getPurchasesBySectionChart")
public List<Integer> getPurchasesBySectionChart() {
List<Section> sections = SectionDao.getAllSections();
List<Integer> purchasesBySection = new ArrayList<>();
for(Section section : sections){
Integer purchases = 0;
List<Book> books = BookDao.getBooksBySection(section.getId());
for(Book book : books){
purchases += PurchaseDao.getPurchasesByBook(book.getId()).size();
}
purchasesBySection.add(purchases);
}
return purchasesBySection;
}
/**
* Операция веб-службы
*/
@WebMethod(operationName = "getPurchasesByPriceChart")
public List<Integer> getPurchasesByPriceChart() {
List<Integer> purchasesByPrice = new ArrayList<>();
for(int minPrice = 0, maxPrice = 50000; maxPrice <= 300000; minPrice += 50000, maxPrice += 50000){
List<Book> books = BookDao.getBooksByPrice(minPrice, maxPrice);
Integer purchases = 0;
for(Book book : books)
purchases += PurchaseDao.getPurchasesByBook(book.getId()).size();
purchasesByPrice.add(purchases);
}
return purchasesByPrice;
}
}
| true |
fe3ab98f1285fadc8aa6026bae043afdec4de5dc | Java | vzhovnitsky/notifee | /android/src/main/java/app/notifee/core/model/TimestampTriggerModel.java | UTF-8 | 4,004 | 2.421875 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package app.notifee.core.model;
/*
* Copyright (c) 2016-present Invertase Limited & Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this library 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 android.os.Bundle;
import androidx.annotation.NonNull;
import java.util.concurrent.TimeUnit;
public class TimestampTriggerModel {
private Bundle mTimeTriggerBundle;
private int mInterval = -1;
private TimeUnit mTimeUnit = null;
private Boolean mWithAlarmManager = false;
private Boolean mAllowWhileIdle = false;
private String mRepeatFrequency = null;
public static final String HOURLY = "HOURLY";
public static final String DAILY = "DAILY";
public static final String WEEKLY = "WEEKLY";
private static final int MINUTES_IN_MS = 60 * 1000;
private static final long HOUR_IN_MS = 60 * MINUTES_IN_MS;
private static final long DAY_IN_MS = 24 * HOUR_IN_MS;
private static final String TAG = "TimeTriggerModel";
private TimestampTriggerModel(Bundle bundle) {
mTimeTriggerBundle = bundle;
// set initial values
TimeUnit timeUnit = null;
if (mTimeTriggerBundle.containsKey("repeatFrequency")) {
Double d = mTimeTriggerBundle.getDouble("repeatFrequency");
int repeatFrequency = d.intValue();
switch (repeatFrequency) {
case -1:
// default value for one-time trigger
break;
case 0:
mInterval = 1;
mTimeUnit = TimeUnit.HOURS;
mRepeatFrequency = HOURLY;
break;
case 1:
mInterval = 1;
mTimeUnit = TimeUnit.DAYS;
mRepeatFrequency = DAILY;
break;
case 2:
// weekly, 7 days
mInterval = 7;
mTimeUnit = TimeUnit.DAYS;
mRepeatFrequency = WEEKLY;
break;
}
}
if (mTimeTriggerBundle.containsKey("alarmManager")) {
mWithAlarmManager = true;
Bundle alarmManagerBundle = mTimeTriggerBundle.getBundle("alarmManager");
if (alarmManagerBundle.containsKey("allowWhileIdle")) {
mAllowWhileIdle = alarmManagerBundle.getBoolean("allowWhileIdle");
}
}
}
public static TimestampTriggerModel fromBundle(@NonNull Bundle bundle) {
return new TimestampTriggerModel(bundle);
}
public long getTimestamp() {
return (long) mTimeTriggerBundle.getDouble("timestamp");
}
public long getDelay() {
long delay = 0;
if (mTimeTriggerBundle.containsKey("timestamp")) {
long timestamp = (long) mTimeTriggerBundle.getDouble("timestamp");
if (timestamp > 0) {
delay = Math.round((timestamp - System.currentTimeMillis()) / 1000);
}
}
return delay;
}
public long getNextTimestamp() {
long timestamp = getTimestamp();
switch (mRepeatFrequency) {
case TimestampTriggerModel.WEEKLY:
timestamp = timestamp + 7 * DAY_IN_MS;
break;
case TimestampTriggerModel.DAILY:
timestamp = timestamp + DAY_IN_MS;
break;
case TimestampTriggerModel.HOURLY:
timestamp = timestamp + HOUR_IN_MS;
break;
}
return timestamp;
}
public int getInterval() {
return mInterval;
}
public TimeUnit getTimeUnit() {
return mTimeUnit;
}
public Boolean getWithAlarmManager() {
return mWithAlarmManager;
}
public Boolean getAllowWhileIdle() {
return mAllowWhileIdle;
}
public String getRepeatFrequency() {
return mRepeatFrequency;
}
public Bundle toBundle() {
return (Bundle) mTimeTriggerBundle.clone();
}
}
| true |
f002caa4d212ee440c1baeca8273c762bccf0a62 | Java | Robert-Miotk/ZSE_Praktyki | /src/third_week/packages/zadania/zadanie3/zadanie3.java | UTF-8 | 198 | 2.515625 | 3 | [] | no_license | package third_week.packages.zadania.zadanie3;
public class zadanie3 {
protected int mnozenie(int x, int y){
int z = x * y;
System.out.print("Wynik: ");
return z;
}
} | true |
b0b13f7192b3e539bced45eb0671c00ad3bd91e2 | Java | Android-linpengdiao/android-kuaimu | /app/src/main/java/com/kuaimu/android/app/model/WorksDetail.java | UTF-8 | 9,261 | 2.015625 | 2 | [] | no_license | package com.kuaimu.android.app.model;
public class WorksDetail {
/**
* code : 200
* msg : 成功
* data : {"id":21,"created_at":"2020-07-03 22:12:13","updated_at":"2020-07-09 00:27:56","is_deleted":2,"tourist_id":6,"tourist_name":"青春有你制作人","active_id":1,"active_name":"这就是街舞3","video":"http://enjoy-money.oss-cn-beijing.aliyuncs.com/TXVideo_20200703_134008.mp4","img":"upload/20200703101207p4M40.jpg","recommend":2,"pre_votes":13,"final_votes":0,"rematch_votes":0,"club_id":8,"club_name":"青春有你","assist_num":3,"comment_num":2,"name":"来来回回","play_num":0,"status":1,"rank":1,"rank_vote":0,"is_person_follow":false,"is_assist":true,"tourist":{"id":6,"name":"青春有你制作人","avatar":"upload/20200606055631F8mzM.jpg","yunxin_token":"a7a89edf135d83a0ea51355e7383f08a","yunxin_accid":"27915679"}}
*/
private int code;
private String msg;
private DataBean data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public static class DataBean {
/**
* id : 21
* created_at : 2020-07-03 22:12:13
* updated_at : 2020-07-09 00:27:56
* is_deleted : 2
* tourist_id : 6
* tourist_name : 青春有你制作人
* active_id : 1
* active_name : 这就是街舞3
* video : http://enjoy-money.oss-cn-beijing.aliyuncs.com/TXVideo_20200703_134008.mp4
* img : upload/20200703101207p4M40.jpg
* recommend : 2
* pre_votes : 13
* final_votes : 0
* rematch_votes : 0
* club_id : 8
* club_name : 青春有你
* assist_num : 3
* comment_num : 2
* name : 来来回回
* play_num : 0
* status : 1
* rank : 1
* rank_vote : 0
* is_person_follow : false
* is_assist : true
* tourist : {"id":6,"name":"青春有你制作人","avatar":"upload/20200606055631F8mzM.jpg","yunxin_token":"a7a89edf135d83a0ea51355e7383f08a","yunxin_accid":"27915679"}
*/
private int id;
private String created_at;
private String updated_at;
private int is_deleted;
private int tourist_id;
private String tourist_name;
private int active_id;
private String active_name;
private String video;
private String img;
private int recommend;
private int pre_votes;
private int final_votes;
private int rematch_votes;
private int club_id;
private String club_name;
private int assist_num;
private int comment_num;
private String name;
private int play_num;
private int status;
private int rank;
private int rank_vote;
private boolean is_person_follow;
private boolean is_assist;
private TouristBean tourist;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public int getIs_deleted() {
return is_deleted;
}
public void setIs_deleted(int is_deleted) {
this.is_deleted = is_deleted;
}
public int getTourist_id() {
return tourist_id;
}
public void setTourist_id(int tourist_id) {
this.tourist_id = tourist_id;
}
public String getTourist_name() {
return tourist_name;
}
public void setTourist_name(String tourist_name) {
this.tourist_name = tourist_name;
}
public int getActive_id() {
return active_id;
}
public void setActive_id(int active_id) {
this.active_id = active_id;
}
public String getActive_name() {
return active_name;
}
public void setActive_name(String active_name) {
this.active_name = active_name;
}
public String getVideo() {
return video;
}
public void setVideo(String video) {
this.video = video;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public int getRecommend() {
return recommend;
}
public void setRecommend(int recommend) {
this.recommend = recommend;
}
public int getPre_votes() {
return pre_votes;
}
public void setPre_votes(int pre_votes) {
this.pre_votes = pre_votes;
}
public int getFinal_votes() {
return final_votes;
}
public void setFinal_votes(int final_votes) {
this.final_votes = final_votes;
}
public int getRematch_votes() {
return rematch_votes;
}
public void setRematch_votes(int rematch_votes) {
this.rematch_votes = rematch_votes;
}
public int getClub_id() {
return club_id;
}
public void setClub_id(int club_id) {
this.club_id = club_id;
}
public String getClub_name() {
return club_name;
}
public void setClub_name(String club_name) {
this.club_name = club_name;
}
public int getAssist_num() {
return assist_num;
}
public void setAssist_num(int assist_num) {
this.assist_num = assist_num;
}
public int getComment_num() {
return comment_num;
}
public void setComment_num(int comment_num) {
this.comment_num = comment_num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPlay_num() {
return play_num;
}
public void setPlay_num(int play_num) {
this.play_num = play_num;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public int getRank_vote() {
return rank_vote;
}
public void setRank_vote(int rank_vote) {
this.rank_vote = rank_vote;
}
public boolean isIs_person_follow() {
return is_person_follow;
}
public void setIs_person_follow(boolean is_person_follow) {
this.is_person_follow = is_person_follow;
}
public boolean isIs_assist() {
return is_assist;
}
public void setIs_assist(boolean is_assist) {
this.is_assist = is_assist;
}
public TouristBean getTourist() {
return tourist;
}
public void setTourist(TouristBean tourist) {
this.tourist = tourist;
}
public static class TouristBean {
/**
* id : 6
* name : 青春有你制作人
* avatar : upload/20200606055631F8mzM.jpg
* yunxin_token : a7a89edf135d83a0ea51355e7383f08a
* yunxin_accid : 27915679
*/
private int id;
private String name;
private String avatar;
private String yunxin_token;
private String yunxin_accid;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getYunxin_token() {
return yunxin_token;
}
public void setYunxin_token(String yunxin_token) {
this.yunxin_token = yunxin_token;
}
public String getYunxin_accid() {
return yunxin_accid;
}
public void setYunxin_accid(String yunxin_accid) {
this.yunxin_accid = yunxin_accid;
}
}
}
}
| true |
df6d4ffcb2e45ac44935bd59d3ebc7a0ecaf4470 | Java | irinajinli/four-minigames | /phase1/Game1/app/src/main/java/com/example/game1/presentation/view/user/StatisticsActivity.java | UTF-8 | 3,606 | 2.171875 | 2 | [] | no_license | package com.example.game1.presentation.view.user;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import com.example.game1.R;
import com.example.game1.presentation.presenter.AppManager;
import com.example.game1.presentation.presenter.UserManager;
public class StatisticsActivity extends AppCompatActivity {
private UserManager userManager = AppManager.getInstance().getUserManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_statistics);
EditText infoText = findViewById(R.id.infoText);
infoText.setText("Your score = points + (" + AppManager.STAR_FACTOR + " x stars)");
EditText currPointsText = findViewById(R.id.currPointsText);
currPointsText.setText(String.valueOf(userManager.getCurrentUser().getCurrentPoints()));
EditText currStarsText = findViewById(R.id.currStarsText);
currStarsText.setText(String.valueOf(userManager.getCurrentUser().getCurrentStars()));
EditText currTapsText = findViewById(R.id.currTapsText);
currTapsText.setText(String.valueOf(userManager.getCurrentUser().getCurrentTaps()));
EditText topPointsText = findViewById(R.id.topPointsText);
topPointsText.setText(String.valueOf(userManager.getCurrentUser().getTopPoints()));
EditText topStarsText = findViewById(R.id.topStarsText);
topStarsText.setText(String.valueOf(userManager.getCurrentUser().getTopStars()));
EditText topTapsText = findViewById(R.id.topTapsText);
topTapsText.setText(String.valueOf(userManager.getCurrentUser().getTopTaps()));
if (userManager.getTopUser() != null) {
System.out.println("=========================");
System.out.println(userManager.getTopUser().getUserName());
EditText topPlayerText = findViewById(R.id.topPlayerText);
topPlayerText.setText("Top player: " + userManager.getTopUser().getUserName());
EditText topPlayerPointsText = findViewById(R.id.topPlayerPointsText);
topPlayerPointsText.setText(String.valueOf(userManager.getTopUser().getTopPoints()));
EditText topPlayerStarsText = findViewById(R.id.topPlayerStarsText);
topPlayerStarsText.setText(String.valueOf(userManager.getTopUser().getTopStars()));
EditText topPlayerTapsText = findViewById(R.id.topPlayerTapsText);
topPlayerTapsText.setText(String.valueOf(userManager.getTopUser().getTopTaps()));
} else {
EditText topPlayerText = findViewById(R.id.topPlayerText);
topPlayerText.setText("Top player: " + userManager.getCurrentUser().getUserName());
EditText topPlayerPointsText = findViewById(R.id.topPlayerPointsText);
topPlayerPointsText.setText(String.valueOf(userManager.getCurrentUser().getTopPoints()));
EditText topPlayerStarsText = findViewById(R.id.topPlayerStarsText);
topPlayerStarsText.setText(String.valueOf(userManager.getCurrentUser().getTopStars()));
EditText topPlayerTapsText = findViewById(R.id.topPlayerTapsText);
topPlayerTapsText.setText(String.valueOf(userManager.getCurrentUser().getTopTaps()));
}
}
/** Called when the user taps the Bac button */
public void goBack(View view) {
Intent intent = new Intent(this, UserMenuActivity.class);
startActivity(intent);
}
}
| true |
732db9a533a348598256a1cba56747016fc1e300 | Java | hvgdfx/javatest | /src/main/java/com/test/function/FunctionTest.java | UTF-8 | 307 | 2.90625 | 3 | [] | no_license | package com.test.function;
import java.util.function.Function;
public class FunctionTest {
public static void main(String[] args) {
Function<String,String> function = (x) -> {System.out.print(x+": ");return "Function";};
System.out.println(function.apply("hello world"));
}
}
| true |
bfc1de77155e09f9a15096a6e725f17194d94709 | Java | amzhulanov/spring-boot-hw | /src/main/java/com/example/springboothw/repositories/RoleRepository.java | UTF-8 | 416 | 2.078125 | 2 | [] | no_license | package com.example.springboothw.repositories;
import com.example.springboothw.entities.Role;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.List;
@Repository
public interface RoleRepository extends CrudRepository<Role, Long> {
Collection<Role> findOneByName(String name);
List<Role> findAll();
}
| true |
d0d2f439d5e11dddc258dc4388a53b1827d24bf9 | Java | Yasnielmr/InitCMS | /InitCMS/src/main/java/com/cms/init/repository/ComentarioRepository.java | UTF-8 | 1,965 | 2.25 | 2 | [] | no_license | package com.cms.init.repository;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.web.SpringDataWebProperties.Pageable;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import com.cms.init.mapper.ComentarioMapper;
import com.cms.init.model.Comentario;
@Repository
public class ComentarioRepository implements ComentarioRep{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public boolean save(Comentario comentario) {
// TODO Auto-generated method stub
try {
String sql= String.format("insert into Comentario (Comentario, IdPost, IdUsuario, Respuesta) "
+ "values('%s', '%d', '%d', '%d')" ,
comentario.getCometario(), comentario.getIdPost(), comentario.getIdUsuario(), comentario.getRespuesta());
jdbcTemplate.execute(sql);
return true;
}
catch (Exception e) {
return false;
}
}
@Override
public boolean update(Comentario comentario) {
// TODO Auto-generated method stub
if(comentario.getIdComentario() != 0) {
String sql= String.format("update Comentario set Comentario='%s', IdPost='%d', IdUsuario='%d', Respuesta='%d' ) " +
"where IdCategoria='%d'",
comentario.getCometario(), comentario.getIdPost(), comentario.getIdUsuario(), comentario.getRespuesta());
jdbcTemplate.execute(sql);
return true;
}
return false;
}
@Override
public List<Comentario> findAll(Pageable pageable) {
// TODO Auto-generated method stub
return jdbcTemplate.query("select * from Comentario", new ComentarioMapper());
}
@Override
public Comentario findById(int Id) {
// TODO Auto-generated method stub
Object [] params= new Object [] {Id};
return jdbcTemplate.queryForObject("select * from Cometario where IdComentario=?", params, new ComentarioMapper());
}
}
| true |
4601745c85e88104ab28961520a3395ebe718f41 | Java | programmerXSX/JavaLearningAllCodes | /Java核心技术/常用工具类/随机数与输入语句/随机数.java | UTF-8 | 289 | 3.171875 | 3 | [] | no_license | package 常用工具类.随机数与输入语句;
import java.util.*;
public class 随机数 {
public static void main(String[] args) {
Random r = new Random();
int a = r.nextInt(10);//获取0-9之间的数字
System.out.println("a = " + a);
}
}
| true |
e92f50b7e559dc3e25d8a225432daa3975df1a1c | Java | oariaf00/practicas_SI | /practica3_SI/src/practica3_SI/Main.java | ISO-8859-1 | 7,446 | 2.875 | 3 | [] | no_license | package practica3_SI;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
//Datos del problema
char [] alf = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' ','.',',',';','','?','','!'};
char [] alf2 = {'a','b','c','d','e',' ','A','B','C','D','E','f','g','h','i','j','k','l','m','n','F','G','H','I','J','K','L','M','N','o','p','q','r','s','t','u','v','w','x','y','z','O','P','Q','R','S','T','U','V','W','X','Y','Z','.',',',';','','?','','!'};
int [] lista= {1,0,0,1,1,0,0,1,0,0,1,1,0,0,0,1,0,0,1,1,0,0,1,1,0,0,1,
1,0,0,1,1,1,1,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,1,0,0,1,1,
0,1,0,0,0,1,1,1,0,0,0,1,0,1,1,0,0,0,0,0,0,0,1,1,0,1,0,1,
0,1,1,0,1,0,1,0,0,1,1,1,0,0,0,0,1,0,0,1,1,0,1,0,0,1,1,0,
0,0,1,0,0,1,1,0,1,1,1,0,1,0,0,1,1,0,1,0,1,0,0,0,0,0,0,0,
0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,
1,0,0,0,1,0,1,1,0,0,0,0,0,0,0,1,0,0,0,1,1,1,0,1,0,0,1,1,
0,1,0,1,1,0,0,1,0,1,0,0,1,1,0,0,0,0,0,0,0,0,1,0,0,0,1,1,
1,1,1,1,0,1,0,0,0,0,1,1,1,1,0,0,1,0,1,1,0,1,0,0,1,0,1,0,
1,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,1,0,1,1,0,
1,0,0,0,0,0,0,0,1,0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,0,0,0,
1,1,1,1,0,1,0,0,1,1,1,0,1,0,0,1,1,1,1,1,1,1,1,0,1,1,0,0,1};
int [] lista2= {0,1,0,1,1,0,1,1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,1,0,0,1,1,0,0,1,0,0,1,1,0,0,0,1,1,1,1,0,1,0,1,0,0,1,
0,0,0,0,1,0,1,1,0,0,0,1,0,1,1,0,1,1,0,0,1,1,0,0,1,0,1,0,
1,0,0,0,1,0,1,1,0,0,1,0,1,0,1,0,0,0,0,0,0,0,0,1,0,0,1,1,
0,1,0,0,0,1,1,1,1,1,1,0,1,0,0,0,1,0,0,1,1,0,1,1,0,0,0,0,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,1,0,1,1,0,1,0,1,
0,0,0,0,1,0,1,1,0,1,0,1,1,0,1,0,0,0,1,0,1,1,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,1,0,1,1,0,1,0,1,1,1,0,0,0,1,0,1,0,0,1,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,
1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,1,1,1,0,1,0,0,0,0,0,0,0,0,
0,1,0,0,0,1,1,1,0,0,0,0,0,0,0,1,1,0,1,0,1,0,0,1,0,0,1,1,
0,0,1,0,1,1,0,1,0,0,1,0,1,0,1,1,0,0,1,1,0,0,0,0,0,1,0,1,
1,0,0,0,1,0,1,1,0,1,0,1,1,0,1,0,0,1,0,1,0,1,0,0,0,1,0,1,
1,0,0,0,1,0,1,1,0,0,1,1,1,1,0,1,0,0,0,1,1,1,0,1,0,0,1,1,
0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,1,1,0,0,0,0,1,0,1,0,0,1,1,
0,0,0,0,1,0,1,1,0,1,0,0,1,1,0,0,1,0,0,1,1,0,1,0,0,0,1,1,
1,0,1,0,0,1,1,0,0,1,0,1,1,0,1,0,0,0,0,0,0,0,1,0,0,1,1,0,
0,1,1,0,1,0,1,0,1,0,0,0,1,1,1,0,0,1,0,1,0,1,0,0,0,0,0,0,
0,0,0,0,1,0,1,1,0,0,0,0,0,0,0,0,0,1,0,1,0,1,1,0,0,0,1,1,
1,1,0,0,1,1,0,0,1,1,0,1,0,1,0,1,1,1,0,1,0,0,1,1,1,1,1,1,
1,1,0,1,1,0,0,1};
//Base=2 porque estamos trabajando con un cdigo binario
int base = 2;
/*
* Calculamos la longitud mnima para codificar cada caracter del alfabeto fuente
* y escogemos el valor inmediatamente superior entero como indica la frmula
*/
double logaritmoFuente = Math.log10(alf2.length)/Math.log10(base);
int longitudAlfabeto2 = (int) Math.ceil(logaritmoFuente);
System.out.println("Longitud del alfabeto fuente: " + longitudAlfabeto2);
/*
* Para saber en cantos elementos tenemos que dividir el mensaje a decodificar nos fijaremos
* en el nmero de columnas de la matriz generadora G=(I | A)
*
* (1,0,0,0,1,1,1
*En este caso G= 0,1,0,0,1,1,0
* 0,0,1,0,1,0,1
* 0,0,0,1,0,1,1)
*
* Al tener 7 columnas dividimos en grupos de 7 dgitos
*
*/
int i=0;
int j=0;
int [] arrayCod = new int [7];
int [] arrayDecod = new int [4];
ArrayList<Integer> codigoFinal = new ArrayList<Integer>();
/*
* Dentro de los conjuntos de 7, debemos diferenciar entre los dgitos para decodificar el mensaje
* y el ruido. En este caso como trabajamos con una matriz identidad de dimensiones 4x4 (I), agrupamos
* los conjuntos de 4 en 4 nmeros, sobrando as 3 dgitos los cuales forman el denominado ruido
*/
while(i+7<=lista2.length) {//Mientras haya palabras en el cdigo
for(j=0 ; j<7; j++) {
if(j<4){
//Aqu entrar para meter los dgitos en el cdigo final
arrayDecod[j] = lista2[i+j];
codigoFinal.add(arrayDecod[j]);
}else {
//Este ser el ruido
arrayCod[j] = lista2[i+j];
}
}
i = i+7;
}
/*
* En las siguientes lneas comprobamos que no haya cola dentro del cdigo que nos han dado para
* decodificar. De ser as cogemos los dgitos que constituyan la cola y los aadimos al arraylist
* con el cdigo final a descifrar
*/
int mod = lista2.length%7;
if(mod>0) {
int [] cola = new int [mod];
for(int k=i; k<lista2.length; k++){
cola[k-i] = lista2[k];
codigoFinal.add(cola[k-i]);
}
}
/*
* En este bucle imprimimos las palabras a descifrar
*/
System.out.println("Conjuntos a decodificar: ");
for(int k=0;k<codigoFinal.size();k++) {
if(k%4==0&&k!=0) {
System.out.println();
}
System.out.print(codigoFinal.get(k));
}
/*
* Como la longitud hallada anteriormente del alfabeto fuente es de 6, dividimos el cdigo a decodificar
* en conjuntos de 6 partes
*/
int tamanioArrayLetras = codigoFinal.size()/6;
i=0;
j=0;
int k=0;
int [] arrayCodigoLetra = new int [6];
char [] arrayLetras = new char [tamanioArrayLetras];
/*
* Repetimos el bucle de antes: Recorremos todo el array con el cdigo y mientras haya conjuntos de 6 elementos
* vamos traduciendolo para obtener el mensaje que queremos descifrar
*/
System.out.println();
while(i+6<=codigoFinal.size()) {
//Con este bucle for conseguimos los 6 elementos para conseguir el smbolo buscado.
System.out.println("Cdigo a traducir: ");
for(j=0 ; j<6; j++) {
arrayCodigoLetra[j] = codigoFinal.get(i+j);
System.out.print(+arrayCodigoLetra[j]);
}
System.out.println();
//Llamamos al mtodo para traducir la letra y la aadimos a un array
arrayLetras[k] = traducirLetra(arrayCodigoLetra, alf2);
System.out.println();
System.out.println("LETRA: " + arrayLetras[k]);
k++;
System.out.println();
i = i+6;
}
//Imprimimos el resultado final
System.out.println("Mensaje decodificado: ");
for(int q=0 ; q<arrayLetras.length ; q++){
System.out.print(arrayLetras[q]);
}
}
public static char traducirLetra(int [] codigoLetra, char [] alf2) {
int sumaCodigo = 0;
int potencia = 0;
for(int i=codigoLetra.length-1 ; i>=0 ; i--){
if(codigoLetra[i] == 1){
//int potenciaDos = 2^potencia;
//System.out.println("POTENCIA " + potencia);
sumaCodigo = sumaCodigo + calcularPotencia(potencia);
System.out.println("POSICION: " + sumaCodigo);
}
potencia++;
}
return alf2[sumaCodigo];
}
public static int calcularPotencia(int potencia){
int potenciaDos = 1;
if(potencia != 0){
for(int i=0 ; i<potencia ; i++){
potenciaDos = potenciaDos * 2;
}
return potenciaDos;
}
return potenciaDos;
}
}
| true |
30b56c2b5462bb8e1211a56b1dfc50490f770560 | Java | ncats/stitcher | /app/controllers/MathJax.java | UTF-8 | 3,145 | 2.375 | 2 | [
"Apache-2.0"
] | permissive | package controllers;
import java.io.*;
import java.security.SecureRandom;
import java.util.concurrent.Callable;
import javax.inject.*;
import play.*;
import play.mvc.*;
import play.libs.ws.*;
import org.webjars.*;
import views.html.*;
import org.webjars.play.WebJarsUtil;
import ncats.stitcher.CacheFactory;
public class MathJax extends Controller {
final SecureRandom rand = new SecureRandom ();
CacheFactory cache;
File workDir;
final Configuration config;
@Inject public WebJarsUtil webjars;
@Inject
public MathJax (Configuration config) {
this.config = config;
try {
cache = CacheFactory.getInstance
(config.getString("ix.repo", "repo.db"));
workDir = new File (config.getString("ix.work", "work"));
workDir.mkdirs();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
String getText (final String id) {
try {
return cache.getOrElse(id, new Callable<String> () {
public String call () throws Exception {
File file = new File (workDir, id);
if (!file.exists())
return null;
StringBuilder buf = new StringBuilder ();
BufferedReader br = new BufferedReader
(new FileReader (file));
for (String line; (line = br.readLine()) != null;) {
buf.append(line+"\n");
}
return buf.toString();
}
});
}
catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public Result render (String id) {
if (id != null) {
String text = getText (id);
if (text != null) {
return ok (mathjax.render(text));
}
}
return ok (mathbox.render(this));
}
@BodyParser.Of(value=BodyParser.FormUrlEncoded.class)
public Result mathjax () {
String[] params = request().body().asFormUrlEncoded().get("matharea");
if (params != null && params.length > 0) {
String text = params[0];
byte[] b = new byte[4];
rand.nextBytes(b);
StringBuilder buf = new StringBuilder ();
for (int i = 0; i < b.length; ++i) {
buf.append(String.format("%1$02x", b[i] & 0xff));
}
String id = buf.toString();
try {
File out = new File (workDir, id);
PrintStream ps = new PrintStream (new FileOutputStream (out));
ps.print(text);
ps.close();
Logger.debug("Rending text... "+id+"\n"+text);
return redirect (routes.MathJax.render(id));
}
catch (IOException ex) {
ex.printStackTrace();
}
}
return redirect (routes.MathJax.render(null));
}
}
| true |
b31d341eb99e9e4596e023d40225d3c1d92c8da7 | Java | admins-2017/cloud-backstage | /src/main/java/com/giantlizardcloud/merchant/enums/IndexKeyEnum.java | UTF-8 | 748 | 2.234375 | 2 | [] | no_license | package com.giantlizardcloud.merchant.enums;
import lombok.Getter;
/**
* @author Administrator
*/
@Getter
public enum IndexKeyEnum {
/**
* 销量排行key
*/
SALE("sales-ranking"),
/**
* 统计key
*/
STATISTICS("statistics"),
/**
* 销售次数统计
*/
SALE_COUNT("saleCount"),
/**
* 进货次数统计
*/
PURCHASE_COUNT("purchaseCount"),
/**
* 统计key
*/
SALE_AMOUNT("saleAmount"),
/**
* 销售value - name
*/
AMOUNT_OF_PAYOUT("amountOfPayout");
;
private String message;
IndexKeyEnum(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
| true |
0592d2867976126ffc06095173a04eeece56a1e7 | Java | DaedalusGame/RequiousFrakto | /src/main/java/requious/compat/jei/ingredient/SuperStackRenderer.java | UTF-8 | 3,176 | 2.1875 | 2 | [
"MIT"
] | permissive | package requious.compat.jei.ingredient;
import mezz.jei.api.ingredients.IIngredientRenderer;
import mezz.jei.util.ErrorUtil;
import mezz.jei.util.Log;
import mezz.jei.util.Translator;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.EnumRarity;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.TextFormatting;
import requious.util.Misc;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class SuperStackRenderer implements IIngredientRenderer<ItemStack> {
@Override
public void render(Minecraft minecraft, int xPosition, int yPosition, @Nullable ItemStack ingredient) {
if (ingredient != null) {
GlStateManager.enableDepth();
RenderHelper.enableGUIStandardItemLighting();
FontRenderer font = getFontRenderer(minecraft, ingredient);
minecraft.getRenderItem().renderItemAndEffectIntoGUI(null, ingredient, xPosition, yPosition);
minecraft.getRenderItem().renderItemOverlayIntoGUI(font, ingredient, xPosition, yPosition, Misc.getCountString(ingredient));
GlStateManager.disableBlend();
RenderHelper.disableStandardItemLighting();
}
}
@Override
public List<String> getTooltip(Minecraft minecraft, ItemStack ingredient, ITooltipFlag tooltipFlag) {
EntityPlayer player = minecraft.player;
List<String> list;
try {
list = ingredient.getTooltip(player, tooltipFlag);
} catch (RuntimeException | LinkageError e) {
String itemStackInfo = ErrorUtil.getItemStackInfo(ingredient);
Log.get().error("Failed to get tooltip: {}", itemStackInfo, e);
list = new ArrayList<>();
list.add(TextFormatting.RED + Translator.translateToLocal("jei.tooltip.error.crash"));
return list;
}
EnumRarity rarity;
try {
rarity = ingredient.getRarity();
} catch (RuntimeException | LinkageError e) {
String itemStackInfo = ErrorUtil.getItemStackInfo(ingredient);
Log.get().error("Failed to get rarity: {}", itemStackInfo, e);
rarity = EnumRarity.COMMON;
}
for (int k = 0; k < list.size(); ++k) {
if (k == 0) {
list.set(k, rarity.rarityColor + list.get(k));
} else {
list.set(k, TextFormatting.GRAY + list.get(k));
}
}
if (list.size() >= 1)
list.set(0, list.get(0) + TextFormatting.GRAY + " x" + ingredient.getCount());
return list;
}
@Override
public FontRenderer getFontRenderer(Minecraft minecraft, ItemStack ingredient) {
FontRenderer fontRenderer = ingredient.getItem().getFontRenderer(ingredient);
if (fontRenderer == null) {
fontRenderer = minecraft.fontRenderer;
}
return fontRenderer;
}
}
| true |
57f11441957abb3c97a6de64b7e772a3f7c54dce | Java | HeavyMetal77/JacksonDatabindingJson | /src/main/java/ua/tarastom/jackson/json/Driver.java | UTF-8 | 990 | 2.875 | 3 | [] | no_license | package ua.tarastom.jackson.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
public class Driver {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
Student theStudent = null;
try {
theStudent = mapper.readValue(new File("data/sample-full.json"), Student.class);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("theStudent id: " + theStudent.getId());
System.out.println("theStudent FirstName: " + theStudent.getFirstName());
System.out.println("theStudent LastName: " + theStudent.getLastName());
System.out.println("theStudent Active: " + theStudent.getActive());
System.out.println("theStudent Address: " + theStudent.getAddress());
System.out.println("theStudent Languages: " + Arrays.toString(theStudent.getLanguages()));
}
}
| true |
b1fc3eb82063262c821dbcecd5ef6b316ab64a7f | Java | Thulebona/infoshare | /src/main/java/infoshare/restapi/people/PersonAPI.java | UTF-8 | 991 | 2.125 | 2 | [] | no_license | package infoshare.restapi.people;
import infoshare.app.conf.RestUtil;
import infoshare.domain.person.Person;
import java.util.Set;
/**
* Created by hashcode on 2015/11/17.
*/
public class PersonAPI {
public static Person save(Person person) {
return RestUtil.save(PersonBaseURI.Person.POST, person, Person.class);
}
public static Person update(Person person) {
return RestUtil.save(PersonBaseURI.Person.POST, person,Person.class);
}
public static Person findById(String company, String id) {
String param = company + "/" + id;
return RestUtil.getById(PersonBaseURI.Person.GET_ID, param, Person.class);
}
public static Set<Person> findAll(String OrganisationPeople) {
return RestUtil.getAll(PersonBaseURI.Person.GET_Org + OrganisationPeople, Person.class);
}
public static Person findByEmail(String param) {
return RestUtil.getById(PersonBaseURI.Person.GET_BY_EMAIL, param, Person.class);
}
}
| true |
f4474efd4baa2b77c526f0497723df8161577678 | Java | BITcampPredavaci/PredavanjaCamp2 | /S12D03_ParallelProcessing/src/Runner.java | UTF-8 | 437 | 2.109375 | 2 | [] | no_license | import ba.bitcamp.benjamin.blockingqueueexample.BlockingQueueExample;
import ba.bitcamp.benjamin.executorexample.ExecutorExample;
import ba.bitcamp.benjamin.latchexample.*;
import ba.bitcamp.benjamin.callableexample.*;
public class Runner {
public static void main(String[] args) {
//BlockingQueueExample.startExample();
//LacthExample.startExample();
//ExecutorExample.runExample();
CallableExample.runExample();
}
}
| true |
faa1dc1d532bffbaccf4af32946909f28e50aa28 | Java | mohsenuss91/Sender | /src/client/Client.java | UTF-8 | 1,761 | 3.28125 | 3 | [] | no_license | package src.client;
import java.net.Socket;
import java.net.InetAddress;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.util.Random;
public class Client extends Thread {
private static final int SERVER_PORT=444;
//Objekti klasa ObjectOutputStream i ObjectInputStream se koriste i za upise u mreznu konekciju!
private ObjectOutputStream out;
private ObjectInputStream in;
private Socket clientSocket;
private String name;
public Client(){
try{
clientSocket=new Socket(InetAddress.getLocalHost(),SERVER_PORT);
out=new ObjectOutputStream(clientSocket.getOutputStream());
in=new ObjectInputStream(clientSocket.getInputStream());
name="Client"+new Random().nextInt(5);
}
catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args){
new Client().start();
new Client().start();
}
@Override
public void run(){
try{
sendString(name);
System.out.println(name+" - I've just sent my name to Server.");
sendBubble(new Bubble());
System.out.println(name+" - Bubble is also sent.");
System.out.println(name+" - I've got Bubble - "+(Bubble)in.readObject()+" back.");
out.writeObject(name+" - Bye.");
System.out.println((String)in.readObject());
out.close();
in.close();
clientSocket.close();
}
catch(IOException e){
e.printStackTrace();
}
catch(ClassNotFoundException e){
e.printStackTrace();
}
}
private void sendString(String arg) throws IOException {
out.writeObject(arg);
}
private void sendBubble(Bubble arg) throws IOException {
out.writeObject(arg);
}
} | true |
f57bfd3a1df9f2710522b1cdc600b3926fdf21fb | Java | bkozyrev/MyRepo | /app/src/main/java/com/bkozyrev/superchat/core/rx/IRxSchedulers.java | UTF-8 | 775 | 2.15625 | 2 | [] | no_license | package com.bkozyrev.superchat.core.rx;
import android.support.annotation.NonNull;
import io.reactivex.Scheduler;
/**
* {@code Interface} для получения {@link Scheduler}, чтобы управлять исполнением
*
* @author Козырев Борис
*/
public interface IRxSchedulers {
/**
* Возвращает {@link Scheduler}, привязанный к главному потоку для передачи результата работы
*
* @return {@link Scheduler}
*/
@NonNull
Scheduler getMainThreadScheduler();
/**
* Возвращает {@link Scheduler} для работы с сетью и файлами (Io)
*
* @return {@link Scheduler}
*/
@NonNull
Scheduler getIOScheduler();
}
| true |
9fe34f88702157a5fc8224004ddba4c6376982e3 | Java | charleswang007/i290t-aep | /out/production/aep/test/edu/berkeley/ischool/aep/RectangleTest.java | UTF-8 | 529 | 2.78125 | 3 | [] | no_license | package edu.berkeley.ischool.aep;
import junit.framework.Assert;
import org.junit.Test;
/**
* Created by Charles on 2014/1/24.
*/
public class RectangleTest {
@Test
public void shouldReturnAreaOfTenForTwoByFiveRectangle() {
Rectangle rectangle = new Rectangle(5, 2);
Assert.assertEquals(10, rectangle.area());
Assert.assertTrue("this is true", rectangle.area()==10);
}
@Test
public void createSquare() {
Assert.assertEquals(25, Rectangle.createSquare(5).area());
}
}
| true |
d2a9cd68dbfc127f4f7fdbcbe845710ce422049d | Java | aditi9413/Core-Java-Programs | /src/ClassAndObject/StaticUse.java | UTF-8 | 622 | 3.90625 | 4 | [] | no_license | package ClassAndObject;
class Ticket{
int number;
static int counter;
static{
counter=0;
}
public Ticket(){
number=++counter;
}
public void show(){
System.out.println("It is a ticket number = " +number);
}
public static int getcounter(){
return counter;
}
}
public class StaticUse {
public static void main(String[] args) {
System.out.println("Creating tickets");;
Ticket t1 = new Ticket();
Ticket t2 = new Ticket();
System.out.println("No of Tickets CREATED= " + Ticket.getcounter());
System.out.println("Ticket Discription");
t1.show();
t2.show();
}
}
| true |
8a7119439d151cf15ff3ca7668895cc112ee7031 | Java | 17803909286/power | /app/src/main/java/com/power/home/ui/adapter/CourseCatalogueAdapter.java | UTF-8 | 4,638 | 2.265625 | 2 | [
"MIT"
] | permissive | package com.power.home.ui.adapter;
import android.widget.TextView;
import androidx.annotation.Nullable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.power.home.R;
import com.power.home.common.util.FontUtil;
import com.power.home.common.util.StringUtil;
import com.power.home.common.util.TimeUtil;
import com.power.home.data.bean.CoursePlayerBean;
import java.text.DecimalFormat;
import java.util.List;
public class CourseCatalogueAdapter extends BaseQuickAdapter<CoursePlayerBean.CoursesBean, BaseViewHolder> {
private int selectPosition;
public int getSelectPosition() {
return selectPosition;
}
public void setSelectPosition(int selectPosition) {
this.selectPosition = selectPosition;
notifyDataSetChanged();
}
public CourseCatalogueAdapter(int layoutResId, @Nullable List<CoursePlayerBean.CoursesBean> data) {
super(layoutResId, data);
}
@Override
protected void convert(BaseViewHolder helper, CoursePlayerBean.CoursesBean item) {
helper.setText(R.id.tv_play_amount, item.getPlayCounts() > 9999 ? StringUtil.getPlayCount(item.getPlayCounts()) + "万" : item.getPlayCounts() + "");
helper.setText(R.id.tv_title,item.getTitle());
// helper.setText(R.id.tv_duration,item.getTime());
if (item.isLastStudy()){
helper.setVisible(R.id.tv_learn_tag,true);
}else {
helper.setVisible(R.id.tv_learn_tag,false);
}
// if (item.isBuy()){
// helper.setGone(R.id.tv_free,false);
// helper.setGone(R.id.iv_course_lock,false);
//
// }else {
// if (item.isFree()){
// helper.setGone(R.id.tv_free,true);
// helper.setGone(R.id.iv_course_lock,false);
// }else {
// helper.setGone(R.id.tv_free,false);
// helper.setGone(R.id.iv_course_lock,true);
// }
// }
if (item.isFree()){
helper.setText(R.id.tv_free,"免费");
helper.setGone(R.id.tv_free,true);
helper.setGone(R.id.iv_course_lock,false);
}else {
if (item.isBuy()){
helper.setText(R.id.tv_free,"已解锁");
helper.setGone(R.id.tv_free,true);
helper.setGone(R.id.iv_course_lock,false);
}else {
helper.setGone(R.id.tv_free,false);
helper.setGone(R.id.iv_course_lock,true);
}
}
if (selectPosition == helper.getLayoutPosition()){
helper.setText(R.id.tv_already_learning,"学习中…");
helper.setVisible(R.id.tv_already_learning,true);
helper.setTextColor(R.id.tv_already_learning,mContext.getResources().getColor(R.color.colorBlack1A1F28));
helper.setTextColor(R.id.tv_title,mContext.getResources().getColor(R.color.colorBlue0D7EF9));
helper.setGone(R.id.iv_learning,true);
helper.setGone(R.id.tv_position,false);
}else {
helper.setTextColor(R.id.tv_already_learning,mContext.getResources().getColor(R.color.colorBlack79808B));
if (item.isFinish()){
helper.setVisible(R.id.tv_already_learning,true);
helper.setText(R.id.tv_already_learning,"已学完");
}else {
double d = (double) item.getTopProgress() / (double) item.getCourseTime();
DecimalFormat df = new DecimalFormat("0%");
String format = df.format(d);
if (d>0.01){
helper.setVisible(R.id.tv_already_learning,true);
helper.setText(R.id.tv_already_learning,"已学"+format);
}else {
helper.setVisible(R.id.tv_already_learning,false);
helper.setText(R.id.tv_already_learning,"");
}
}
helper.setTextColor(R.id.tv_title,mContext.getResources().getColor(R.color.colorBlack1A1F28));
helper.setGone(R.id.iv_learning,false);
helper.setGone(R.id.tv_position,true);
helper.setText(R.id.tv_position,item.getSort());
FontUtil.setFont((TextView) helper.getView(R.id.tv_position));
}
if (item.getCourseTime()>3600){
helper.setText(R.id.tv_duration, TimeUtil.dateToString(item.getCourseTime()*1000,TimeUtil.dateFormat_hour2));
}else {
helper.setText(R.id.tv_duration, TimeUtil.dateToString(item.getCourseTime()*1000,TimeUtil.dateFormat_minutes));
}
}
}
| true |
ab446835ffb857096521546387404f137e65b98b | Java | Duanxiaodai/Algorithms-and-data-structure | /Java数据结构与算法/Leetcode/Solution_101.java | UTF-8 | 707 | 3.109375 | 3 | [] | no_license | class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public class Sulotion_101 {
public boolean isSymmetric(TreeNode root) {
return iscore(root,root);
}
public boolean iscore(TreeNode root1,TreeNode root2){
if (root1==null&&root2==null){
return true;
}
else if(root1==null&&root2!=null){
return false;
}
else if (root1!=null&&root2==null){
return false;
}
else if(root1.val!=root2.val){
return false;
}
else{
return iscore(root1.left,root2.right)&&iscore(root1.right,root2.left);
}
}
}
| true |
67ffeb775dc159441bede73250526be37bddb83c | Java | GoodHot/WebSpider | /src/main/java/com/goodHot/fun/domain/media/JPEGMedia.java | UTF-8 | 503 | 2.5 | 2 | [] | no_license | package com.goodHot.fun.domain.media;
import com.goodHot.fun.enums.MediaEnum;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class JPEGMedia extends AbstractMedia {
public JPEGMedia(String url, Integer width, Integer height) {
this.url = url;
this.width = width;
this.height = height;
}
public JPEGMedia() {
}
private String url;
private Integer width;
private Integer height;
private MediaEnum type = MediaEnum.JPEG;
}
| true |
6cc660cd522dfd0b295e75e58108b4305f3197fe | Java | lsa4449/DDIT-middleProject | /Book_Client2/src/kr/or/ddit/view/study/StudyWriteController.java | UTF-8 | 2,900 | 1.898438 | 2 | [] | no_license | package kr.or.ddit.view.study;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import kr.or.ddit.service.study.IStudyService;
import kr.or.ddit.session.Session;
import kr.or.ddit.view.questions.selectmain;
import kr.or.ddit.vo.BoardVO;
import kr.or.ddit.vo.FilesVO;
public class StudyWriteController implements Initializable{
FilesVO filesvo = new FilesVO();
private ObservableList<BoardVO> a;
private ObservableList<File> f;
private Registry reg;
IStudyService service;
@FXML TextField boardContent;
@FXML TextField boardTitle;
@FXML Button insert;
@FXML Text boardDate;
@FXML
private TextField boardfile;
@FXML Text memName;
@FXML Button files;
//커뮤니티 게시판 등록
@SuppressWarnings("null")
@Override
public void initialize(URL location, ResourceBundle resources) {
//boardDate.setCellValueFactory(new PropertyValueFactory<>("boardDate"));
try {
reg = LocateRegistry.getRegistry("localhost", 8429);
service = (IStudyService) reg.lookup("studyService");
System.out.println("AllEatdealHomeController RMI성공");
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
SimpleDateFormat format = new SimpleDateFormat("yyyy년 MM월dd일 HH : mm분");
Date time = new Date();
String time1 = format.format(time);
boardDate.setText(time1);
insert.setOnAction(e -> {
BoardVO vo = new BoardVO();
vo.setBoardTitle(boardTitle.getText());
vo.setBoardContent(boardContent.getText());
vo.setMemNum(Session.loginUser.getMemNum());
a = FXCollections.observableArrayList(vo);
int cnt = 0;
try {
cnt = service.insertStudy(vo);
if (cnt == 1) {
System.out.println("성공");
}
} catch (RemoteException e1) {
e1.printStackTrace();
}
FXMLLoader loader = new FXMLLoader(getClass().getResource("selStudy.fxml"));
Parent parent = null;
try{
parent = loader.load();
} catch (IOException e1) {
e1.printStackTrace();
}
studymain.t.getScene().setRoot(parent);
});
}
}
| true |
014a5650fc9c374574fda3bb307658d0cb373962 | Java | pegasus-isi/pegasus | /test/junit/edu/isi/pegasus/planner/mapper/output/OutputMapperTestSetup.java | UTF-8 | 4,341 | 2.28125 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2007-2013 University Of Southern California
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 edu.isi.pegasus.planner.mapper.output;
import edu.isi.pegasus.common.logging.LogManager;
import edu.isi.pegasus.planner.catalog.site.classes.SiteStore;
import edu.isi.pegasus.planner.classes.PlannerOptions;
import edu.isi.pegasus.planner.common.PegasusProperties;
import edu.isi.pegasus.planner.test.*;
import java.util.List;
/**
* A default test setup implementation for the junit tests.
*
* @author Karan Vahi
*/
public class OutputMapperTestSetup implements TestSetup {
/** The input directory for the test. */
private String mTestInputDir;
/** The Default Testup that this uses */
private DefaultTestSetup mDefaultTestSetup;
/** The default constructor. */
public OutputMapperTestSetup() {
mTestInputDir = ".";
mDefaultTestSetup = new DefaultTestSetup();
}
/**
* Set the input directory for the test on the basis of the classname of test class
*
* @param testClass the test class.
*/
public void setInputDirectory(Class testClass) {
mDefaultTestSetup.setInputDirectory(testClass);
}
/**
* Set the input directory for the test.
*
* @param directory the directory
*/
public void setInputDirectory(String directory) {
mDefaultTestSetup.setInputDirectory(directory);
}
/**
* Returns the input directory set by the test.
*
* @return
*/
public String getInputDirectory() {
return mDefaultTestSetup.getInputDirectory();
}
/**
* Loads up PegasusProperties properties.
*
* @param sanitizeKeys list of keys to be sanitized
* @return
*/
public PegasusProperties loadProperties(List<String> sanitizeKeys) {
return mDefaultTestSetup.loadProperties(sanitizeKeys);
}
/**
* Loads up properties from the input directory for the test.
*
* @param propertiesBasename basename of the properties file in the input directory.
* @param sanitizeKeys list of keys to be sanitized . relative paths replaced with full path on
* basis of test input directory.
* @return
*/
public PegasusProperties loadPropertiesFromFile(
String propertiesBasename, List<String> sanitizeKeys) {
return mDefaultTestSetup.loadPropertiesFromFile(propertiesBasename, sanitizeKeys);
}
/**
* Loads the logger from the properties and sets default level to INFO
*
* @param properties
* @return
*/
public LogManager loadLogger(PegasusProperties properties) {
return mDefaultTestSetup.loadLogger(properties);
}
/**
* Loads the planner options for the test
*
* @return
*/
public PlannerOptions loadPlannerOptions() {
PlannerOptions options = new PlannerOptions();
options.addOutputSite("local");
return options;
}
/**
* Loads up the SiteStore with the sites passed in list of sites.
*
* @param props the properties
* @param logger the logger
* @param sites the list of sites to load
* @return the SiteStore
*/
public SiteStore loadSiteStore(PegasusProperties props, LogManager logger, List<String> sites) {
return mDefaultTestSetup.loadSiteStore(props, logger, sites);
}
/**
* Loads up the SiteStore with the sites passed in list of sites.
*
* @param props the properties
* @param logger the logger
* @param sites the list of sites to load
* @return the SiteStore
*/
public SiteStore loadSiteStoreFromFile(
PegasusProperties props, LogManager logger, List<String> sites) {
return mDefaultTestSetup.loadSiteStoreFromFile(props, logger, sites);
}
}
| true |
3aa0aa58c2e245abefc3759a610fe9d6b129ec33 | Java | FaresMenzli/PIDEV-Covid | /src/com/esprit/Service/ServiceQuestion.java | UTF-8 | 2,846 | 2.46875 | 2 | [] | no_license | /*
* 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 com.esprit.Service;
import com.esprit.utils.DataBase;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author MKadmin
*/
public class ServiceQuestion {
private Connection con = DataBase.getInstance().getConnection();
private Statement ste;
public ServiceQuestion() {
try {
ste = con.createStatement();
} catch (SQLException ex) {
System.out.println(ex);
}
}
public String afficheQuestion() {
String Qu = null;
try {
ResultSet rs = ste.executeQuery("select * from Question where Q_id=1 ;");
while (rs.next()) {
Qu = rs.getString(2);
}
} catch (SQLException ex) {
System.out.println(ex);
}
return Qu;
}
public String afficheQuestion2() {
String Qu = null;
try {
ResultSet rs = ste.executeQuery("select * from Question where Q_id=2 ;");
while (rs.next()) {
Qu = rs.getString(2);
}
} catch (SQLException ex) {
System.out.println(ex);
}
return Qu;
}
public String afficheQuestion3() {
String Qu = null;
try {
ResultSet rs = ste.executeQuery("select * from Question where Q_id=2 ;");
while (rs.next()) {
Qu = rs.getString(2);
}
} catch (SQLException ex) {
System.out.println(ex);
}
return Qu;
}
public String TestafficheQ(int i) {
String question = "";
switch (i) {
case 1:
question = "Question loula";
break;
case 2:
question = "Question thenia";
break;
case 3:
question = "Question theltha";
break;
case 4:
question = "Question 4";
break;
case 5:
question = "Question 5";
break;
case 6:
question = "Question 6";
break;
case 7:
question = "Question 7";
break;
case 8:
question = "Question 8";
break;
case 9:
question = "Question 9";
break;
case 10:
question = "Question 10";
break;
default:
}
return question;
}
}
| true |
80d420e7fdeddfa23c28e9af2a019d340c8aff98 | Java | jayshharma/Java-Mini-Projects | /B1.java | UTF-8 | 584 | 3.03125 | 3 | [] | no_license | class B1
{
public static void main(String[] args)
{
System.out.println("Which country are you from?");
String country1= In.getString();
if (country1.equals ("India"))
{
System.out.println ("This country is filled with amazing people and food");
}
else if (country1.equals ("Canada"))
{
System.out.println ("This country is filled with amazing people and food");
}if (country1.equals ("France"))
{
System.out.println("Do you speak french?");
}
else
{
System.out.println ("I don't know anything about this region");
}
}
} | true |
7f2d6e62904c8703dc43b9f6ba65c3229f2262a4 | Java | toandv/fluent-collections | /src/main/java/fluent/collection/FluentListTest.java | UTF-8 | 809 | 3.5 | 4 | [
"MIT"
] | permissive | package fluent.collection;
import java.util.List;
import fluent.collection.mutable.FluentArrayList;
import fluent.collection.mutable.FluentFastList;
import fluent.collection.mutable.FluentLinkedList;
public class FluentListTest {
public static void main(String[] args) {
// treated as java.util.List
List<String> list = new FluentArrayList<String>().plus("s0", "s1", "s2", "s2");
// treated as fluent.collection.FluentList
FluentList<String> fluentList = (FluentList<String>) list;
fluentList.plus(new FluentFastList<String>().plus("s3", "s4"));
fluentList.plus(new FluentLinkedList<String>().plus("s5", "s6"));
// lambda expression used to iterate over the list
list.forEach(e -> System.out.print(e.toUpperCase() + " | "));
}
}
| true |
92907e87073cf8ad4de01044f73dd7b3064f0786 | Java | moutainhigh/jzy | /src/main/java/com/kaisa/kams/components/utils/ParamUtil.java | UTF-8 | 4,861 | 2.34375 | 2 | [] | no_license | package com.kaisa.kams.components.utils;
import com.kaisa.kams.components.params.common.DataTableParam;
import com.kaisa.kams.components.utils.excelUtil.Condition;
import com.kaisa.kams.components.utils.excelUtil.ExcelAssistant;
import org.apache.commons.lang.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.sql.Sql;
import javax.servlet.http.HttpServletRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Map;
/**
* Created by zhouchuang on 2017/4/28.
*/
public class ParamUtil {
private static String filters = ",start,draw,length,";
public static Cnd getCndFromRequest(HttpServletRequest request){
Cnd cnd = Cnd.where("1", "=", 1);
Enumeration em = request.getParameterNames();
while (em.hasMoreElements()) {
String name = (String) em.nextElement();
if(!filters.contains(","+name+",")&&!name.startsWith("columns[")&&!name.startsWith("search[")){
String value = request.getParameter(name);
if(!StringUtils.isEmpty(value))
cnd.and(name,"=",value);
}
}
return cnd;
}
public static Cnd getCndFromRequest(HttpServletRequest request,Class clazz){
try {
Cnd cnd = Cnd.where("1", "=", 1);
//从当前类里面获取匹配参数
addCnd(request,clazz,cnd);
//从父类获取匹配参数
addCnd(request,clazz.getSuperclass(),cnd);
return cnd;
} catch (SecurityException e) {
e.printStackTrace();
}
return Cnd.where("1", "=", 1);
}
private static Cnd addCnd(HttpServletRequest request,Class clazz,Cnd cnd ){
Arrays.stream(clazz.getDeclaredFields()).forEach(field -> {
String fieldName = field.getName();
String value = request.getParameter(fieldName);
if(!StringUtils.isEmpty(value)){
Annotation annotation = field.getAnnotation(Condition.class);
if(annotation!=null){
Condition condition = (Condition)annotation;
String cnds = condition.condition();
String sql = condition.sql();
cnd.and(fieldName,cnds,sql.replace("{}",value));
}else{
cnd.and(fieldName,"=",value);
}
}
});
return cnd;
}
public static ParamData getParamFromRequest(HttpServletRequest request,Class clazz){
ParamData paramData = new ParamData();
if(StringUtils.isNotEmpty(request.getParameter("start")))
paramData.setStart(Integer.parseInt(request.getParameter("start")));
if(StringUtils.isNotEmpty(request.getParameter("length")))
paramData.setLength(Integer.parseInt(request.getParameter("length")));
if(StringUtils.isNotEmpty(request.getParameter("draw")))
paramData.setDraw(Integer.parseInt(request.getParameter("draw")));
paramData.setCnd(getCndFromRequest(request,clazz));
return paramData;
}
public static Cnd getCndFromDataTableParam(DataTableParam param,Class clazz){
Map<String,String> map = param.getSearchKeys();
Cnd cnd = Cnd.where("1", "=", 1);
Object object = null;
try {
object = clazz.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
map.forEach((k,v)->{
try {
Field field = clazz.getDeclaredField(k);
if(field!=null){
if(v!=null&&( !(v instanceof String) || StringUtils.isNotEmpty((String)v) ) ){
Annotation annotation = field.getAnnotation(Condition.class);
if(annotation!=null) {
Condition condition = (Condition) annotation;
String cnds = condition.condition();
String sql = condition.sql();
cnd.and(k, cnds, sql.replace("{}", v));
}else{
cnd.and(k,"=",v);
}
}
}
}catch (Exception e){
e.printStackTrace();
}
});
return cnd;
}
public static void matchParam( Sql sql,DataTableParam param,Map<String,Object> addParam){
if (null != param.getSearchKeys()) {
Map<String, String> keys = param.getSearchKeys();
keys.forEach((k,v)->{
sql.setParam(k,v);
});
}
if (null != addParam) {
addParam.forEach((k,v)->{
sql.setParam(k,v);
});
}
}
}
| true |
edb2cd770919898d1557501f53b4452156435bbf | Java | mleger/Graph | /src/graph/algorithms/MinimumSpanningTree.java | WINDOWS-1257 | 4,189 | 3.578125 | 4 | [
"Apache-2.0"
] | permissive | package graph.algorithms;
import graph.elements.Graph;
import graph.elements.Node;
import graph.elements.WeightedEdge;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* This class can be used to find the minimum spanning tree of a graph.
* The algorithm used is based off of Prim's algorithm.
*
* @author Mathieu Lger
* @since Mar 16, 2014
*/
public class MinimumSpanningTree<N extends Node, E extends WeightedEdge<N>> {
private final Set<E> spanningTreeEdges;
private final long spanningTreeWeight;
/**
* Finds the minimum spanning tree of a graph. The algorithm used is
* based off of Prim's algorithm.
*
* @param graph to run the tree selection algorithm on.
*
* @throws IllegalArgumentException if the graph is empty.
*/
public MinimumSpanningTree(Graph<N, E> graph) {
if(graph.isEmpty()) {
throw new IllegalArgumentException("The graph cannot be empty");
}
Set<E> treeEdges = new LinkedHashSet<E>();
Set<N> treeNodes = new LinkedHashSet<N>();
Set<E> cotreeEdges = new LinkedHashSet<E>();
Set<N> cotreeNodes = new LinkedHashSet<N>();
cotreeEdges.addAll(graph.getAllEdges());
cotreeNodes.addAll(graph.getAllNodes());
long treeWeight = 0;
//Add a first Node to the tree (and remove from the cotree)
Iterator<N> iter = cotreeNodes.iterator();
N groundNode = iter.next();
treeNodes.add(groundNode);
cotreeNodes.remove(groundNode);
while( !cotreeNodes.isEmpty() ){
long weightToAdd = Long.MAX_VALUE;
E edgeToAdd = null;
N nodeToAdd = null;
// Find all the potential edges (edges that connect to one node in the
// present tree and one node not in the present tree). From these
// potential edges, find the edge with the lowest weight. Add this edge
// and its new node to the tree (and remove them from the cotree).
for(E edge : cotreeEdges) {
N sourceNode = edge.getSourceNode();
N targetNode = edge.getTargetNode();
boolean sourceIsInTree = treeNodes.contains(sourceNode);
boolean targetIsInTree = treeNodes.contains(targetNode);
if( (sourceIsInTree && !targetIsInTree) || (!sourceIsInTree && targetIsInTree)) {
// Note: By using <= instead of < ensures that the edges with
// a weight of Long.MAX_VALUE can be placed in the tree.
if(edge.getWeight() <= weightToAdd){
weightToAdd = edge.getWeight();
edgeToAdd = edge;
if(!sourceIsInTree) {
nodeToAdd = sourceNode;
} else {
nodeToAdd = targetNode;
}
}
}
}
if(edgeToAdd != null && nodeToAdd != null) {
treeEdges.add(edgeToAdd);
treeNodes.add(nodeToAdd);
cotreeEdges.remove(edgeToAdd);
cotreeNodes.remove(nodeToAdd);
treeWeight += weightToAdd;
} else {
// This should never happen
throw new IllegalStateException("No edge from cotree could be added to the tree");
}
}
spanningTreeEdges = treeEdges;
spanningTreeWeight = treeWeight;
}
/**
* Returns an unmodifiable Set of tree edges.
*
* <p>
* NOTE: The returned Set is unmodifiable and will therefore throw
* UnsupportedOperationException if one attempts to call its add() or
* remove() methods.
* </p>
*
* @return unmodifiable Set of edges contained in the tree.
*/
public Set<E> getTreeEdges() {
return Collections.unmodifiableSet(spanningTreeEdges);
}
/**
* @return the sum of the weight of all the edges in the tree.
*/
public long getTreeWeight() {
return spanningTreeWeight;
}
}
| true |
1302a6870a1f2470afec21a1ff655f5c119ea5a7 | Java | gitdlf/FreeMallV1.0 | /FreeMall/src/com/freemall/service/IAddOrderService.java | UTF-8 | 389 | 2.0625 | 2 | [] | no_license | package com.freemall.service;
import com.freemall.dao.entry.OrderEntry;
/**
* 增加订单的接口类
* @author LFSenior
*
*上午8:54:03
*
*/
public interface IAddOrderService {
/**
* 增加订单实现方法
* @param orderEntry 封装好的订单数据
* @return boolean 返回是否添加成功
*/
public boolean addOrder(OrderEntry orderEntry);
}
| true |
b2f63d6c7d781349b528b5be762bf82c51d210e3 | Java | daniilperestoronin/order-execution-system | /authentication-server/src/main/java/com/orderexecution/authentication/repository/TokenRepository.java | UTF-8 | 261 | 2.09375 | 2 | [] | no_license | package com.orderexecution.authentication.repository;
import com.orderexecution.authentication.domainobjects.User;
/**
* @author Perestoronin Daniil
*/
public interface TokenRepository {
User checkToken(String token);
void addToken(String token, User user);
}
| true |
be631baeb80d53208c9c893b67265c31ba9ee14e | Java | aparna-14/MovieBooking-DesktopApplication | /MovieTheater/src/movietheater/mainMenu.java | UTF-8 | 1,185 | 2.5625 | 3 | [
"MIT"
] | permissive | package movietheater;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class mainMenu extends javax.swing.JFrame {
private int mousepX;
private int mousepY;
public static String firstTime;
public static String firstTime2;
public static String firstTime3;
private static int cnt1;
private static int cnt2;
private static int cnt3;
public static ArrayList<Theater1> t1 = new ArrayList<>();
public static int cntt1;
public static ArrayList<Theater2> t2 = new ArrayList<>();
public static int cntt2;
public static ArrayList<Theater3> t3 = new ArrayList<>();
public static int cntt3;
public mainMenu() {
initComponents();
this.setLocationRelativeTo(null); // set center
}
public void seatTheater1(Theater1 t1){
t1.setVisible(true);
}
public void seatTheater2(Theater2 t2){
t2.setVisible(true);
}
public void seatTheater3(Theater3 t3){
t3.setVisible(true);
}
public void startPage(){
Starter.start.setVisible(true);
}
}
| true |
9fec4d0ce72acd959b6756f1427ede25998f17d8 | Java | muhammed06/myfirsjavas | /POLİNOM2/PolConstants.java | UTF-8 | 405 | 1.554688 | 2 | [
"Unlicense"
] | permissive | /* Generated By:JavaCC: Do not edit this line. PolConstants.java */
public interface PolConstants {
int EOF = 0;
int BOLME = 6;
int US = 7;
int TOPLAM = 8;
int SAYI = 9;
int X = 10;
int DEFAULT = 0;
String[] tokenImage = {
"<EOF>",
"\" \"",
"\"\\t\"",
"\"\\n\"",
"\"\\r\"",
"\"\\r\\n\"",
"<BOLME>",
"\"^\"",
"\"+\"",
"<SAYI>",
"<X>",
};
}
| true |
a65468f26e5a3e4c4063742167fc3fdadd689513 | Java | phax/phase4 | /phase4-lib/src/main/java/com/helger/phase4/client/AS4ClientReceiptMessage.java | UTF-8 | 6,245 | 1.703125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2015-2023 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.phase4.client;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.WillNotClose;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import com.helger.commons.annotation.Nonempty;
import com.helger.phase4.crypto.IAS4CryptoFactory;
import com.helger.phase4.ebms3header.Ebms3UserMessage;
import com.helger.phase4.http.HttpXMLEntity;
import com.helger.phase4.messaging.crypto.AS4Signer;
import com.helger.phase4.messaging.domain.AS4ReceiptMessage;
import com.helger.phase4.messaging.domain.EAS4MessageType;
import com.helger.phase4.util.AS4ResourceHelper;
/**
* AS4 client for {@link AS4ReceiptMessage} objects.
*
* @author Philip Helger
*/
public class AS4ClientReceiptMessage extends AbstractAS4ClientSignalMessage <AS4ClientReceiptMessage>
{
private boolean m_bNonRepudiation = false;
private Node m_aSoapDocument;
private Ebms3UserMessage m_aEbms3UserMessage;
private boolean m_bReceiptShouldBeSigned = false;
public AS4ClientReceiptMessage (@Nonnull @WillNotClose final AS4ResourceHelper aResHelper)
{
super (EAS4MessageType.RECEIPT, aResHelper);
}
/**
* Default value is <code>false</code>
*
* @return if non-repudiation is used or not
*/
public final boolean isNonRepudiation ()
{
return m_bNonRepudiation;
}
@Nonnull
public final AS4ClientReceiptMessage setNonRepudiation (final boolean bNonRepudiation)
{
m_bNonRepudiation = bNonRepudiation;
return this;
}
@Nullable
public final Node getSoapDocument ()
{
return m_aSoapDocument;
}
/**
* As node set the usermessage if it is signed, so the references can be
* counted and used in non repudiation.
*
* @param aSoapDocument
* Signed UserMessage
* @return this for chaining
*/
@Nonnull
public final AS4ClientReceiptMessage setSoapDocument (@Nullable final Node aSoapDocument)
{
m_aSoapDocument = aSoapDocument;
return this;
}
@Nullable
public final Ebms3UserMessage getEbms3UserMessage ()
{
return m_aEbms3UserMessage;
}
/**
* Needs to be set to refer to the message which this receipt is the response
* and if non-repudiation is not used, to fill the receipt content
*
* @param aEbms3UserMessage
* UserMessage which this receipt should be the response for
* @return this for chaining
*/
@Nonnull
public final AS4ClientReceiptMessage setEbms3UserMessage (@Nullable final Ebms3UserMessage aEbms3UserMessage)
{
m_aEbms3UserMessage = aEbms3UserMessage;
return this;
}
public final boolean isReceiptShouldBeSigned ()
{
return m_bReceiptShouldBeSigned;
}
@Nonnull
public final AS4ClientReceiptMessage setReceiptShouldBeSigned (final boolean bReceiptShouldBeSigned)
{
m_bReceiptShouldBeSigned = bReceiptShouldBeSigned;
return this;
}
private void _checkMandatoryAttributes ()
{
// SoapVersion can never be null
if (m_aSoapDocument == null && m_aEbms3UserMessage == null)
throw new IllegalStateException ("A SOAP document or a Ebms3UserMessage has to be set.");
if (m_bNonRepudiation)
{
if (m_aSoapDocument == null)
throw new IllegalStateException ("Non-repudiation only works in conjunction with a set SOAP document.");
}
else
{
if (m_aEbms3UserMessage == null)
throw new IllegalStateException ("Ebms3UserMessage has to be set, if the SOAP document is not signed.");
}
}
@Override
public AS4ClientBuiltMessage buildMessage (@Nonnull @Nonempty final String sMessageID,
@Nullable final IAS4ClientBuildMessageCallback aCallback) throws WSSecurityException
{
_checkMandatoryAttributes ();
final AS4ReceiptMessage aReceiptMsg = AS4ReceiptMessage.create (getSoapVersion (),
sMessageID,
m_aEbms3UserMessage,
m_aSoapDocument,
m_bNonRepudiation);
if (aCallback != null)
aCallback.onAS4Message (aReceiptMsg);
final Document aPureDoc = aReceiptMsg.getAsSoapDocument ();
if (aCallback != null)
aCallback.onSoapDocument (aPureDoc);
Document aDoc = aPureDoc;
if (m_bReceiptShouldBeSigned && signingParams ().isSigningEnabled ())
{
final IAS4CryptoFactory aCryptoFactorySign = internalGetCryptoFactorySign ();
final boolean bMustUnderstand = true;
final Document aSignedDoc = AS4Signer.createSignedMessage (aCryptoFactorySign,
aDoc,
getSoapVersion (),
aReceiptMsg.getMessagingID (),
null,
getAS4ResourceHelper (),
bMustUnderstand,
signingParams ().getClone ());
if (aCallback != null)
aCallback.onSignedSoapDocument (aSignedDoc);
aDoc = aSignedDoc;
}
// Wrap SOAP XML
return new AS4ClientBuiltMessage (sMessageID, new HttpXMLEntity (aDoc, getSoapVersion ().getMimeType ()));
}
}
| true |
f17f179fd221a21a861b0ce50af34dec25e5d67c | Java | troytan1991/design-pattern | /src/test/java/com/troytan/creation/SingletonTest.java | UTF-8 | 570 | 2.984375 | 3 | [
"MIT"
] | permissive | package com.troytan.creation;
import org.junit.Assert;
import org.junit.Test;
import com.troytan.creation.Singleton.DbManager;
/**
* 单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点(getInstance方法)
*
* @author troytan
* @date 2017年12月4日
*/
public class SingletonTest {
@Test
public void singletonTest() {
DbManager instance1 = DbManager.getInstance();
DbManager instance2 = DbManager.getInstance();
Assert.assertTrue(instance1 == instance2);
}
}
| true |
5147b6cf6cb0325fb1aae3b71e91e45bda387fc8 | Java | WilliamAmorim/SistemaDeGerenciamento | /Medical Drugs/src/br/com/medicalpharm/model/SaidaItemModel.java | UTF-8 | 1,357 | 1.984375 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.medicalpharm.model;
import java.util.Date;
/**
*
* @author ALENCAR
*/
public class SaidaItemModel {
public Integer getCodSaida() {
return codSaida;
}
public void setCodSaida(Integer codSaida) {
this.codSaida = codSaida;
}
private Integer codSaida;
private ProdutoModel produto;
private Integer quantidade;
private String lote;
private Date vencimento;
public String getLote() {
return lote;
}
public void setLote(String lote) {
this.lote = lote;
}
public Date getVencimento() {
return vencimento;
}
public void setVencimento(Date vencimento) {
this.vencimento = vencimento;
}
public SaidaModel getSaidaModel() {
return saidaModel;
}
public void setSaidaModel(SaidaModel saidaModel) {
this.saidaModel = saidaModel;
}
private SaidaModel saidaModel;
public ProdutoModel getProduto() {
return produto;
}
public void setProduto(ProdutoModel produto) {
this.produto = produto;
}
public Integer getQuantidade() {
return quantidade;
}
public void setQuantidade(Integer quantidade) {
this.quantidade = quantidade;
}
}
| true |
ecb86c4d9308408323c73481f881de9eaf54ef2f | Java | lararogu/EjercicioTTA | /EjercicioTTA/app/src/main/java/es/tta/ejerciciotta/Business.java | UTF-8 | 3,580 | 2.390625 | 2 | [] | no_license | package es.tta.ejerciciotta;
import android.util.Log;
import android.widget.TextView;
import android.net.Uri;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import es.tta.ejerciciotta.Test.Choice;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Created by LARA MARIA on 28/12/2015.
*/
public class Business {
private final RestClient rest;
public Business(RestClient rest){
this.rest=rest;
}
public Test getTest(int id)throws IOException,JSONException{
JSONObject json=rest.getJson(String.format("getTest?id=%d",id));//Recogemos el test en formato JSON
String wording=json.getString("wording");
JSONArray array=json.getJSONArray("choices");
int length=array.length();
String [] choicesAnswer = new String[length];
boolean [] choicesCorrect = new boolean[length];
String [] choicesAdvise = new String[length];
String [] choicesAdvType = new String[length];
int [] choicesId = new int[length];
for(int i=0;i<length;i++){
JSONObject item=array.getJSONObject(i);
choicesId[i] = item.getInt("id");
choicesAnswer[i] = item.getString("answer");
choicesAdvise[i] = item.getString("advise");
choicesCorrect[i] = item.getBoolean("correct");
if(item.isNull("resourceType")){
choicesAdvType[i] = "null";
}else{
choicesAdvType[i] = item.getJSONObject("resourceType").getString("mime");;
}
}
Test test = new Test(wording,choicesId,choicesAnswer,choicesCorrect,choicesAdvise,choicesAdvType);
return test;
}
public Exercise getExercise(int id)throws IOException,JSONException{
JSONObject json=rest.getJson(String.format("getExercise?id=%d",id));//Recogemos el ejercicio en formato JSON
Exercise exercise=new Exercise();
exercise.setId(json.getInt("id"));
exercise.setWording(json.getString("wording"));
return exercise;
}
public Status getStatus(String dni,String passwd)throws IOException,JSONException{
JSONObject json=rest.getJson(String.format("getStatus?dni=%s", dni));//Recogemos el status en formato JSON
Status userStatus=new Status(dni,passwd);
userStatus.setId(json.getInt("id"));
userStatus.setName(json.getString("user"));
userStatus.setlessonNumber(json.getInt("lessonNumber"));
userStatus.setlessonTitle(json.getString("lessonTitle"));
userStatus.setnextTest(json.getInt("nextTest"));
userStatus.setnextEx(json.getInt("nextExercise"));
return userStatus;
}
public int postTest(int user,int id)throws IOException,JSONException{
JSONObject json=new JSONObject();
json.put("userId",user);
json.put("choiceId",id);
int codeResponse=rest.postJson(json, "postChoice");//Recogemos el codigo de rspuesta del mensahe POST al servidor
Log.d("tag", "coderesponse:"+codeResponse);
return codeResponse;
}
public int postExercise(Uri file,String fileName,int userid,int exercise)throws IOException,JSONException{
String path="postExercise?user="+userid+"&id="+exercise;
InputStream is=new FileInputStream(file.getPath());
int codeResponse=rest.postFile(path,is,fileName);//Recogemos el codigo de rspuesta del mensaje POST al servidor
Log.d("tag", "coderesponse:"+codeResponse);
return codeResponse;
}
}
| true |
4e79f2e08759a484dad8cc0737bedd8d360f5da6 | Java | hamigakitanuki/codnate_android | /app/src/main/java/com/example/codnate3/intent/Start5.java | UTF-8 | 2,576 | 2.3125 | 2 | [] | no_license | package com.example.codnate3.intent;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.example.codnate3.R;
import com.example.codnate3.object.Account_data;
public class Start5 extends AppCompatActivity {
private EditText editText;
private String message;
public static String text;
private String type_text;
TextView error;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start5);
error = findViewById(R.id.start_mens_error);
Button back = findViewById(R.id.back_start5);
//↓前のActivityへ
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
//ラジオボタンの処理
RadioGroup radioGroup = findViewById(R.id.RadioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(RadioGroup group,int checkedId2){
//選択されているラジオボタンの取得
RadioButton radiobutton2 = findViewById(checkedId2);
//ラジオボタンのテキストを取得
String text = radiobutton2.getText().toString();
type_text = text;
Log log = null;
log.v("checked",text);
}
});
//↓呼び出したActivityにデータを返す
Button finish = findViewById(R.id.next_start_mens);
finish.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(type_text != null){
Account_data account_data = new Account_data();
account_data.setType(type_text);
Intent intent = new Intent();
intent.putExtra("Account_data",account_data);
setResult(RESULT_OK,intent);
finish();
}else{
error.setText("タイプを選択してください");
}
}
});
}
}
| true |
77201bb25507fcbe6665c97fef8128c647813f1d | Java | agoncal/agoncal-fascicle-microprofile | /health/health-live-ready/src/main/java/org/agoncal/fascicle/microprofile/health/liveready/SystemVariableCheck.java | UTF-8 | 884 | 2.171875 | 2 | [
"MIT"
] | permissive | package org.agoncal.fascicle.microprofile.health.liveready;
import org.eclipse.microprofile.health.HealthCheck;
import org.eclipse.microprofile.health.HealthCheckResponse;
import org.eclipse.microprofile.health.Readiness;
import javax.enterprise.context.ApplicationScoped;
// tag::adocSnippet[]
@Readiness
@ApplicationScoped
public class SystemVariableCheck implements HealthCheck {
@Override
public HealthCheckResponse call() {
if (System.getProperty("server.name") == null) {
return HealthCheckResponse
.named(SystemVariableCheck.class.getSimpleName() + "Readiness")
.withData("server", "not available")
.down()
.build();
}
return HealthCheckResponse
.named(SystemVariableCheck.class.getSimpleName() + "Readiness")
.withData("default server", "available")
.up()
.build();
}
}
// end::adocSnippet[]
| true |
6ddb443fb8fe0c8f4fe8c95aba8cd61bfe8701ad | Java | YFuLin/NewsApp | /app/src/main/java/com/example/newsapp/ContentActivity.java | UTF-8 | 855 | 2.046875 | 2 | [] | no_license | package com.example.newsapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ContentActivity extends AppCompatActivity {
public static String LINK_NAME="CONTENT";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
WebView webView=(WebView)findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.setWebViewClient(new WebViewClient());
Intent intent=getIntent();
String LinkName=intent.getStringExtra(LINK_NAME).toString();
webView.loadUrl(LinkName);
}
}
| true |
35f17c227753c6b7bbf3e83d2f86908457e425fe | Java | georgepachitariu/DistributedDatabase | /src/networkInfrastructure/ServerNetworkInfo.java | UTF-8 | 768 | 3.15625 | 3 | [] | no_license | package NetworkInfrastructure;
public class ServerNetworkInfo {
private String IP;
private int port;
public ServerNetworkInfo(String input) {
String[] parts=input.split(":");
this.IP=parts[0];
this.port=Integer.parseInt(parts[1]);
}
public ServerNetworkInfo (String ip, int port) {
this.IP=ip;
this.port=port;
}
public String getIP() {
return IP;
}
public void setIP(String iP) {
IP = iP;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String toString() {
return this.IP+":"+this.port;
}
@Override
public boolean equals(Object o) {
if(this.toString().equals(((ServerNetworkInfo)o).toString()))
return true;
return false;
}
}
| true |
adaddab8f5302e467c3a7aab858851f0e6279dae | Java | mahao521/CacheBitmap | /database/src/main/java/com/bitmap/database/base/BaseImpl.java | UTF-8 | 319 | 1.78125 | 2 | [] | no_license | package com.bitmap.database.base;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import io.reactivex.disposables.Disposable;
/**
* Created by Administrator on 2018/6/30.
*/
public interface BaseImpl {
boolean addDisposable(Disposable dispoable);
Context getContext();
}
| true |
870f92da748098655ec3af6951f20c2d583779ac | Java | maiconm/hello-world-android-2 | /app/src/main/java/com/example/mandraski/helloworldandroid2/lista3/Pessoa.java | UTF-8 | 1,193 | 2.625 | 3 | [] | no_license | package com.example.mandraski.helloworldandroid2.lista3;
public class Pessoa {
private long id;
private String nome;
private String idade;
private String cpf;
private String profissao;
public Pessoa (long id, String nome, String idade, String profissao) {
this.id = id;
this.nome = nome;
this.idade = idade;
this.profissao = profissao;
}
public Pessoa (String nome, String idade, String cpf) {
this.nome = nome;
this.idade = idade;
this.cpf = cpf;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getIdade() {
return idade;
}
public void setIdade(String idade) {
this.idade = idade;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getProfissao() { return this.profissao; }
public void setProfissao(String profissao) { this.profissao = profissao; }
}
| true |
5be76378e1b7dc3060b23088e8ccc389f8f7900e | Java | P79N6A/oyph | /sp2p_sjzyj.activity.shake/app/daos/activity/shake/ShakeActivityDao.java | UTF-8 | 1,557 | 2.40625 | 2 | [
"MIT"
] | permissive | package daos.activity.shake;
import java.util.List;
import common.utils.PageBean;
import daos.base.BaseDao;
import models.activity.shake.entity.t_shake_activity;
/**
* 摇一摇活动DAO
*
* @author niu
* @create 2017-12-08
*/
public class ShakeActivityDao extends BaseDao<t_shake_activity> {
/**
* 保存摇一摇活动
*
* @param name 活动名称
* @param ctime 活动时间
* @return 添加成功返回true,添加失败返回flase.
*
* @author niu
* @create 2017-12-08
*/
public boolean saveShakeActivity(String name, int ctime) {
t_shake_activity activity = new t_shake_activity();
activity.name = name;
activity.ctime = ctime;
activity.status = 1;
return activity.save() == null ? false : true;
}
/**
* 分页查询摇一摇活动
*
* @param currPage 当前页码
* @param pageSize 显示条数
* @return
*
* @author niu
* @create 2017-12-08
*/
public PageBean<t_shake_activity> listOfShakeActivity(int currPage, int pageSize) {
String querySQL = "SELECT * FROM t_shake_activity t ORDER BY t.id DESC";
String countSQL = "SELECT COUNT(t.id) FROM t_shake_activity t ORDER BY t.id DESC";
return pageOfBeanBySQL(currPage, pageSize, countSQL, querySQL, t_shake_activity.class, null);
}
/**
* 查询已开始的活动
*
* @return
*
* @author niu
* @create 2017-12-12
*/
public t_shake_activity getOngoingActivity() {
String sql = "SELECT * FROM t_shake_activity t WHERE t.status = 3";
return findBySQL(sql, null);
}
}
| true |
f5ae80d4bc63a0045442645cec92695e6a816063 | Java | samlovespider/CUtilsLibrary | /cutilslibrary/src/main/java/com/samcai/cutilslibrary/utils/ArrayUtils.java | UTF-8 | 554 | 2.359375 | 2 | [] | no_license | package com.samcai.cutilslibrary.utils;
import java.util.List;
import java.util.Map;
/**
* Created by caizhenliang on 2018/4/27.
*
* @version 1.2
*/
public class ArrayUtils {
/**
* not null and size>0
*
* @param list
* @return
*/
public static boolean IsEmpty(List list) {
return list == null || list.size() == 0;
}
/**
* not null and size>0
*
* @param map
* @return
*/
public static boolean IsEmpty(Map map) {
return map == null || map.size() == 0;
}
}
| true |
ec3995d1fd2d4e41daca4e0913f1b5eda38f1df0 | Java | zdddrszj/hotelmansys | /.svn/pristine/40/4049e94d77316bd942ab6c9178a01509958bd60a.svn-base | UTF-8 | 945 | 2.328125 | 2 | [] | no_license | package com.wx.model;
import java.util.HashSet;
import java.util.Set;
/***
* 设置关联
* @author 王雪
* @desc商品类型 跟商品一对多
* 2013-7-25
*/
public class ProductType {
/**商品类型id*/
private Integer type_id;
/**商品名称*/
private String type_name;
/**商品*/
private Set<Product> type_proId = new HashSet<Product>();
public Integer getType_id() {
return type_id;
}
public void setType_id(Integer typeId) {
type_id = typeId;
}
public String getType_name() {
return type_name;
}
public void setType_name(String typeName) {
type_name = typeName;
}
public Set<Product> getType_proId() {
return type_proId;
}
public void setType_proId(Set<Product> typeProId) {
type_proId = typeProId;
}
public ProductType() {
}
public ProductType(Integer typeId, String typeName, Set<Product> typeProId) {
super();
type_id = typeId;
type_name = typeName;
type_proId = typeProId;
}
}
| true |
0bea3f836c0ced95fe84c8fc219e8b7093184b45 | Java | nekitos911/sberproject | /src/main/java/com/task/sberproject/service/WeatherServiceImpl.java | UTF-8 | 781 | 2.1875 | 2 | [] | no_license | package com.task.sberproject.service;
import com.task.sberproject.Constant;
import com.task.sberproject.entity.Weather;
import com.task.sberproject.utils.URIUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.util.UriTemplate;
import java.net.URI;
@Service
@RequiredArgsConstructor
public class WeatherServiceImpl implements WeatherService {
private final URIUtils uriUtils;
@Value("${weather.appid}")
private String appId;
@Override
public Weather getWeather(String cityName) {
URI url = new UriTemplate(Constant.BASE_WEATHER_URL).expand(cityName, appId);
return uriUtils.invoke(url, Weather.class);
}
}
| true |
fa4b0dfbd5e1525c0bda88e0f968758d1cd8dd41 | Java | sakaiproject/sakai | /conversations/api/src/main/java/org/sakaiproject/conversations/api/model/ConversationsPost.java | UTF-8 | 3,483 | 1.773438 | 2 | [
"ECL-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-generic-cla",
"GPL-1.0-or-later"
] | permissive | /*
* Copyright (c) 2003-2021 The Apereo Foundation
*
* Licensed under the Educational Community 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://opensource.org/licenses/ecl2
*
* 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.sakaiproject.conversations.api.model;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.Lob;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.sakaiproject.springframework.data.PersistableEntity;
import lombok.Getter;
import lombok.Setter;
@Entity
@Table(name = "CONV_POSTS", indexes = { @Index(name = "conv_posts_topic_idx", columnList = "TOPIC_ID"),
@Index(name = "conv_posts_topic_creator_idx", columnList = "TOPIC_ID, CREATOR"),
@Index(name = "conv_posts_site_idx", columnList = "SITE_ID"),
@Index(name = "conv_posts_parent_post_idx", columnList = "PARENT_POST_ID"),
@Index(name = "conv_posts_parent_thread_idx", columnList = "PARENT_THREAD_ID") })
@Getter
@Setter
public class ConversationsPost implements PersistableEntity<String> {
@Id
@Column(name = "POST_ID", length = 36, nullable = false)
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
@Column(name = "TOPIC_ID", length = 36, nullable = false)
private String topicId;
@Column(name = "PARENT_POST_ID", length = 36)
private String parentPostId;
// This holds the oldest ancestor, the thread starter, in this thread of posts
@Column(name = "PARENT_THREAD_ID", length = 36)
private String parentThreadId;
@Column(name = "SITE_ID", length = 99, nullable = false)
private String siteId;
@Lob
@Column(name = "MESSAGE", nullable = false)
private String message;
@Column(name = "NUMBER_OF_COMMENTS")
private Integer numberOfComments = 0;
// This is only used in a thread context, ie when a post is a top level
// reply to a topic
@Column(name = "NUMBER_OF_THREAD_REPLIES")
private Integer numberOfThreadReplies = 0;
@Column(name = "NUMBER_OF_THREAD_REACTIONS")
private Integer numberOfThreadReactions = 0;
@Column(name = "DEPTH")
private Integer depth = 1;
@Column(name = "HOW_ACTIVE")
private Integer howActive = 0;
@Column(name = "DRAFT")
private Boolean draft = Boolean.FALSE;
@Column(name = "HIDDEN")
private Boolean hidden = Boolean.FALSE;
@Column(name = "LOCKED")
private Boolean locked = Boolean.FALSE;
@Column(name = "UPVOTES")
private Integer upvotes = 0;
@Column(name = "PRIVATE_POST")
private Boolean privatePost = Boolean.FALSE;
@Column(name = "ANONYMOUS")
private Boolean anonymous = Boolean.FALSE;
@Embedded
private Metadata metadata;
}
| true |
4fb138e7c268a049ae4fc7ade0a32e031feee2d1 | Java | PeronVolodymyr/universityJDBC | /src/main/java/per/coursework/university/DAO/teacher/TeacherDAOJDBCImpl.java | UTF-8 | 6,408 | 2.609375 | 3 | [] | no_license | package per.coursework.university.DAO.teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import per.coursework.university.DAO.teacher.interfaces.ITeacherDAO;
import per.coursework.university.datastorage.DataStorageJDBC;
import per.coursework.university.model.*;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
@Component
public class TeacherDAOJDBCImpl implements ITeacherDAO {
@Autowired
private DataStorageJDBC dataStorage;
private List<Teacher> list = new ArrayList<>();
@Override
public Teacher insertTeacher(Teacher teacher) throws SQLException {
String query = "INSERT INTO `newdb`.`teacher` (`name`, `date_of_birth`, `count_of_children`, `salary`, `category_of_teacher_id`, `chair_id`) VALUES (?,?,?,?,?,?)";
PreparedStatement statement = dataStorage.getConnection().prepareStatement(query);
statement.setString(1, teacher.getName());
statement.setDate(2, java.sql.Date.valueOf(teacher.getDateOfBirth()));
statement.setInt(3, teacher.getCountOfChildren());
statement.setInt(4, teacher.getSalary());
statement.setInt(5, teacher.getCategoryOfTeacher().getId());
statement.setInt(6, teacher.getChair().getId());
int countInsertedRows = statement.executeUpdate();
statement.close();
return teacher;
}
@Override
public Teacher getTeacher(int id) throws SQLException {
String query = "SELECT * FROM `newdb`.`teacher` " +
"INNER JOIN category_of_teacher ON category_of_teacher_id = category_of_teacher.id " +
"INNER JOIN chair ON chair_id = chair.id " +
"INNER JOIN department ON department_id = department.id " +
"INNER JOIN deanery ON deanery_id = deanery.id WHERE teacher.id=?";
PreparedStatement statement = dataStorage.getConnection().prepareStatement(query);
statement.setInt(1,id);
ResultSet rs = statement.executeQuery();
rs.next();
Teacher teacher = new Teacher(
rs.getInt("teacher.id"),
rs.getString("teacher.name"),
rs.getDate("teacher.date_of_birth").toLocalDate(),
rs.getInt("teacher.count_of_children"),
rs.getInt("teacher.salary"),
new CategoryOfTeacher(
rs.getInt("category_of_teacher.id"),
rs.getString("category_of_teacher.category")),
new Chair(
rs.getInt("chair.id"),
rs.getString("chair.name"),
rs.getString("chair.head_of_chair"),
new Department(
rs.getInt("department.id"),
rs.getString("department.name"),
rs.getString("department.dean"),
new Deanery(rs.getInt("deanery.id"),
rs.getString("deanery.address"),
rs.getString("deanery.phone_number"))
)
)
);
statement.close();
return teacher;
}
@Override
public Teacher updateTeacher(Teacher teacher) throws SQLException {
String query = "UPDATE `newdb`.`teacher` SET `name`=?, `date_of_birth`=?, `count_of_children`=?, `salary`=?, `category_of_teacher_id`=?, `chair_id`=? WHERE `id`=?";
PreparedStatement statement = dataStorage.getConnection().prepareStatement(query);
statement.setString(1, teacher.getName());
statement.setDate(2, java.sql.Date.valueOf(teacher.getDateOfBirth()));
statement.setInt(3, teacher.getCountOfChildren());
statement.setInt(4, teacher.getSalary());
statement.setInt(5, teacher.getCategoryOfTeacher().getId());
statement.setInt(6, teacher.getChair().getId());
statement.setInt(7, teacher.getId());
int countUpdatedRows = statement.executeUpdate();
statement.close();
return teacher;
}
@Override
public void deleteTeacher(int id) throws SQLException {
String query = "DELETE FROM `newdb`.`teacher` WHERE `id`=?";
PreparedStatement statement = dataStorage.getConnection().prepareStatement(query);
statement.setInt(1,id);
int countDeletedRows = statement.executeUpdate();
statement.close();
}
@Override
public List<Teacher> getAll() throws SQLException {
list.clear();
ResultSet rs = dataStorage.executeQuery("select * from teacher " +
"inner join category_of_teacher on category_of_teacher_id = category_of_teacher.id " +
"inner join chair on chair_id = chair.id " +
"inner join department on department_id = department.id " +
"inner join deanery on deanery_id = deanery.id " +
"order by teacher.id");
while (rs.next()){
list.add(new Teacher(
rs.getInt("teacher.id"),
rs.getString("teacher.name"),
rs.getDate("teacher.date_of_birth").toLocalDate(),
rs.getInt("teacher.count_of_children"),
rs.getInt("teacher.salary"),
new CategoryOfTeacher(
rs.getInt("category_of_teacher.id"),
rs.getString("category_of_teacher.category")),
new Chair(
rs.getInt("chair.id"),
rs.getString("chair.name"),
rs.getString("chair.head_of_chair"),
new Department(
rs.getInt("department.id"),
rs.getString("department.name"),
rs.getString("department.dean"),
new Deanery(rs.getInt("deanery.id"),
rs.getString("deanery.address"),
rs.getString("deanery.phone_number"))
)
)
));
}
return list;
}
}
| true |
9abb4e9d626ab5de756a331a6287c2a65687cc16 | Java | wind-o-f-change/CarePortalWebApp | /src/main/java/ru/careportal/core/config/AopConfig.java | UTF-8 | 1,305 | 2.125 | 2 | [] | no_license | package ru.careportal.core.config;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Aspect
@Configuration
public class AopConfig {
@Pointcut("within(ru.careportal.core.controller..*)")
public void controllersPoint(){}
@Before("controllersPoint()")
public void logControllers(JoinPoint point) {
log.debug(point.toShortString());
}
@AfterThrowing(value = "controllersPoint()", throwing = "e")
public void logErrorControllers(JoinPoint point, Throwable e) {
log.warn(String.format("%s method throw exception: %s", point.toShortString(), e));
}
@Pointcut("within(ru.careportal.core.service..*)")
public void servicesPoint(){}
@Before("servicesPoint()")
public void logServices(JoinPoint point){
log.debug(point.toShortString());
}
@AfterThrowing(value = "servicesPoint()", throwing = "e")
public void logErrServices(JoinPoint point, Throwable e){
log.warn(String.format("%s method throw exception: %s", point.toShortString(), e));
}
}
| true |
dd3ae5f37944b4d1ce7de49bb6dbd4da50c78d71 | Java | voidmirror/NC_dockerMavenPostman | /spring-boot-data-jpa-2021-v2/src/main/java/com/netcracker/controller/ContactController.java | UTF-8 | 1,772 | 2.34375 | 2 | [] | no_license | package com.netcracker.controller;
import com.netcracker.exception.ResourceNotFoundException;
import com.netcracker.model.Contact;
import com.netcracker.repository.ContactRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/rest/v1")
public class ContactController {
@Autowired
private ContactRepository contactRepository;
@GetMapping("/contacts")
public List<Contact> retrieveAllContacts() {
return contactRepository.findAll();
}
@GetMapping("/contacts/{id}")
public ResponseEntity<Contact> findContactById(
@PathVariable(value = "id") Integer contactId
) throws ResourceNotFoundException {
Contact contact = contactRepository.findById(contactId)
.orElseThrow(() -> new ResourceNotFoundException("contact not found for id: "+contactId));
return ResponseEntity.ok().body(contact);
}
@PostMapping("/contacts")
public Contact createContact(@RequestBody Contact contact) {
return contactRepository.save(contact);
}
@DeleteMapping("/contacts/{id}")
public Map<String, Boolean> deleteContact(@PathVariable(value = "id") Integer contactId) throws ResourceNotFoundException {
Contact contact = contactRepository.findById(contactId)
.orElseThrow(() -> new ResourceNotFoundException("contact not found for id: "+contactId));
contactRepository.delete(contact);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
}
| true |
06a9d95757ee66590d07725d2c660781130a4d03 | Java | Conanjun/HK_CPDT | /src/com/cw/wizbank/report/SynlrnActivityReportScheduler.java | UTF-8 | 2,940 | 2.171875 | 2 | [] | no_license | package com.cw.wizbank.report;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.cw.wizbank.ScheduledTask;
import com.cw.wizbank.config.WizbiniLoader;
import com.cw.wizbank.message.MessageScheduler;
import com.cw.wizbank.util.cwSQL;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
public class SynlrnActivityReportScheduler extends ScheduledTask implements Job{
public SynlrnActivityReportScheduler(){
logger = Logger.getLogger(MessageScheduler.class);
}
@Override
protected void init() {
// TODO Auto-generated method stub
}
@Override
protected void process() {
try {
wizbini = WizbiniLoader.getInstance();
dbSource = new cwSQL();
dbSource.setParam(wizbini);
con = dbSource.openDB(false);
synLrarnRecord(con);
con.commit();
}
catch (Exception e) {
logger.debug("error in SynlrnActivityReportScheduler process()");
logger.debug(e);
try {
if (con != null && !con.isClosed()) {
con.rollback();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
finally {
try {
if (con != null) {
con.close();
}
}
catch (Exception e) {
logger.debug("error in SynlrnActivityReportScheduler()");
logger.debug(e);
}
}
}
public void synLrarnRecord(Connection con) throws SQLException{
//删除表数据
delLrnActivityReport(con);
//添加表数据
String sql = "insert into lrnActivityReport (lar_c_itm_id,lar_p_itm_id,lar_usr_ent_id,lar_app_id,lar_tkh_id,lar_att_ats_id,lar_cov_score,lar_cov_total_time,lar_attempts_user,lar_total_attempt,";
sql += " lar_app_create_timestamp,lar_app_status,lar_app_process_status,lar_att_timestamp,lar_att_create_timestamp,lar_att_remark,lar_att_rate,lar_cov_cos_id,lar_cov_commence_datetime, lar_cov_last_acc_datetime)";
sql += " select lar_c_itm_id,lar_p_itm_id,lar_usr_ent_id,lar_app_id,lar_tkh_id,lar_att_ats_id,lar_cov_score,lar_cov_total_time,lar_attempts_user,lar_total_attempt, ";
sql += " lar_app_create_timestamp,lar_app_status,lar_app_process_status,lar_att_timestamp,lar_att_create_timestamp,lar_att_remark,lar_att_rate,lar_cov_cos_id,lar_cov_commence_datetime, lar_cov_last_acc_datetime";
sql += " from view_lrn_activity_group";
PreparedStatement stmt = con.prepareStatement(sql);
stmt.executeUpdate();
if(stmt != null){
stmt.close();
}
}
public void delLrnActivityReport(Connection con) throws SQLException {
PreparedStatement stmt = null;
try {
stmt = con.prepareStatement("truncate table lrnActivityReport");
stmt.executeUpdate();
} finally {
if (stmt != null)
stmt.close();
}
return;
}
@Override
public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
init();
process();
}
}
| true |
9e6ba50c31a1ed3845e8cec30142015c80471060 | Java | DonSiMP/retina | /src/main/java/ch/ethz/idsc/demo/mp/pid/PIDCurveHelper.java | UTF-8 | 1,196 | 2.390625 | 2 | [] | no_license | // code by mcp
package ch.ethz.idsc.demo.mp.pid;
import ch.ethz.idsc.sophus.planar.ArcTan2D;
import ch.ethz.idsc.tensor.Scalar;
import ch.ethz.idsc.tensor.Tensor;
import ch.ethz.idsc.tensor.red.ArgMin;
import ch.ethz.idsc.tensor.red.Norm;
/* package */ enum PIDCurveHelper {
;
/** @param curve
* @param pose
* @return position of the closest point on the curve to the current pose */
public static int closest(Tensor curve, Tensor pose) {
return ArgMin.of(Tensor.of(curve.stream().map(curvePoint -> Norm._2.between(curvePoint, pose))));
}
/** @param curve
* @param point
* @return angle between two following points of the closest point on the curve to the current pose */
public static Scalar trajAngle(Tensor curve, Tensor point) {
int index = closest(curve, point);
int nextIndex = index + 1;
if (nextIndex > curve.length()) // TODO MCP Write this better
nextIndex = 0;
return ArcTan2D.of(curve.get(nextIndex).subtract(curve.get(index)));
}
/** @param optionalCurve
* @return if enough elements in curve */
static boolean bigEnough(Tensor optionalCurve) {
return optionalCurve.length() > 1; // TODO MCP Write this better
}
} | true |
bfbd6e71a51081963977ad79ba98fc9680fb91f0 | Java | steven28zhang/ITTechlife | /itlCore/src/main/java/com/sxw/itl/utils/io/file/FileOperations.java | UTF-8 | 1,900 | 2.578125 | 3 | [] | no_license | /**
*
*/
package com.sxw.itl.utils.io.file;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.sxw.itl.common.ITLConstants.Symbols;
/**
* @author stephenxianweizhang@gmail.com
*
*/
public final class FileOperations {
private static final Log logger = LogFactory.getLog(FileOperations.class);
private static final String className = FileOperations.class.getName();
public static final String getFileType(final String fileName) {
if (fileName == null || fileName.length() < 1) {
return null;
}
String fileType = null;
if (fileName.indexOf(Symbols.SYMBOL_COMMA) > 0) {
fileType = fileName.substring(fileName
.indexOf(Symbols.SYMBOL_COMMA) + 1);
}
return fileType;
}
/**
* read the uploaded file<br>
*
* @param uploadedFile
* @return
* @throws IOException
*/
public static final byte[] readUploadFile(File uploadedFile)
throws IOException {
FileInputStream fileInput = new FileInputStream(uploadedFile);
byte[] readFile = new byte[fileInput.available()];
fileInput.read(readFile);
fileInput.close();
return readFile;
}
/**
*
* @param in
* @param formDataLength
* @return
* @throws IOException
*/
public static final byte[] readUploadFileInputStream(final DataInputStream in,
final int formDataLength) throws IOException {
byte[] readFile = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
// this loop converting the uploaded file into byte code
while (totalBytesRead < formDataLength) {
byteRead = in.read(readFile, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
return readFile;
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(getFileType("terms and condtions.html"));
}
}
| true |