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
fb8c961304f4d1aa0c0ce33e15dccace78c7c542
Java
DonJayamanne/vscode-javac
/src/test/java/org/javacs/ResponseCollector.java
UTF-8
421
2.203125
2
[]
no_license
package org.javacs; import org.javacs.message.Response; import org.javacs.message.ResponseChannel; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class ResponseCollector implements ResponseChannel { public final List<Response> responses = new ArrayList<>(); @Override public void next(Response response) throws IOException { responses.add(response); } }
true
e5c6fc5b8a9734b139bbf27379ee85be1ce2c59f
Java
dadaabcamps/Mrefugee2017
/app/src/main/java/com/drcdadaab/mrefugee/NewsViewHolder.java
UTF-8
1,000
2.03125
2
[]
no_license
package com.drcdadaab.mrefugee; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.github.curioustechizen.ago.RelativeTimeTextView; /** * Created by oriaso on 9/22/17. */ public class NewsViewHolder extends RecyclerView.ViewHolder { TextView textViewNewsListTitle, textViewNewsListAuthor; RelativeTimeTextView textViewNewsListSince; View mView; ImageView imageViewNewsListImage; public NewsViewHolder(View itemView){ super(itemView); this.mView = itemView; textViewNewsListTitle = (TextView) itemView.findViewById(R.id.textViewNewsListTitle); textViewNewsListAuthor = (TextView) itemView.findViewById(R.id.textViewNewsListAuthor); textViewNewsListSince = (RelativeTimeTextView) itemView.findViewById(R.id.textViewNewsListSince); imageViewNewsListImage = (ImageView) itemView.findViewById(R.id.imageViewNewsListImage); } }
true
a08c0c6308beb3f7ce655568bbde8d45f3112ea0
Java
P79N6A/icse_20_user_study
/methods/Method_22146.java
UTF-8
482
2.921875
3
[]
no_license
/** * ???????????????. * @param itemsString ?????? * @return ????? */ public static List<Integer> toItemList(final String itemsString){ if (Strings.isNullOrEmpty(itemsString)) { return Collections.emptyList(); } String[] items=itemsString.split(DELIMITER); List<Integer> result=new ArrayList<>(items.length); for ( String each : items) { int item=Integer.parseInt(each); if (!result.contains(item)) { result.add(item); } } return result; }
true
99d6e98441661aefa420532accb5fa3740217a88
Java
jingsan0801/ktanx-jdbc
/ktanx-jdbc/src/main/java/com/ktanx/jdbc/command/simple/ResultHandler.java
UTF-8
187
1.84375
2
[ "Apache-2.0" ]
permissive
package com.ktanx.jdbc.command.simple; public interface ResultHandler<T> { /** * 处理结果 * * @param object * @return */ T handle(Object object); }
true
f9c319e25253d5dfacae87b43e73a60a89bcfd39
Java
RollingSoftware/L2J_HighFive_Hardcore
/l2j_server/src/main/java/com/l2jserver/gameserver/network/serverpackets/StaticObject.java
UTF-8
2,484
2.359375
2
[ "MIT" ]
permissive
/* * Copyright (C) 2004-2016 L2J Server * * This file is part of L2J Server. * * L2J Server is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * L2J Server is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jserver.gameserver.network.serverpackets; import com.l2jserver.gameserver.model.actor.instance.L2DoorInstance; import com.l2jserver.gameserver.model.actor.instance.L2StaticObjectInstance; /** * @author KenM */ public class StaticObject extends L2GameServerPacket { private final int _staticObjectId; private final int _objectId; private final int _type; private final boolean _isTargetable; private final int _meshIndex; private final boolean _isClosed; private final boolean _isEnemy; private final int _maxHp; private final int _currentHp; private final boolean _showHp; private final int _damageGrade; public StaticObject(L2StaticObjectInstance staticObject) { _staticObjectId = staticObject.getId(); _objectId = staticObject.getObjectId(); _type = 0; _isTargetable = true; _meshIndex = staticObject.getMeshIndex(); _isClosed = false; _isEnemy = false; _maxHp = 0; _currentHp = 0; _showHp = false; _damageGrade = 0; } public StaticObject(L2DoorInstance door, boolean targetable) { _staticObjectId = door.getId(); _objectId = door.getObjectId(); _type = 1; _isTargetable = door.isTargetable() || targetable; _meshIndex = door.getMeshIndex(); _isClosed = !door.getOpen(); _isEnemy = door.isEnemy(); _maxHp = door.getMaxHp(); _currentHp = (int) door.getCurrentHp(); _showHp = door.getIsShowHp(); _damageGrade = door.getDamage(); } @Override protected final void writeImpl() { writeC(0x9f); writeD(_staticObjectId); writeD(_objectId); writeD(_type); writeD(_isTargetable ? 1 : 0); writeD(_meshIndex); writeD(_isClosed ? 1 : 0); writeD(_isEnemy ? 1 : 0); writeD(_currentHp); writeD(_maxHp); writeD(_showHp ? 1 : 0); writeD(_damageGrade); } }
true
9fb27f928ab9d69ad97cc3c3cb9265ce557fbe8f
Java
xsa1994/hx
/src/main/java/com/hx/mapper/SeoConfigMapper.java
UTF-8
220
1.820313
2
[]
no_license
package com.hx.mapper; import com.hx.domain.SeoConfig; public interface SeoConfigMapper { int insertHxSeoConfig(SeoConfig object); int updateHxSeoConfig(SeoConfig object); SeoConfig selectSeoConfig(); }
true
209d1915626cfccc7ede8deea255c502069a5126
Java
nice79422/project
/project/nexacro/erpNexacroJava/57thERP/src/main/java/kr/co/seoulit/statement/financialStatement/applicationService/FinancialStatementApplicationServiceImpl.java
UTF-8
2,656
2.046875
2
[]
no_license
package kr.co.seoulit.statement.financialStatement.applicationService; import java.util.HashMap; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import kr.co.seoulit.statement.financialStatement.dao.EarlyFinancialStatementsDAO; import kr.co.seoulit.statement.financialStatement.dao.FinancialStatementsDAO; import kr.co.seoulit.statement.financialStatement.to.EarlyAssetsCountTO; import kr.co.seoulit.statement.financialStatement.to.EarlyFinancialStatementsTO; import kr.co.seoulit.statement.financialStatement.to.EarlyLiabilitiesAndCapitalCountTO; import kr.co.seoulit.statement.financialStatement.to.FinancialStatementsTO; import kr.co.seoulit.statement.financialStatement.to.eFinancialStatementsTO; @Component public class FinancialStatementApplicationServiceImpl implements FinancialStatementApplicationService { @Autowired private FinancialStatementsDAO financialStatementsDAO; @Autowired private EarlyFinancialStatementsDAO earlyFinancialStatementsDAO; @Override public List<FinancialStatementsTO> findFinancialStatements(HashMap<String, Object> approvalDate) { // TODO Auto-generated method stub List<FinancialStatementsTO> FinancialStatementsList = null; FinancialStatementsList = financialStatementsDAO.selectFinancialStatements(approvalDate); return FinancialStatementsList; } @Override public List<eFinancialStatementsTO> getEFinancialStatements(){ // TODO Auto-generated method stub List<eFinancialStatementsTO> eFinancialStatementsList = null; eFinancialStatementsList = financialStatementsDAO.selectEFinancialStatements(); return eFinancialStatementsList; } @Override public List<EarlyAssetsCountTO> findAssetsOnLastYear() { // TODO Auto-generated method stub List<EarlyAssetsCountTO> earlyAccountCountList = null; earlyAccountCountList = earlyFinancialStatementsDAO.selectAssetsOnLastYear(); return earlyAccountCountList; } @Override public List<EarlyLiabilitiesAndCapitalCountTO> findLiabilitiesAndCapitalOnLastYear() { // TODO Auto-generated method stub List<EarlyLiabilitiesAndCapitalCountTO> earlyAccountCountList = null; earlyAccountCountList = earlyFinancialStatementsDAO.selectLiabilitiesAndCapitalOnLastYear(); return earlyAccountCountList; } @Override public List<EarlyFinancialStatementsTO> findFinancialStatementsOnLastYear(){ // TODO Auto-generated method stub List<EarlyFinancialStatementsTO> earlyFinancialStatementsList = null; earlyFinancialStatementsList = earlyFinancialStatementsDAO.selectFinancialStatementsOnLastYear(); return earlyFinancialStatementsList; } }
true
3d0c2720be25d19ec0e002fc61ff7c39a5580a6b
Java
HardWareMall2016/AoYouStore
/app/src/main/java/com/zhan/aoyoustore/utils/Tools.java
UTF-8
19,519
1.828125
2
[]
no_license
package com.zhan.aoyoustore.utils; import android.app.Activity; import android.app.Dialog; import android.app.DownloadManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Environment; import android.text.TextUtils; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.TextView; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONException; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.utils.DiskCacheUtils; import com.nostra13.universalimageloader.utils.MemoryCacheUtils; import com.zhan.aoyoustore.R; import com.zhan.aoyoustore.base.App; import com.zhan.aoyoustore.base.BaseResponseBean; import com.zhan.aoyoustore.base.UserInfo; import com.zhan.aoyoustore.ui.activity.MainActivity; import com.zhan.aoyoustore.ui.fragment.login.LoginFragment; import com.zhan.framework.component.container.FragmentContainerActivity; import com.zhan.framework.utils.ToastUtils; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Objects; import static java.util.Calendar.DAY_OF_MONTH; import static java.util.Calendar.MONTH; import static java.util.Calendar.YEAR; /** * 作者:伍岳 on 2016/3/7 21:55 * 邮箱:wuyue8512@163.com // // ............................................. // 美女坐镇 BUG辟易 // ............................................. // // .::::. // .::::::::. // ::::::::::: // ..:::::::::::' // '::::::::::::' // .:::::::::: // '::::::::::::::.. // ..::::::::::::. // ``:::::::::::::::: // ::::``:::::::::' .:::. // ::::' ':::::' .::::::::. // .::::' :::: .:::::::'::::. // .:::' ::::: .:::::::::' ':::::. // .::' :::::.:::::::::' ':::::. // .::' ::::::::::::::' ``::::. // ...::: ::::::::::::' ``::. // ```` ':. ':::::::::' ::::.. // '.:::::' ':'````.. // */ public class Tools { public static DisplayImageOptions buldDefDisplayImageOptions(){ return new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.ic_launcher) .showImageForEmptyUri(R.drawable.ic_launcher) .showImageOnFail(R.drawable.ic_launcher) .cacheInMemory(true) .bitmapConfig(Bitmap.Config.RGB_565) .cacheOnDisk(true) .imageScaleType(ImageScaleType.IN_SAMPLE_INT) .considerExifParams(true) .build(); } public static String md5(String string) { byte[] hash = null; try { hash = string.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Huh,UTF-8 should be supported?", e); } return computeMD5(hash); } public static String computeMD5(byte[] input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(input, 0, input.length); byte[] md5bytes = md.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < md5bytes.length; i++) { String hex = Integer.toHexString(0xff & md5bytes[i]); if (hex.length() == 1) hexString.append('0'); hexString.append(hex); } return hexString.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } /*** * 解析服务器时间,服务器是GMT+08时区 * * @param serverTimeStr * @return 返回 时间戳 */ /*public static long parseServerTime(String serverTimeStr) { if (TextUtils.isEmpty(serverTimeStr)) { return 0; } final String FORMAT = "yyyy-MM-dd HH:mm:ss"; Date date = DateUtil.parseDate(serverTimeStr, FORMAT, TimeZone.getTimeZone("GMT+08")); if (date == null) { return 0; } return date.getTime(); }*/ /*** * 时间戳转换 */ public static String parseTime(Long time) { Date date=new Date(time); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String strTime =format.format(date); return strTime; } public static String parseTimeToDateStr(Long time) { Date date=new Date(time); SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); String strTime =format.format(date); return strTime; } /*** * 将时间戳转换为日期或时间字符串,当前显示时间其他显示日期 * @param time * @return */ public static String parseToTimeOrDateStr(Long time) { SimpleDateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd"); String strDate =formatDate.format(time); SimpleDateFormat formatTime=new SimpleDateFormat("HH:mm:ss"); String strTime =formatTime.format(time); String strDateToday =formatDate.format(System.currentTimeMillis()); if(strDateToday.equals(strDate)){ return strTime; }else{ return strDate; } } /*** * 将时间戳装换为服务器时间字符串 * 服务器是GMT+08时区 * * @param time * @return */ /*public static String formatToServerTimeStr(long time) { if (time > 0) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08")); Date date = new Date(time); return dateFormat.format(date); } else { return null; } }*/ /*** * 装换Json * * @param json * @param beanClass * @return 如果转换出错 返回 */ public static <T> T parseJson(String json, Class<T> beanClass) { T bean = null; try { bean = JSON.parseObject(json, beanClass); } catch (JSONException ex) { Log.e("Utils", "fromJson error : " + ex.getMessage()); } return bean; } /** * 将Json String 转换为JsonObject 如果Json格式错误或Code!=0 返回null * * @param json * @param beanClass * @param <T> * @return 转换正确且Code==0返回 beanClass,否则返回null,并Toast 错误信息 */ public static <T> T parseJsonTostError(String json, Class<T> beanClass) { T bean = parseJson(json, beanClass); if (bean == null) { ToastUtils.toast(R.string.json_syntax_error); } else { BaseResponseBean baseResponseBean=parseJson(json,BaseResponseBean.class); if (baseResponseBean == null) { ToastUtils.toast(R.string.json_syntax_error); }else if (baseResponseBean.getResult().getRes() == 1) { return bean; } else if (baseResponseBean.getResult().getRes() == 100) { ToastUtils.toast(R.string.utils_token_timeout); UserInfo.logout(); Intent intent = new Intent(App.getInstance(), FragmentContainerActivity.class); intent.putExtra("className", LoginFragment.class.getName()); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); App.getInstance().startActivity(intent); /*Intent homePageIntent = new Intent(App.getInstance(), MainActivity.class); homePageIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); App.getInstance().startActivity(homePageIntent);*/ } else { ToastUtils.toast(baseResponseBean.getResult().getMsg()); } } return null; } public static String verifyResponseResult(String jsonStr) { String errorMsg = null; BaseResponseBean bean = parseJson(jsonStr, BaseResponseBean.class); if (bean == null) { errorMsg = App.getInstance().getString(R.string.json_syntax_error); } else if (bean.getResult().getRes() == 1) { errorMsg = null; } else if (bean.getResult().getRes() == 100) { errorMsg = App.getInstance().getString(R.string.utils_token_timeout); ToastUtils.toast(errorMsg); UserInfo.logout(); Intent intent = new Intent(App.getInstance(), FragmentContainerActivity.class); intent.putExtra("className", LoginFragment.class.getName()); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); App.getInstance().startActivity(intent); /*Intent homePageIntent = new Intent(App.getInstance(), MainActivity.class); homePageIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); App.getInstance().startActivity(homePageIntent);*/ } else { errorMsg = bean.getResult().getMsg(); } return errorMsg; } public static boolean sameDate(Calendar cal, Calendar selectedDate) { return cal.get(MONTH) == selectedDate.get(MONTH) && cal.get(YEAR) == selectedDate.get(YEAR) && cal.get(DAY_OF_MONTH) == selectedDate.get(DAY_OF_MONTH); } public static boolean betweenDates(Calendar cal, Calendar minCal, Calendar maxCal) { final Date date = cal.getTime(); return betweenDates(date, minCal, maxCal); } public static boolean betweenDates(Date date, Calendar minCal, Calendar maxCal) { final Date min = minCal.getTime(); return (date.equals(min) || date.after(min)) // >= minCal && date.before(maxCal.getTime()); // && < maxCal } public static void hideSoftInputFromWindow(View view) { InputMethodManager imm = (InputMethodManager) App.getInstance().getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } /** * 下载并安装app * * @param url */ public static void installApp(String url) { final DownloadManager systemService = (DownloadManager) App.getInstance().getSystemService(Context.DOWNLOAD_SERVICE); DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "upgrade.apk"); systemService.enqueue(request); IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE); final BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); DownloadManager.Query myDownloadQuery = new DownloadManager.Query(); myDownloadQuery.setFilterById(reference); Cursor myDownload = systemService.query(myDownloadQuery); if (myDownload.moveToFirst()) { int fileUriIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI); String fileUri = myDownload.getString(fileUriIdx); Intent ViewInstallIntent = new Intent(Intent.ACTION_VIEW); ViewInstallIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); ViewInstallIntent.setDataAndType(Uri.parse(fileUri), "application/vnd.android.package-archive"); context.startActivity(ViewInstallIntent); } myDownload.close(); App.getInstance().unregisterReceiver(this); } }; App.getInstance().registerReceiver(receiver, filter); } public static int getScreenWidth(Activity context) { DisplayMetrics dm = new DisplayMetrics(); context.getWindowManager().getDefaultDisplay().getMetrics(dm); return dm.widthPixels; } public static int getScreenHeight(Activity context) { DisplayMetrics dm = new DisplayMetrics(); context.getWindowManager().getDefaultDisplay().getMetrics(dm); return dm.heightPixels; } public static Dialog createDialog(Activity context, int dialogLayoutRes) { final Dialog dialog = new Dialog(context, com.zhan.framework.R.style.Dialog); dialog.setContentView(dialogLayoutRes); /*Window window = dialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); int screenW = getScreenWidth(context); lp.width = (int) (0.6 * screenW);*/ return dialog; } public static Dialog showConfirmDialog(Activity activity,String title,String summary,View.OnClickListener onConfirmClickListener,Object tag){ final Dialog confirmDialog=Tools.createDialog(activity, R.layout.dialog_cancel_or_confirm); TextView titleView= (TextView)confirmDialog.findViewById(R.id.title); titleView.setText(title); TextView summaryView= (TextView)confirmDialog.findViewById(R.id.summary); summaryView.setText(summary); TextView cancelBtn= (TextView)confirmDialog.findViewById(R.id.cancel); cancelBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { confirmDialog.dismiss(); } }); TextView confirmBtn= (TextView)confirmDialog.findViewById(R.id.confirm); confirmBtn.setTag(tag); confirmBtn.setOnClickListener(onConfirmClickListener); confirmDialog.show(); return confirmDialog; } public static boolean checkMobilePhoneNumber(String phoneNumber) { String telRegex = "[1]\\d{10}"; if (TextUtils.isEmpty(phoneNumber)) return false; else return phoneNumber.matches(telRegex); } public static String parseTimeLeftStr(long between){ int day = (int) (between / (24 * 60 * 60 * 1000)); int hour = (int) (between / (60 * 60 * 1000) - day * 24); int min = (int) ((between / (60 * 1000)) - day * 24 * 60 - hour * 60); int second = (int) (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); return String.format("%02d天 %02d小时 %02d分 %02d秒",day,hour,min,second); } private static DisplayImageOptions sDefAvatarDisplayImageOptions; /** * 头像选项 * @return */ public static DisplayImageOptions buildDisplayImageOptionsForAvatar(){ if(sDefAvatarDisplayImageOptions ==null){ sDefAvatarDisplayImageOptions = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.bg_head_portrait) .showImageForEmptyUri(R.drawable.bg_head_portrait) .showImageOnFail(R.drawable.bg_head_portrait) .cacheInMemory(true) .cacheOnDisk(true) .considerExifParams(true) .build(); } return sDefAvatarDisplayImageOptions; } /** * 商品选项 * @return */ private static DisplayImageOptions sDefDisplayGoodsImageOptions; public static DisplayImageOptions buildDisplayGoodsImgOptions(){ if(sDefDisplayGoodsImageOptions ==null){ sDefDisplayGoodsImageOptions = new DisplayImageOptions.Builder() .showImageOnLoading(R.drawable.def_pic) .showImageForEmptyUri(R.drawable.def_pic) .showImageOnFail(R.drawable.def_pic) .cacheInMemory(true) .cacheOnDisk(true) .considerExifParams(true) .build(); } return sDefDisplayGoodsImageOptions; } public static void removeImgFromCache(String imgUrl) { MemoryCacheUtils.removeFromCache(imgUrl, ImageLoader.getInstance().getMemoryCache()); DiskCacheUtils.removeFromCache(imgUrl, ImageLoader.getInstance().getDiskCache()); } public static void clearImgCahce() { ImageLoader.getInstance().clearDiskCache(); ImageLoader.getInstance().clearMemoryCache(); } private static long lastClickTime; public synchronized static boolean isFastClick() { long time = System.currentTimeMillis(); if ( time - lastClickTime < 500) { return true; } lastClickTime = time; return false; } public static void setTextView(TextView textView,String text){ if(textView==null){ return; } if(TextUtils.isEmpty(text)){ textView.setText(""); }else{ textView.setText(text); } } /*** * 检测是否登录,如果没有登录就启动登录页面 * @param activity * @return */ public static boolean checkIsLogin(Activity activity){ if (UserInfo.getCurrentUser() == null || !UserInfo.getCurrentUser().isLogin()) { LoginFragment.launch(activity); return false; } return true; } public static boolean isLogin(){ if (UserInfo.getCurrentUser() == null || !UserInfo.getCurrentUser().isLogin()) { return false; } return true; } public static Dialog showDialogFromBottom(Activity activity, int dialogLayout, boolean showSoftInput) { Dialog dialog = new Dialog(activity, com.zhan.framework.R.style.Dialog); dialog.setContentView(dialogLayout); Window window = dialog.getWindow(); if (showSoftInput) { window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); } WindowManager.LayoutParams lp = window.getAttributes(); lp.width = Tools.getScreenWidth(activity); window.setGravity(Gravity.BOTTOM); //此处可以设置dialog显示的位置 window.setWindowAnimations(R.style.pop_menu_animation); //添加动画 dialog.show(); return dialog; } public static String formatNumber(double value){ DecimalFormat nf = new DecimalFormat("##.##"); return nf.format(value); } public static String formatNumberWithMoney(double value){ DecimalFormat nf = new DecimalFormat("¥###,###,###.##"); return nf.format(value); } }
true
8d3aed6496795fa6e56aa7da6498770e36d2e399
Java
jianghang/JavaAction
/SE/src/main/java/com/hangjiang/designmode/factory/SendMailFactory.java
UTF-8
227
2.0625
2
[]
no_license
package com.hangjiang.designmode.factory; /** * Created by jianghang on 2017/4/29. */ public class SendMailFactory implements IProvider { @Override public ISender produce() { return new MailSender(); } }
true
c17935da2bc12736b2577646e2c7e54f6bb2600c
Java
harneet-9039/NotifyMe
/app/src/main/java/app/com/admin/Admin_ViewRequest.java
UTF-8
7,866
1.976563
2
[]
no_license
package app.com.admin; import android.app.ProgressDialog; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.Toolbar; import androidx.appcompat.app.AppCompatActivity; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.google.android.material.snackbar.Snackbar; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import app.com.adapters.ViewRequestAdapter; import app.com.common.GlobalMethods; import app.com.common.Singleton; import app.com.models.ViewRequestModel; import app.com.notifyme.R; public class Admin_ViewRequest extends AppCompatActivity { private ArrayList<String> requests=new ArrayList<>(); private SharedPreferences pref; private SharedPreferences.Editor editor; private Button Accept,Reject; private ProgressDialog progressDialog; private Toolbar toolbar; private View view; private ArrayList<ViewRequestModel> viewRequestModelArrayList; private ViewRequestAdapter viewRequestAdapter; private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_request); listView = findViewById(R.id.list); Accept=findViewById(R.id.acceptbtn); Reject=findViewById(R.id.rejectbtn); CommonWorkOfMenuItems(); viewRequestModelArrayList = new ArrayList<>(); progressDialog = new ProgressDialog(this); androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Notify Me"); LoadData(); } private void LoadData() { String URL = GlobalMethods.getURL()+"viewRequests"; progressDialog.show(); progressDialog.setMessage("Fetching your requests..."); view =findViewById(R.id.mainreq); StringRequest jsonObjectRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d("HAR", response); viewRequestModelArrayList.clear(); try { JSONObject jsonObject = new JSONObject(response); int data=(int)jsonObject.get("code"); if (jsonObject.getBoolean("status") == true) { JSONArray dataArray = jsonObject.getJSONArray("data"); if (dataArray.length() < 1) { Snackbar.make(view, "No requests for you", Snackbar.LENGTH_INDEFINITE) .setAction("Retry", new View.OnClickListener() { @Override public void onClick(View view) { LoadData(); } }).show(); } else { for (int i = 0; i < dataArray.length(); i++) { ViewRequestModel noticeModel = new ViewRequestModel(); ArrayList<String> attachmentList = new ArrayList<>(); JSONObject dataobj = dataArray.getJSONObject(i); noticeModel.setRequestId(dataobj.getString("request_id")); noticeModel.setDate(dataobj.getString("date")); noticeModel.setFacultyName(dataobj.getString("faculty_name")); noticeModel.setValidity(String.valueOf(dataobj.getInt("duration"))); String[] names = dataobj.getString("Student_name").split(","); ArrayList<String> studentnameList = new ArrayList<>(); for (String name : names) { studentnameList.add(name); } String[] regid = dataobj.getString("Student_id").split(","); ArrayList<String> studentIDList = new ArrayList<>(); for (String name : regid) { studentIDList.add(name); } String[] status = dataobj.getString("status").split(","); ArrayList<String> statusList = new ArrayList<>(); for (String name : status) { statusList.add(name); } noticeModel.setNames(studentnameList); noticeModel.setRegistrationID(studentIDList); noticeModel.setStatus(statusList); viewRequestModelArrayList.add(noticeModel); } } } } catch (JSONException e) { e.printStackTrace(); Snackbar.make(view, "Exception Occured", Snackbar.LENGTH_LONG) .show(); } Collections.sort(viewRequestModelArrayList, ViewRequestModel.priorityComparator); viewRequestAdapter = new ViewRequestAdapter(Admin_ViewRequest.this, viewRequestModelArrayList, view); listView.setAdapter(viewRequestAdapter); progressDialog.dismiss(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("HAR",error.toString()); Snackbar.make(view, "Error Response from Server", Snackbar.LENGTH_INDEFINITE) .setAction("Retry", new View.OnClickListener(){ @Override public void onClick(View view) { LoadData(); } }).show(); progressDialog.dismiss(); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> parameters = new HashMap<>(); // Log.d("HAR",String.valueOf(DepartmentID)); /* if(pref.getString("fregistrationNumber","")!="") { parameters.put("faculty_id",pref.getString("fregistrationNumber","")); }*/ //if(pref.getString("actionRequest","")!="") return parameters; } }; Singleton.getInstance(this).addToRequestQueue(jsonObjectRequest); } private void CommonWorkOfMenuItems() { pref = getApplicationContext().getSharedPreferences("UserVals", 0); // 0 - for private mode editor = pref.edit(); //androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.requesttoolbarstatus); // setSupportActionBar(toolbar); //getSupportActionBar().setTitle(Html.fromHtml("<small>View request status</small>")); } }
true
e1d0a5a2463cb15622d597155af9c8751787e942
Java
zulkarnainfaizan/EduVisualize
/app/src/main/java/com/example/julqa_000/eduvisualize/StudentModule.java
UTF-8
7,860
2.171875
2
[]
no_license
package com.example.julqa_000.eduvisualize; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.webkit.WebChromeClient; import android.webkit.WebView; import android.widget.AdapterView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; public class StudentModule extends AppCompatActivity { // static TextView dataDb; ListView listLog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_student_module); // setContentView(R.layout.activity_chart_registration); // dataDb=findViewById(R.id.dataDB); listLog = findViewById(R.id.listViewInserted); // WebView webView=findViewById(R.id.webViewId); // webView.getSettings().setJavaScriptEnabled(true); // webView.getSettings().setBuiltInZoomControls(true); // // webView.setWebChromeClient(new WebChromeClient()); //// setContentView(webView); // webView.loadUrl("http://zulkarnainfaizan.000webhostapp.com/ProMajor3D/php/mainphp.php"); new StudentModule.ConnectToRemote().execute("http://zulkarnainfaizan.000webhostapp.com/ProMajor3D/AndroidPhp/mainphp.php"); } class ConnectToRemote extends AsyncTask<String, String, String> { String data=""; HashMap<String,String> arrayLog=new HashMap<>(); @Override protected String doInBackground(String... params) { URL url; HttpURLConnection connection; StringBuilder builder = new StringBuilder(); String readFromRemote; //Add the username to URL String urlToHit = null; // try { urlToHit = params[0]; // } catch (UnsupportedEncodingException e) { // Log.e("USException", e.getMessage()); // } Log.e("urlToHit", urlToHit); try { //pass the url to URL object url = new URL(urlToHit); //open the connection connection = (HttpURLConnection) url.openConnection(); //Write the code to fetch response //Get the inputStream InputStream in = connection.getInputStream(); //Get the InputStreamReader object InputStreamReader inReader = new InputStreamReader(in); //Pass the InputStreamReader to BufferedReader BufferedReader reader = new BufferedReader(inReader); //Traverse through the result while ((readFromRemote = reader.readLine()) != null) { builder.append(readFromRemote); data=data+readFromRemote; } // BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())) } catch (MalformedURLException e) { Log.e("ExceptionMUE", e.getMessage()); } catch (IOException e) { Log.e("ExceptionIO", e.getMessage()); // } catch (JSONException e) { // e.printStackTrace(); } return data; } @Override protected void onPostExecute(String s) { // Log.e("responseFromServer", s); // // //DIsplay the data from remote URL on a TOAST // // if (s.equalsIgnoreCase("member registered successfully")) { //// startActivity(new Intent(StudentModule.this, Dashboard.class)); // Toast.makeText(StudentModule.this, s, Toast.LENGTH_LONG).show(); // } else try { JSONArray JA = new JSONArray(s); for (int i = 0; i < JA.length(); i++) { JSONObject jo = (JSONObject) JA.get(i); String nameFromTable = jo.get("studentname").toString(); String rollFromTable = jo.get("enroll").toString(); arrayLog.put("Name: " + nameFromTable, "Enroll: " + rollFromTable); // Toast.makeText(StudentModule.this, nameFromTable, Toast.LENGTH_LONG).show(); // Toast.makeText(StudentModule.this, nameFromTable, Toast.LENGTH_LONG).show(); } } catch (JSONException e) { e.printStackTrace(); } final List<HashMap<String,String>> listItems=new ArrayList<>(); final SimpleAdapter adapter = new SimpleAdapter( StudentModule.this,listItems, R.layout.extra_list_sub_item_view,new String[]{"first","second"}, new int[]{R.id.etv1,R.id.etv2}); Iterator it= arrayLog.entrySet().iterator(); while (it.hasNext()){ HashMap<String,String> resultMap= new HashMap<>(); Map.Entry pair=(Map.Entry)it.next(); resultMap.put("first",pair.getKey().toString()); resultMap.put("second",pair.getValue().toString()); listItems.add(resultMap); } listLog.setAdapter(adapter); listLog.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { ////////////////////tricky part///////////// HashMap<String,String> my = (HashMap<String,String>)adapter.getItem(i); // my.remove(my); String myyy= my.get("second"); //////////////////lastpoint//////// String mm=myyy.substring(7); Toast.makeText(StudentModule.this, mm, Toast.LENGTH_LONG).show(); setContentView(R.layout.activity_chart_registration); ProgressBar bar=findViewById(R.id.progressBar2); WebView webView=findViewById(R.id.webViewId); webView.getSettings().setJavaScriptEnabled(true); webView.getSettings().setBuiltInZoomControls(true); webView.setWebChromeClient(new WebChromeClient()); // setContentView(webView); // webView.loadUrl("http://zulkarnainfaizan.000webhostapp.com/ProMajor3D/php/retrievereg.php"); // new StudentModule.ConnectToRemote().execute("http://zulkarnainfaizan.000webhostapp.com/ProMajor3D/php/collection.php" +"?enroll=" + URLEncoder.encode(params[0], "utf-8")); webView.loadUrl("http://zulkarnainfaizan.000webhostapp.com/ProMajor3D/php/collective.php?enroll="+mm); bar.setVisibility(View.INVISIBLE); // adapter.notifyDataSetChanged(); Log.e("status", "item clicked..."); //Show a Toast displaying the item has been clicked // Toast.makeText(DeleteDatabase.this, myyy + " Item deleted", Toast.LENGTH_SHORT).show(); } }); } } }
true
0550dfcbc1973fd2b2972e34c4c29f654fe5a4d5
Java
chpladmin/chpl-api
/chpl/chpl-service/src/main/java/gov/healthit/chpl/entity/statistics/CuresListingStatisticByAcbEntity.java
UTF-8
3,035
1.90625
2
[ "BSD-3-Clause", "BSD-2-Clause-Views" ]
permissive
package gov.healthit.chpl.entity.statistics; import java.time.LocalDate; import java.util.Date; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; import gov.healthit.chpl.domain.statistics.CuresListingStatisticByAcb; import gov.healthit.chpl.entity.CertificationBodyEntity; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Builder @Data @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "cures_listing_statistics_by_acb") public class CuresListingStatisticByAcbEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id", nullable = false) private Long id; @OneToOne(optional = true, fetch = FetchType.LAZY) @JoinColumn(name = "certification_body_id", insertable = true, updatable = true) private CertificationBodyEntity certificationBody; @Basic(optional = false) @Column(name = "cures_listing_without_cures_criteria_count", nullable = false) private Long curesListingWithoutCuresCriteriaCount; @Basic(optional = false) @Column(name = "cures_listing_withcures_criteria_count", nullable = false) private Long curesListingWithCuresCriteriaCount; @Basic(optional = false) @Column(name = "non_cures_listing_count", nullable = false) private Long nonCuresListingCount; @Basic(optional = false) @Column(name = "statistic_date", nullable = false) private LocalDate statisticDate; @Basic(optional = false) @Column(name = "creation_date", nullable = false) private Date creationDate; @Basic(optional = false) @Column(name = "deleted", nullable = false) private Boolean deleted; @Basic(optional = false) @Column(name = "last_modified_date", nullable = false) private Date lastModifiedDate; @Basic(optional = false) @Column(name = "last_modified_user", nullable = false) private Long lastModifiedUser; public CuresListingStatisticByAcbEntity(CuresListingStatisticByAcb domain) { this.id = domain.getId(); this.certificationBody = CertificationBodyEntity.getNewAcbEntity(domain.getCertificationBody()); this.curesListingWithoutCuresCriteriaCount = domain.getCuresListingWithoutCuresCriteriaCount(); this.curesListingWithCuresCriteriaCount = domain.getCuresListingWithCuresCriteriaCount(); this.nonCuresListingCount = domain.getNonCuresListingCount(); this.statisticDate = domain.getStatisticDate(); this.creationDate = domain.getCreationDate(); this.deleted = domain.getDeleted(); this.lastModifiedDate = domain.getLastModifiedDate(); this.lastModifiedUser = domain.getLastModifiedUser(); } }
true
6e426b9b22e6bd75fb399c3d77f97c879f916a6c
Java
jiujiujiujiujiuaia/SpringInAction
/spring/src/main/java/chapter4/AopTest.java
UTF-8
512
1.804688
2
[]
no_license
package chapter4; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes =Config.class) public class AopTest { @Autowired private Performence performence; @Test public void test(){ performence.performance(); } }
true
aa55c6ac146939afe4a372f91dfad423619bf403
Java
lilaoda/springcloundtest
/src/main/java/com/lhy/mybatis1/entity/User.java
UTF-8
506
2.015625
2
[]
no_license
package com.lhy.mybatis1.entity; import lombok.Data; import javax.validation.constraints.Max; import java.io.Serializable; @Data //@Table(name = "user") public class User implements Serializable{ // @Id // @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @Max(value = 99,message = "年龄最大不能超过99") private int age; private String account; private String password; private String sex; private String token; }
true
d9d1fe40dabede049aaa3a53d74e722467ebe57c
Java
imjinghun/university
/sjms/Four/src/first/Women.java
UTF-8
65
2.0625
2
[]
no_license
package first; public interface Women { public void play(); }
true
82b3daeb37c1b299de3c351e6f11f341e5be5241
Java
diegojuarez6/Practice
/src/main/java/mx/utng/practice/controller/InstanceController.java
UTF-8
1,735
2.359375
2
[]
no_license
package mx.utng.practice.controller; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ViewScoped; import javax.inject.Named; import org.springframework.beans.factory.annotation.Autowired; import mx.utng.practice.model.Instance; import mx.utng.practice.repository.InstanceRepository; @Named @ViewScoped public class InstanceController { @Autowired private InstanceRepository instanceRepository; private Instance instance = new Instance(); private List<Instance> instances; private boolean editMode = false; @PostConstruct public void init(){ setInstances(instanceRepository.finAll()); } public void save(){ instanceRepository.save(instance); if(!editMode){ getInstances().add(instance); } instance = new Instance(); setEditMode(false); } public void delete(Instance instance){ instanceRepository.delete(instance); instances.remove(instance); } public void update(Instance instance){ setInstance(instance); setEditMode(true); } public void cancel(){ instance = new Instance(); setEditMode(false); } public InstanceRepository getInstanceRepository() { return instanceRepository; } public void setInstanceRepository(InstanceRepository instanceRepository) { this.instanceRepository = instanceRepository; } public Instance getInstance() { return instance; } public void setInstance(Instance instance) { this.instance = instance; } public List<Instance> getInstances() { return instances; } public void setInstances(List<Instance> instances) { this.instances = instances; } public boolean isEditMode() { return editMode; } public void setEditMode(boolean editMode) { this.editMode = editMode; } }
true
91eafdf66b591c11f593ec81097845134a931673
Java
guoyongsheng/Zf_mobile
/app/src/main/java/com/zfsoftmh/entity/CanteenInfo.java
UTF-8
1,212
1.882813
2
[]
no_license
package com.zfsoftmh.entity; /** * Created by li on 2017/8/3. */ public class CanteenInfo { String canteenName; String picPath; String lunchBox; String fullDiscount; String description; String isactive; public String getCanteenName() { return canteenName; } public void setCanteenName(String canteenName) { this.canteenName = canteenName; } public String getPicPath() { return picPath; } public void setPicPath(String picPath) { this.picPath = picPath; } public String getLunchBox() { return lunchBox; } public void setLunchBox(String lunchBox) { this.lunchBox = lunchBox; } public String getFullDiscount() { return fullDiscount; } public void setFullDiscount(String fullDiscount) { this.fullDiscount = fullDiscount; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIsactive() { return isactive; } public void setIsactive(String isactive) { this.isactive = isactive; } }
true
ff406e12b282e0fc6a9b71233f1651e00741b526
Java
Markmeimei/ZhiXin
/app/src/main/java/com/example/zhi/fragment/Fragment_Manage.java
UTF-8
2,141
1.914063
2
[]
no_license
package com.example.zhi.fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import com.example.zhi.R; import com.example.zhi.activity.manage.ProjectActivity; import com.lidroid.xutils.ViewUtils; import com.lidroid.xutils.view.annotation.ViewInject; /** * 管理 * * Author:Mark * Date:2015/11/24 0024 * Tell:15006330640 * */ public class Fragment_Manage extends Fragment implements View.OnClickListener { // 项目管理 @ViewInject(R.id.re_project) RelativeLayout re_project; // 询价资产 @ViewInject(R.id.rv_inquiry) RelativeLayout rv_inquiry; // 考勤管理 @ViewInject(R.id.re_attendance) RelativeLayout re_attendance; // 车油管理 @ViewInject(R.id.re_oil) RelativeLayout re_oil; // 客户管理 @ViewInject(R.id.re_clientele) RelativeLayout re_clientele; // 进销存 @ViewInject(R.id.re_stock) RelativeLayout re_stock; // 对象 private Context context; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_manage,container,false); ViewUtils.inject(this,view); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initConstants(); initViews(); initEvents(); } private void initConstants() { context = getActivity(); } private void initViews() { re_project.setOnClickListener(this); } private void initEvents() { } @Override public void onClick(View v) { switch (v.getId()){ case R.id.re_project: startActivity(new Intent(context, ProjectActivity.class)); break; } } }
true
9a5e1ca6f4e4e7b20a93278e564113ac9b3c3509
Java
1742087/Android
/MusicForLife/app/src/main/java/com/example/musicforlife/SongModel.java
UTF-8
5,406
2.484375
2
[]
no_license
package com.example.musicforlife; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.provider.MediaStore; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.ArrayList; public class SongModel { private String path; private String title; private String album; private String artist; private Bitmap bitmap; private String duration; public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAlbum() { return album; } public void setAlbum(String album) { this.album = album; } public String getArtist() { return artist; } public void setArtist(String artist) { this.artist = artist; } public Bitmap getBitmap() { return bitmap; } public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; } public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public static ArrayList<SongModel> getAllAudioFromDevice(final Context context) { final ArrayList<SongModel> tempAudioList = new ArrayList<>(); Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; String[] projection = {MediaStore.Audio.AudioColumns.DATA, MediaStore.Audio.AudioColumns.TITLE, MediaStore.Audio.AudioColumns.ALBUM, MediaStore.Audio.ArtistColumns.ARTIST, MediaStore.Audio.AudioColumns.DURATION }; String sortOrder = MediaStore.Audio.Media.TITLE + " ASC"; String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0 "; Cursor c = context.getContentResolver().query(uri, projection, selection, null, sortOrder); int debugLoop = 40; if (c != null) { int count = 0; while (c.moveToNext() ) {// && count++<debugLoop count++; // Log.d(TAG, "getAllAudioFromDevice: " + count); SongModel songModel = new SongModel(); String path = c.getString(0);//c.getColumnIndex(MediaStore.Audio.AudioColumns.DATA) String name = c.getString(1);//c.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE) String album = c.getString(2);//c.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM) String artist = c.getString(3);//c.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST) String duration = c.getString(4);//c.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION) MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); mediaMetadataRetriever.setDataSource(path); InputStream inputStream; Bitmap bitmap; if (mediaMetadataRetriever.getEmbeddedPicture() != null) { inputStream = new ByteArrayInputStream(mediaMetadataRetriever.getEmbeddedPicture()); mediaMetadataRetriever.release(); bitmap = BitmapFactory.decodeStream(inputStream); } else { bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.musical_note_light_64); } songModel.setTitle(name); songModel.setAlbum(album); songModel.setArtist(artist); songModel.setPath(path); songModel.setBitmap(bitmap); songModel.setDuration(formateMilliSeccond(Long.valueOf(duration))); // Log.e("Name :" + name, " Album :" + album); // Log.e("Path :" + path, " Artist :" + artist); tempAudioList.add(songModel); } c.close(); } return tempAudioList; } private static String formateMilliSeccond(long milliseconds) { String finalTimerString = ""; String secondsString = ""; // Convert total duration into time int hours = (int) (milliseconds / (1000 * 60 * 60)); int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60); int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000); // Add hours if there if (hours > 0) { finalTimerString = hours + ":"; } // Prepending 0 to seconds if it is one digit if (seconds < 10) { secondsString = "0" + seconds; } else { secondsString = "" + seconds; } finalTimerString = finalTimerString + minutes + ":" + secondsString; // return String.format("%02d Min, %02d Sec", // TimeUnit.MILLISECONDS.toMinutes(milliseconds), // TimeUnit.MILLISECONDS.toSeconds(milliseconds) - // TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(milliseconds))); // return timer string return finalTimerString; } }
true
d98da441fe1e901e83c857e6294588b38a14cb4e
Java
naseermohammed23/DSLearning
/src/Trees/LeastCommonAcncestor.java
UTF-8
1,268
3.328125
3
[]
no_license
package trees; import trees.util.Node; import trees.util.TreeUtil; /** * Tawheed TIPS Summer 2021 * Aug, 14, 2021 - Assignment * * Least Common Ancestor (LCA) * https://classroom.google.com/c/MzcwMjU4Mzg4ODE0/a/Mzc1Njc3MjQ0Mjg1/details * * @author Naseer Mohammed Abdul */ public class LeastCommonAcncestor { /** Binary Tree. 1 / \ 2 3 / \ / \ 4 5 6 7 \ 8 **/ static Node getBinaryTree() { Node root = new Node(1); Node node1 = new Node(2); Node node2 = new Node(3); Node node3 = new Node(4); Node node4 = new Node(5); Node node5 = new Node(6); Node node6 = new Node(7); Node node7 = new Node(8); root.left = node1; root.right = node2; node1.left = node3; node1.right = node4; node2.left = node5; node2.right = node6; node5.right = node7; return root; } public static void main(String[] args) { System.out.println("Least Common Ancestor is :" + TreeUtil.findLeastCommonAncestor(getBinaryTree(), 6, 7)); } }
true
e975f5c91b814957cf7cf66db2827e117aef25b4
Java
Ayomilotunde/Toolbar_Practice
/app/src/main/java/com/ayomi/toolbarpractice/DataBaseHelper.java
UTF-8
2,646
2.5
2
[]
no_license
package com.ayomi.toolbarpractice; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.widget.EditText; import androidx.annotation.Nullable; public class DataBaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "people.db"; public static final String TABLE_NAME = "people_table"; public static final String COL1 = "ID"; public static final String COL2 = "NAME"; public static final String COL3 = "EMAIL"; public static final String COL4 = "DATE"; //public static final String COL5 = "USERNAME"; public DataBaseHelper(@Nullable Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " + " NAME TEXT, EMAIL TEXT, DATE NUMBER, USERNAME TEXT)"; db.execSQL(createTable); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(TABLE_NAME); onCreate(db); } public boolean addData(String name, String email, String date, EditText username) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL2,name); contentValues.put(COL3,email); contentValues.put(COL4,date); //contentValues.put(COL5,username); long result = db.insert(TABLE_NAME, null, contentValues); if (result == -1) { return false; }else{ return true; } } //To show data public Cursor showData() { SQLiteDatabase db = this.getWritableDatabase(); Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null); return data; } //for update of data public boolean updateData(String id, String name, String email, String date) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL1,id); contentValues.put(COL2,name); contentValues.put(COL3,email); contentValues.put(COL4,date); db.update(TABLE_NAME, contentValues, "ID = ?", new String[] {id}); return true; } public Integer deleteData(String id){ SQLiteDatabase db = this.getWritableDatabase(); return db.delete(TABLE_NAME, "ID = ?", new String[] {id}); } }
true
f030775cce53d64d17d375dc301c0f27e6bce897
Java
magic-coder/DaggerAndroid
/app/src/main/java/me/xiaobailong24/daggerandroid/di/component/MainActivitySubcomponent.java
UTF-8
723
1.953125
2
[]
no_license
package me.xiaobailong24.daggerandroid.di.component; import dagger.Subcomponent; import dagger.android.AndroidInjector; import me.xiaobailong24.daggerandroid.MainActivity; import me.xiaobailong24.daggerandroid.di.module.KobeModule; import me.xiaobailong24.daggerlibrary.di.scope.ActivityScope; /** * Created by xiaobailong24 on 2017/9/6. * Dagger.Android Subcomponent * * @see <a href="https://google.github.io/dagger/android.html">Dagger & Android</a> */ @ActivityScope @Subcomponent(modules = KobeModule.class)//DataModule public interface MainActivitySubcomponent extends AndroidInjector<MainActivity> { @Subcomponent.Builder abstract class Builder extends AndroidInjector.Builder<MainActivity> { } }
true
d74195bff25c37cfb16e2a79a43213218edeb7f8
Java
ryanrussell10/CSC-115-Programs
/StackNode.java
UTF-8
654
3.6875
4
[]
no_license
/* * StackNode.java * * A plain-jane node for a ref-based Stack, assuming that the stack * meant to contains nodes storing values of type T. * * UVic CSC 115, Spring 2017 */ class StackNode<T> { T data; StackNode<T> next; public StackNode(T data) { this.data = data; this.next = null; } public T getValue() { return this.data; } public StackNode<T> getNext() { return this.next; } public void setNext(StackNode<T> next) { this.next = next; } public String toString() { return data.toString(); } }
true
fe330c623fdc1b81cf732cfbcf0a161407b10798
Java
han-gyeol/Tdoo
/src/test/java/seedu/Tdoo/testutil/DeadlineListBuilder.java
UTF-8
707
2.875
3
[ "MIT" ]
permissive
package seedu.Tdoo.testutil; import seedu.Tdoo.model.TaskList; import seedu.Tdoo.model.task.Task; import seedu.Tdoo.model.task.UniqueTaskList; /** * A utility class to help with building TodoList objects. Example usage: <br> * {@code TodoList ab = new DeadlineListBuilder().withTask("Assignment 1").build();} */ // @@author A0132157M reused public class DeadlineListBuilder { private TaskList DeadlineList; public DeadlineListBuilder(TaskList DeadlineList) { this.DeadlineList = DeadlineList; } public DeadlineListBuilder withTask(Task task) throws UniqueTaskList.DuplicatetaskException { DeadlineList.addTask(task); return this; } public TaskList build() { return DeadlineList; } }
true
fab31f0eedb1a91cac50f2854385c72c362f461f
Java
saketrule/Research_Project-HackerRank_CheckStyle
/Greedy/sherlock-and-minimax/java/rakshit_tanti.java
UTF-8
1,636
3.328125
3
[]
no_license
import java.util.*; class Solution { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } Arrays.sort(arr); int p = sc.nextInt(); int q = sc.nextInt(); int m = 0; int maxMinDistance = 0; if(p < arr[0]) { int temp = Math.abs(p - arr[0]); if(temp > maxMinDistance) { maxMinDistance = temp; m = p; } } if(q > arr[n - 1]) { int temp = Math.abs(q - arr[n - 1]); if(temp > maxMinDistance) { maxMinDistance = temp; m = q; } } int i = 0; while(arr[i] < p) { i++; } i = i == 0 ? 1 : i; while(i < n) { int temp_m = arr[i] + arr[i - 1]; temp_m = temp_m / 2; if(temp_m <= q){ int distance = Math.abs(arr[i - 1] - temp_m); if(distance > maxMinDistance) { maxMinDistance = distance; m = temp_m; } i++; } else if(temp_m > q) { int distance = Math.abs(arr[i - 1] - q); if(distance > maxMinDistance) { maxMinDistance = distance; m = q; } break; } } System.out.println(m); } }
true
99370e952e5bbd1481d7557ca32b3fa9e961fbfe
Java
sarunassp/deleteLater2
/src/main/java/lt/vu/rest/StudentRestService.java
UTF-8
1,409
2.5
2
[]
no_license
package lt.vu.rest; import lt.vu.asynchronous.CompA; import lt.vu.entities.Student; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.transaction.Transactional; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; @ApplicationScoped @Path("/student") @Produces(MediaType.APPLICATION_JSON) public class StudentRestService { @Inject private EntityManager em; @GET @Path("/{studentId}") public Student find(@PathParam("studentId") Integer studentId) { return em.find(Student.class, studentId); } @POST @Consumes(MediaType.APPLICATION_JSON) @Transactional public Student create(Student student) { student.setId(null); em.persist(student); return student; } @PUT @Transactional @Consumes(MediaType.APPLICATION_JSON) public Student modify(Student student) { Student oldStudent = em.getReference(Student.class, student.getId()); if (oldStudent == null) { throw new IllegalArgumentException("user id " + student.getId() + " not found"); } if (student.getFirstName() != null) oldStudent.setFirstName(student.getFirstName()); if (student.getLastName() != null) oldStudent.setLastName(student.getLastName()); return student; } }
true
0574d1509f49b75e4cbe7cc336a7105d972bb84e
Java
zdx/recommendation-algorithms
/RSVD.java
GB18030
9,777
2.421875
2
[]
no_license
package com.fangqiang.myutils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Random; public class RSVD { private static String SPLIT="\t"; private static String TrainDataFile="F:\\Recommendation\\coding\\My\\recordWithRate2_itemMaped_train"; private static String TestDataFile="F:\\Recommendation\\coding\\My\\recordWithRate2_itemMaped_test"; private static String lofFile="F:\\Recommendation\\coding\\My\\RSVDlog.txt"; private static int ratingNum=89280; private static int trainNum=62496; private static int userNum = 9861; // 943; private static int itemNum = 12606; // 1682; public static int[] factorNums; private static int loopNum = 500; List<String> modelTrain; List<String> modelTest; // the user-factor martix private static double[][] u; // the item-factor martix private static double[][] v; // private static double regularization; private static double learnRate1; private static double learnRate2; private static double[] regularization; // ÿѵʱMAE private static double[] trainMAEArray = new double[loopNum]; private static double[] trainRMSEArray = new double[loopNum]; // ÿβԼʱMAE private static double[] testMAEArray = new double[loopNum]; private static double[] testRMSEArray = new double[loopNum]; private static HashMap<Integer, Integer> itemIdMap; static { factorNums = new int[] { 50 }; regularization = new double[] {0.03}; } public static void main(String[] args) { // System.out.println(); Long time1=System.currentTimeMillis(); /*Data data=new Data(); itemIdMap=data.mapItemId(moviesOriginFile, movieMapFile15);*/ // data.divideTrainTest(ratingNum, trainNum, originFile, TrainDataFile, TestDataFile); // System.out.println("ϣ"); RSVD rsvd = new RSVD(); learnRate1 = 0.005; learnRate2 = 0.005; for (int i = 0; i < factorNums.length; i++) { for (int j = 0; j < regularization.length; j++) { rsvd.myRSVD(factorNums[i],regularization[j], regularization[j], learnRate1, learnRate2); } } Long time2=System.currentTimeMillis(); System.out.println("time:"+((time2-time1)/1000)+"s"); } public void inital(int factorNum) { Random r = new Random(); u = new double[userNum][factorNum]; for (int i = 0; i < userNum; i++) { for (int j = 0; j < factorNum; j++) { u[i][j] = r.nextDouble() * 0.001; } } v = new double[itemNum][factorNum]; for (int i = 0; i < itemNum; i++) { for (int j = 0; j < factorNum; j++) { v[i][j] = r.nextDouble() * 0.001; } } modelTrain = readData(TrainDataFile); modelTest = readData(TestDataFile); System.out.println("inital"); } public void myRSVD(int factorNum, double regularization1, double regularization2, double learnRate1, double learnRate2) { inital(factorNum); for (int k = 0; k < loopNum; k++) { for (String s : modelTrain) { String[] str = s.split(SPLIT); int userId = Integer.parseInt(str[0]); int itemId = Integer.parseInt(str[1]); // int itemMapId=itemIdMap.get(itemId); double rate = Double.parseDouble(str[2]); HashMap<String, String> map; double preRate = getDotProduct(u[userId - 1], v[itemId-1], factorNum); double e = rate - preRate; double[] oldU = Arrays.copyOf(u[userId - 1], factorNum); double[] temp1 = VectorAddVector( u[userId - 1], NumMulVector( learnRate1, VectorMinusVector( NumMulVector(e, v[itemId-1], factorNum), NumMulVector(regularization1, u[userId - 1], factorNum), factorNum), factorNum), factorNum); System.arraycopy(temp1, 0, u[userId - 1], 0, factorNum); double[] temp2 = VectorAddVector( v[itemId-1], NumMulVector( learnRate2, VectorMinusVector( NumMulVector(e, oldU, factorNum), NumMulVector(regularization2, v[itemId-1], factorNum), factorNum), factorNum), factorNum); System.arraycopy(temp2, 0, v[itemId-1], 0, factorNum); } // ÿεMAERMSE double MAE = 0.0; double RMSE = 0.0; int count = 0; for (String s : modelTrain) { String[] str = s.split(SPLIT); int userId = Integer.parseInt(str[0]); int itemId = Integer.parseInt(str[1])-1; double rate = Double.parseDouble(str[2]); // int itemMapId=itemIdMap.get(itemId-1); double prerate = getDotProduct(u[userId - 1], v[itemId], factorNum); MAE += Math.abs(rate - prerate); RMSE += Math.pow(rate - prerate, 2); count++; } MAE = MAE / count; RMSE = Math.sqrt(RMSE / count); trainMAEArray[k] = MAE; trainRMSEArray[k] = RMSE; predict(k, factorNum); } save(lofFile, factorNum, regularization1, regularization2); modelTrain = null; modelTest=null; } // бMAERMSEд뵽ļ public void save(String fileName, int factorNum, double regularization1, double regularization2) { BufferedWriter bw = null; try { bw = new BufferedWriter(new FileWriter(fileName, true)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { for (int i = 0; i < loopNum; i++) { String dMAE = Double.toString(trainMAEArray[i]); String dRMSE = Double.toString(trainRMSEArray[i]); bw.write(dMAE+","+dRMSE+","+regularization1+","+factorNum+"TRAIN"); bw.newLine(); } for (int i = 0; i < loopNum; i++) { String dMAE = Double.toString(testMAEArray[i]); String dRMSE = Double.toString(testRMSEArray[i]); bw.write(dMAE+","+dRMSE+","+regularization1+","+factorNum+"TEST"); bw.newLine(); } } catch (IOException e) { e.printStackTrace(); } finally { try { bw.flush(); bw.close(); } catch (IOException e) { e.printStackTrace(); } } } // Լϲ MAERMSE public void predict(int k, int factorNum) { double MAE = 0.0; double RMSE = 0.0; int count = 0; for (String s : modelTest) { String[] str = s.split(SPLIT); int userId = Integer.parseInt(str[0]); int itemId = Integer.parseInt(str[1])-1; double rate = Double.parseDouble(str[2]); // int itemMapId=itemIdMap.get(itemId); double prerate = getDotProduct(u[userId - 1], v[itemId], factorNum); MAE += Math.abs(rate - prerate); RMSE += Math.pow(rate - prerate, 2); count++; } MAE = MAE / count; RMSE = Math.sqrt(RMSE / count); testMAEArray[k] = MAE; testRMSEArray[k] = RMSE; } // //add two vector public double[] VectorAddVector(double[] a, double[] b, int factorNum) { double c[] = new double[factorNum]; for (int i = 0; i < factorNum; i++) { c[i] = a[i] + b[i]; } return c; } // //subtract two vectors public double[] VectorMinusVector(double[] a, double[] b, int factorNum) { double c[] = new double[factorNum]; for (int i = 0; i < factorNum; i++) { c[i] = a[i] - b[i]; } return c; } // //make a multiplication between a number and a vector public double[] NumMulVector(double a, double[] b, int factorNum) { double c[] = new double[factorNum]; for (int i = 0; i < factorNum; i++) { c[i] = b[i] * a; } return c; } // private static double getDotProduct(double[] p, double[] q, int factorNum) { double sum = 0; for (int i = 0; i < factorNum; i++) { sum += p[i] * q[i]; } return sum; } public void initial(int factorNum) { Random r = new Random(); u = new double[userNum][factorNum]; for (int i = 0; i < userNum; i++) { for (int j = 0; j < factorNum; j++) { u[i][j] = r.nextDouble() * 0.001; } } v = new double[itemNum][factorNum]; for (int i = 0; i < itemNum; i++) { for (int j = 0; j < factorNum; j++) { v[i][j] = r.nextDouble() * 0.001; } } } // read the training Data file public List<String> readData(String fileName) { File fileIn = new File(fileName); BufferedReader br = null; try { br = new BufferedReader(new FileReader(fileIn)); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } String s; String[] str; int userId; int itemId; double rate; int counter = 0; List<String> model = new LinkedList<>(); try { while ((s = br.readLine()) != null) { str = s.split(SPLIT); userId = Integer.parseInt(str[0]); itemId = Integer.parseInt(str[1]); rate = Double.parseDouble(str[2]); counter++; model.add(s); } } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * userNum=userIds.size(); itemNum=itemIds.size(); userIds=null; * itemIds=null; */ System.out.println("ϣ" + model.size() + ""); System.out.println("counter="+counter); return model; } }
true
a509ef43f32602b5e138e9cdc34f5c7ed7103f56
Java
rockmeamadeus/cc
/callCenter/src/main/java/examen/callCenter/Director.java
UTF-8
154
1.921875
2
[]
no_license
package examen.callCenter; public class Director extends Empleado { public Director() { priority = 3; queue.add(priority); } }
true
3c3e8455a04c8503056205f9f87fd6622252ef55
Java
habeeb17/MasterKey
/src/main/java/com/makinus/masterkey/ChangeMasterPwdActivity.java
UTF-8
2,702
2.46875
2
[]
no_license
package com.makinus.masterkey; import com.makinus.masterkey.R; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class ChangeMasterPwdActivity extends BaseActivity{ final Context context = this; private Button btnConfirm; private EditText txtOldKey; private EditText txtNewKey; private EditText txtConfirmKey; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_change_masterkey); txtOldKey = (EditText)findViewById(R.id.eTxtOldPwd); txtNewKey = (EditText)findViewById(R.id.eTxtNewPwd); txtConfirmKey = (EditText)findViewById(R.id.eTxtConfirmPwd); btnConfirm = (Button)findViewById(R.id.btnConfirm); btnConfirm.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { String masterKeyDigest = dbService.getMasterKey(); if(checkValidation(masterKeyDigest)) { dbService.updateMasterKey(masterKeyDigest, mKeyUtil.digest(txtNewKey.getText().toString())); Intent i = new Intent(); i.putExtra("result","Master key updated successfully!"); setResult(Activity.RESULT_OK, i); finish(); } } }); } private boolean checkValidation(String masterKeyDigest) { if(txtOldKey.getText().toString().trim().isEmpty()) { Toast.makeText(context, "Current Master key is required.", Toast.LENGTH_SHORT).show(); return false; } if(txtNewKey.getText().toString().trim().isEmpty()) { Toast.makeText(context, "New Master key is required.", Toast.LENGTH_SHORT).show(); return false; } if(txtConfirmKey.getText().toString().trim().isEmpty()) { Toast.makeText(context, "Confirm Master key is required.", Toast.LENGTH_SHORT).show(); return false; } if(!txtNewKey.getText().toString().trim().equals(txtConfirmKey.getText().toString().trim())) { Toast.makeText(context, "New and Confirm Master key must be same.", Toast.LENGTH_SHORT).show(); return false; } if(!mKeyUtil.matches(txtOldKey.getText().toString().trim(), masterKeyDigest)) { Toast.makeText(context, "Invalid Master key. Try Again!", Toast.LENGTH_SHORT).show(); return false; } if(mKeyUtil.matches(txtNewKey.getText().toString().trim(), masterKeyDigest)) { Toast.makeText(context, "New Master key must not be same as old Master key.!", Toast.LENGTH_SHORT).show(); return false; } return true; } }
true
add1a6365c63db231973dd9a1407ce3466c49cda
Java
t0HiiBwn/CoolapkRelease
/sources/com/amap/api/mapcore2d/dl.java
UTF-8
670
1.71875
2
[]
no_license
package com.amap.api.mapcore2d; import android.content.Context; import java.lang.Thread; /* compiled from: BasicLogHandler */ public class dl { protected static dl a; protected Thread.UncaughtExceptionHandler b; protected boolean c = true; protected void a() { } protected void a(Context context, da daVar, boolean z) { } protected void a(da daVar, String str, String str2) { } protected void a(Throwable th, int i, String str, String str2) { } public static void a(Throwable th, String str, String str2) { dl dlVar = a; if (dlVar != null) { dlVar.a(th, 1, str, str2); } } }
true
06fe2144a462aacf028f9bc6d2cf7c332e1801f6
Java
WorldInEye/psp
/psp-web/src/main/java/com/psp/web/persist/impl/ServiceImpl.java
UTF-8
1,428
2.046875
2
[]
no_license
package com.psp.web.persist.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Repository; import com.psp.web.model.CategoryBean; import com.psp.web.persist.dao.ServiceDao; @Repository public class ServiceImpl extends BaseImpl implements ServiceDao { final String NAME_SPACE = NAME_SPACE_HEADER + ".ServiceMapper"; @Override public List<CategoryBean> selectAllCates() { return sqlSessionTemplate.selectList(NAME_SPACE + ".selectAllCates"); } @Override public List<CategoryBean> selectService(String parentId) { return sqlSessionTemplate.selectList(NAME_SPACE + ".selectService", parentId); } @Override public int selectServiceCountByPid(int parentId) { Map<String, Object> params = new HashMap<String, Object>(); params.put("parentId", parentId); return sqlSessionTemplate.selectOne(NAME_SPACE + ".selectServiceCountByPid", params); } @Override public List<CategoryBean> selectServiceByPid(int parentId) { Map<String, Object> params = new HashMap<String, Object>(); params.put("parentId", parentId); return sqlSessionTemplate.selectList(NAME_SPACE + ".selectServiceByPid", params); } @Override public CategoryBean selectServiceById(int cid) { Map<String, Object> params = new HashMap<String, Object>(); params.put("cid", cid); return sqlSessionTemplate.selectOne(NAME_SPACE + ".selectServiceById", params); } }
true
c0e3b046381d4c515826801f2331c5812e18649b
Java
JSansalone/GZMigration
/src/br/com/gz/migration/IDatabaseInfo.java
ISO-8859-1
572
2.09375
2
[]
no_license
package br.com.gz.migration; import org.database.connection.DatabaseConfigurations; import br.com.gz.util.GZSoftwares; /** * Interface que fornece informaes sobre bancos de dados e o software utilizado * * @author Jonathan Sansalone * */ public interface IDatabaseInfo { /** * Mtodo que retorna as configuraes do banco de dados * * @return - As configuraes do banco de dados */ DatabaseConfigurations getDatabaseInfo(); /** * Mtodo que retorna o software utilizado * * @return - O software utilizado */ GZSoftwares getSoftware(); }
true
a52c40968dafd0927bc6f645627607fbc0564e96
Java
yingCMU/Flight-Delay-Service
/app/models/YelpBiz.java
UTF-8
1,820
2.6875
3
[]
no_license
package models; public class YelpBiz { protected double distance; protected double rating; protected String rating_img_url; protected String image_url; protected String name; protected String categories; protected String category; protected String display_phone; protected GeoLocation geoLocation; protected String address; public YelpBiz(String name, String category, double latitude, double longitude, String address, String city, String zipcode) { this.address = address; this.name = name; this.category = category; this.geoLocation = new GeoLocation(address, city, zipcode, longitude, latitude); } public String getCategory(){ return this.category; } public String getImage_url(){ return this.image_url; } public String getAddress(){ return this.address; } public String getCategories(){ return this.categories; } public String getRating_img_url(){ return this.rating_img_url; } public String getName() { return this.name; } public String getPhone(){ return this.display_phone; } public GeoLocation getGeoLocation() { return this.geoLocation; } public double getRating() { return this.rating; } public double getDistance() { return this.distance; } public void setDistance(double distance) { this.distance = distance; } public void setCategories(String categories){ this.categories = categories; } public void setRating(double rating) { this.rating = rating; } public void setPhone(String phone){ this.display_phone = phone; } public void setRating_img_url(String url){ this.rating_img_url = url; } public void setImage_url(String url){ this.image_url = url; } public void setAddress( String addr){ this.address = addr; } public String toString(){ return "name: "+name+"cat:"+category+" distance:"+distance; } }
true
ff77d4e524a8549c8eae373be0622d0456cb3893
Java
treejames/workspace_e
/sea/src/model/com/nari/qrystat/colldataanalyse/LineEceltricQuantityDto.java
UTF-8
6,134
2.265625
2
[]
no_license
package com.nari.qrystat.colldataanalyse; import java.util.Date; /** * * 线路电量查询DTO * @author ChunMingLi * @since 2010-6-23 * */ public class LineEceltricQuantityDto { //供电单位编号 private String orgNo; //供电单位 private String orgName; //线路ID private String lineId; //线路名称 private String lineName; //开始时间 private Date statDate; //正向有功总电能量 private int pap_e; //正向有功费率1电能量 private int pap_e1; //正向有功费率2电能量 private int pap_e2; //正向有功费率3电能量 private int pap_e3; //正向有功费率4电能量 private int pap_e4; //最大有功功率 private int max_p; //最大有功功率发生时间 private Date max_p_time; //最小有功功率 private int min_p; //最小有功功率发生时间 private Date min_p_time; //最大无功功率发生时间 private int max_q; //最大无功功率发生时间 private Date max_q_time; //最小无功功率发生时间 private int min_q; //最小无功功率发生时间 private Date min_q_time; //平均无功功率 private int avg_q; //平均有功功率 private int avg_p; /** * the avg_q * @return the avg_q */ public int getAvg_q() { return avg_q; } /** * the avg_q to set * @param avgQ the avg_q to set */ public void setAvg_q(int avgQ) { avg_q = avgQ; } /** * the avg_p * @return the avg_p */ public int getAvg_p() { return avg_p; } /** * the avg_p to set * @param avgP the avg_p to set */ public void setAvg_p(int avgP) { avg_p = avgP; } /** * the orgNo * @return the orgNo */ public String getOrgNo() { return orgNo; } /** * the orgNo to set * @param orgNo the orgNo to set */ public void setOrgNo(String orgNo) { this.orgNo = orgNo; } /** * the orgName * @return the orgName */ public String getOrgName() { return orgName; } /** * the orgName to set * @param orgName the orgName to set */ public void setOrgName(String orgName) { this.orgName = orgName; } /** * the lineId * @return the lineId */ public String getLineId() { return lineId; } /** * the lineId to set * @param lineId the lineId to set */ public void setLineId(String lineId) { this.lineId = lineId; } /** * the lineName * @return the lineName */ public String getLineName() { return lineName; } /** * the lineName to set * @param lineName the lineName to set */ public void setLineName(String lineName) { this.lineName = lineName; } /** * the statDate * @return the statDate */ public Date getStatDate() { return statDate; } /** * the statDate to set * @param statDate the statDate to set */ public void setStatDate(Date statDate) { this.statDate = statDate; } /** * the pap_e * @return the pap_e */ public int getPap_e() { return pap_e; } /** * the pap_e to set * @param papE the pap_e to set */ public void setPap_e(int papE) { pap_e = papE; } /** * the pap_e1 * @return the pap_e1 */ public int getPap_e1() { return pap_e1; } /** * the pap_e1 to set * @param papE1 the pap_e1 to set */ public void setPap_e1(int papE1) { pap_e1 = papE1; } /** * the pap_e2 * @return the pap_e2 */ public int getPap_e2() { return pap_e2; } /** * the pap_e2 to set * @param papE2 the pap_e2 to set */ public void setPap_e2(int papE2) { pap_e2 = papE2; } /** * the pap_e3 * @return the pap_e3 */ public int getPap_e3() { return pap_e3; } /** * the pap_e3 to set * @param papE3 the pap_e3 to set */ public void setPap_e3(int papE3) { pap_e3 = papE3; } /** * the pap_e4 * @return the pap_e4 */ public int getPap_e4() { return pap_e4; } /** * the pap_e4 to set * @param papE4 the pap_e4 to set */ public void setPap_e4(int papE4) { pap_e4 = papE4; } /** * the max_p * @return the max_p */ public int getMax_p() { return max_p; } /** * the max_p to set * @param maxP the max_p to set */ public void setMax_p(int maxP) { max_p = maxP; } /** * the max_p_time * @return the max_p_time */ public Date getMax_p_time() { return max_p_time; } /** * the max_p_time to set * @param maxPTime the max_p_time to set */ public void setMax_p_time(Date maxPTime) { max_p_time = maxPTime; } /** * the min_p * @return the min_p */ public int getMin_p() { return min_p; } /** * the min_p to set * @param minP the min_p to set */ public void setMin_p(int minP) { min_p = minP; } /** * the min_p_time * @return the min_p_time */ public Date getMin_p_time() { return min_p_time; } /** * the min_p_time to set * @param minPTime the min_p_time to set */ public void setMin_p_time(Date minPTime) { min_p_time = minPTime; } /** * the max_q * @return the max_q */ public int getMax_q() { return max_q; } /** * the max_q to set * @param maxQ the max_q to set */ public void setMax_q(int maxQ) { max_q = maxQ; } /** * the max_q_time * @return the max_q_time */ public Date getMax_q_time() { return max_q_time; } /** * the max_q_time to set * @param maxQTime the max_q_time to set */ public void setMax_q_time(Date maxQTime) { max_q_time = maxQTime; } /** * the min_q * @return the min_q */ public int getMin_q() { return min_q; } /** * the min_q to set * @param minQ the min_q to set */ public void setMin_q(int minQ) { min_q = minQ; } /** * the min_q_time * @return the min_q_time */ public Date getMin_q_time() { return min_q_time; } /** * the min_q_time to set * @param minQTime the min_q_time to set */ public void setMin_q_time(Date minQTime) { min_q_time = minQTime; } }
true
150092ffc5e7486cad55042dadad90854f6b8339
Java
copperdale/CloudLadder
/CloudElevatorApp/app/src/main/java/com/studio/cloudelevator/task/Screenshot.java
UTF-8
5,544
2.140625
2
[]
no_license
package com.studio.cloudelevator.task; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.params.CoreConnectionPNames; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Rect; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.net.http.AndroidHttpClient; import android.os.AsyncTask; import android.studio.os.LogCat; import android.view.View; import com.studio.cloudelevator.MyApplication; import com.studio.cloudelevator.config.AppConfig; /** * 截屏 * * @author Administrator * */ public class Screenshot { private Activity mHoldingActivity; private BlurAsyncTask mBluringTask; private boolean sending; public Screenshot(Activity holdingActivity) { mHoldingActivity = holdingActivity; } public void startScreenshot(String currMedia, int currentPosition) { if (sending) { return; } cancel(); sending = true; mBluringTask = new BlurAsyncTask(currMedia, currentPosition); mBluringTask.execute(); } /** * 取消截屏 */ public void cancel() { sending = false; if (mBluringTask != null) { mBluringTask.cancel(true); mBluringTask = null; } } /** * Async task used to process blur out of ui thread */ public class BlurAsyncTask extends AsyncTask<Void, Void, Void> { private Bitmap mBackground; private View mBackgroundView; String currMedia; int currentPosition; public BlurAsyncTask(String currMedia, int currentPosition) { this.currMedia = currMedia; this.currentPosition = currentPosition; } @Override protected void onPreExecute() { super.onPreExecute(); LogCat.i("Screenshot ing..."); mBackgroundView = mHoldingActivity.getWindow().getDecorView(); Rect rect = new Rect(); mBackgroundView.getWindowVisibleDisplayFrame(rect); mBackgroundView.destroyDrawingCache(); mBackgroundView.setDrawingCacheEnabled(true); mBackgroundView.buildDrawingCache(true); mBackground = mBackgroundView.getDrawingCache(true); if (mBackground == null) { mBackgroundView.measure(View.MeasureSpec.makeMeasureSpec(rect.width(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(rect.height(), View.MeasureSpec.EXACTLY)); mBackgroundView.layout(0, 0, mBackgroundView.getMeasuredWidth(), mBackgroundView.getMeasuredHeight()); mBackgroundView.destroyDrawingCache(); mBackgroundView.setDrawingCacheEnabled(true); mBackgroundView.buildDrawingCache(true); mBackground = mBackgroundView.getDrawingCache(true); } } @Override protected Void doInBackground(Void... params) { Bitmap bitmap = null; int bitmapWidth = mBackground.getWidth() * 3 / 8; int bitmapHeight = mBackground.getHeight() * 3 / 8; if (currMedia != null) { MediaMetadataRetriever rev = new MediaMetadataRetriever(); rev.setDataSource(mHoldingActivity, Uri.parse(currMedia)); bitmap = rev.getFrameAtTime(currentPosition * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC); // bitmap = Bitmap.createScaledBitmap(bitmapVideo, bitmapWidth, // bitmapHeight, true); // bitmapVideo.recycle(); } if (bitmap == null) { bitmap = mBackground; } Bitmap tempBitmap = bitmap; bitmap = Bitmap.createScaledBitmap(tempBitmap, bitmapWidth, bitmapHeight, true); tempBitmap.recycle(); // clear memory // mBackground.recycle(); mBackgroundView.destroyDrawingCache(); mBackgroundView.setDrawingCacheEnabled(false); try { // ByteArrayOutputStream outStream = new // ByteArrayOutputStream(); File _tempFile = new File(MyApplication.mediaDir, "_temp.png"); OutputStream outStream = new FileOutputStream(_tempFile); bitmap.compress(Bitmap.CompressFormat.JPEG, 10, outStream); bitmap.recycle(); outStream.flush(); outStream.close(); sendRequestBitmap(_tempFile); } catch (Throwable e) { LogCat.e("%s", e.getMessage()); } return null; } private void sendRequestBitmap(File _tempFile) throws IOException { HttpPost request = new HttpPost(AppConfig.SCREENSHOT_POST); MultipartEntity entity = new MultipartEntity(); entity.addPart("clientId", new StringBody(AppConfig.getUuid())); entity.addPart("screenImage", new FileBody(_tempFile)); request.setEntity(entity); AndroidHttpClient httpClient = AndroidHttpClient.newInstance("WebAndroid"); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10 * 1000); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10 * 1000); executeHttp(request, httpClient); httpClient.close(); } private void executeHttp(HttpPost request, AndroidHttpClient httpClient) throws IOException { LogCat.i("sned ..."); int retry = 0; while (retry++ < 5) { try { HttpResponse response = httpClient.execute(request); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { LogCat.i("sned OK"); return; } } catch (Exception e) { LogCat.i("send retry: " + retry); } } } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); mBackgroundView = null; mBackground = null; sending = false; } } }
true
f0b3002bb506e60468ecc2d0851fbfee98562d2c
Java
MadMcFly/Some-LC
/Linked List/Demo234_Palindrome_Linked_List.java
UTF-8
1,059
3.484375
3
[]
no_license
import java.util.ArrayList; public class Demo234_Palindrome_Linked_List { public static void main(String[] args) { ListNode l1 = new ListNode(-129); ListNode l2 = new ListNode(-129); l1.next = l2; System.out.println(new Solution_234().isPalindrome(l1)); } } class Solution_234 { public boolean isPalindrome(ListNode head) { if(head == null) return true; boolean flag = true; ArrayList<Integer> list = new ArrayList<>(); while(head != null) { list.add(head.val); head = head.next; } // System.out.println(list); for(int i = 0; i < list.size() / 2; i++) { // System.out.println(list.get(i)); // System.out.println(list.get(list.size() - 1 - i)); // System.out.println(list.get(i).equals(list.get(list.size() - 1 - i))); if(!list.get(i).equals(list.get(list.size() - 1 - i))) flag = false; } return flag; } }
true
533798a3242d42775c219126d74038625d3dbc3c
Java
mklump/CS_OIT2005Degree_Accademic_Work
/CST 407 Java J2EE/examples/chapters/DeitelBookstore/OrderProductEJB.java
UTF-8
4,485
2.421875
2
[]
no_license
// OrderProductEJB.java // Entity EJB OrderProductEJB represents the mapping between // a Product and an Order, including the quantity of the // Product in the Order. package com.deitel.advjhtp1.bookstore.ejb; // Java core packages import java.rmi.RemoteException; // Java extension packages import javax.ejb.*; import javax.naming.*; import javax.rmi.PortableRemoteObject; // Deitel packages import com.deitel.advjhtp1.bookstore.model.*; public class OrderProductEJB implements EntityBean { private EntityContext entityContext; // container-managed fields public String ISBN; public Integer orderID; public int quantity; // get OrderProduct details as OrderProductModel public OrderProductModel getOrderProductModel() throws EJBException { OrderProductModel model = new OrderProductModel(); // get ProductModel for Product in this OrderProduct try { Context initialContext = new InitialContext(); // look up Product EJB Object object = initialContext.lookup( "java:comp/env/ejb/Product" ); // get ProductHome interface ProductHome productHome = ( ProductHome ) PortableRemoteObject.narrow( object, ProductHome.class ); // find Product using its ISBN Product product = productHome.findByPrimaryKey( ISBN ); // get ProductModel ProductModel productModel = product.getProductModel(); // set ProductModel in OrderProductModel model.setProductModel( productModel ); } // end try // handle exception when looking up Product EJB catch ( Exception exception ) { throw new EJBException( exception ); } // set orderID and quantity in OrderProductModel model.setOrderID( orderID ); model.setQuantity( quantity ); return model; } // end method getOrderProductModel // set OrderProduct details using OrderProductModel private void setOrderProductModel( OrderProductModel model ) { ISBN = model.getProductModel().getISBN(); orderID = model.getOrderID(); quantity = model.getQuantity(); } // create OrderProduct for given OrderProductModel public OrderProductPK ejbCreate( OrderProductModel model ) { setOrderProductModel( model ); return null; } // perform any necessary post-creation tasks public void ejbPostCreate( OrderProductModel model ) {} // set EntityContext public void setEntityContext( EntityContext context ) { entityContext = context; } // unset EntityContext public void unsetEntityContext() { entityContext = null; } // activate OrderProduct EJB instance public void ejbActivate() { OrderProductPK primaryKey = ( OrderProductPK ) entityContext.getPrimaryKey(); ISBN = primaryKey.getISBN(); orderID = primaryKey.getOrderID(); } // passivate OrderProduct EJB instance public void ejbPassivate() { ISBN = null; orderID = null; } // remove OrderProduct EJB instance public void ejbRemove() {} // store OrderProduct EJB data in database public void ejbStore() {} // load OrderProduct EJB data from database public void ejbLoad() {} } /*************************************************************** * (C) Copyright 2002 by Deitel & Associates, Inc. and * * Prentice Hall. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have * * used their best efforts in preparing the book. These * * efforts include the development, research, and testing of * * the theories and programs to determine their effectiveness. * * The authors and publisher make no warranty of any kind, * * expressed or implied, with regard to these programs or to * * the documentation contained in these books. The authors * * and publisher shall not be liable in any event for * * incidental or consequential damages in connection with, or * * arising out of, the furnishing, performance, or use of * * these programs. * ***************************************************************/
true
65612385ebb59dd399b76e634e841a29d5d540e3
Java
Jonhcs/projeto-jdbc-servlet-jsp
/src/servlet/CadastroUsuario.java
ISO-8859-2
8,924
2.15625
2
[]
no_license
package servlet; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.tomcat.util.codec.binary.Base64; import beans.BeanCursoJsp; import dao.DaoLogin; import dao.DaoUsuario; /** * Servlet implementation class CadastroUsuario */ @WebServlet("/CadastroUsuario") @MultipartConfig public class CadastroUsuario extends HttpServlet { private static final long serialVersionUID = 1L; private DaoUsuario daoUsuario = new DaoUsuario(); /** * @see HttpServlet#HttpServlet() */ public CadastroUsuario() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String acao = request.getParameter("acao"); String user = request.getParameter("user"); String tipo = request.getParameter("tipo"); if (acao == null) { RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp"); request.setAttribute("usuarios", daoUsuario.listarTodos()); view.forward(request, response); } else if (acao.equals("delete")) { daoUsuario.deletar(user); System.out.println("Ao delete ok!"); RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp"); request.setAttribute("usuarios", daoUsuario.listarTodos()); view.forward(request, response); } else if (acao.equals("editar")) { BeanCursoJsp beancursojsp = daoUsuario.consultar(user); RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp"); request.setAttribute("user", beancursojsp); view.forward(request, response); } else if (acao.equals("listarTodos")) { RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp"); request.setAttribute("usuarios", daoUsuario.listarTodos()); view.forward(request, response); } else if (acao.equals("download")) { BeanCursoJsp usuario = daoUsuario.consultar(user); if (usuario != null) { String contentType = ""; byte[] fileBytes = null; if (tipo.equals("imagem")) { contentType = usuario.getContentType(); fileBytes = new Base64().decodeBase64(usuario.getFotoBase64()); response.setHeader("Content-Disposition", "attachment; filename = arquivo." + contentType.split("\\/")[1]); } if (tipo.equals("pdf")) { contentType = usuario.getContentTypePdf(); fileBytes = new Base64().decodeBase64(usuario.getPdfBase64()); response.setHeader("Content-Disposition", "attachment; filename = pdf." + contentType.split("\\/")[1]); } InputStream is = new ByteArrayInputStream(fileBytes); int read = 0; byte[] bytes = new byte[1024]; OutputStream os = response.getOutputStream(); while ((read = is.read(bytes)) != -1) { os.write(bytes, 0, read); } os.flush(); os.close(); } RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp"); request.setAttribute("usuarios", daoUsuario.listarTodos()); view.forward(request, response); } } catch (Exception e) { e.printStackTrace(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BeanCursoJsp usuario = new BeanCursoJsp(); String acao = request.getParameter("acao"); boolean podeInserir = true; if (acao != null && acao.equalsIgnoreCase("resetar")) { try { RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp"); request.setAttribute("usuarios", daoUsuario.listarTodos()); view.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } else { String id = request.getParameter("id"); String nome = request.getParameter("nome"); String login = request.getParameter("login"); String senha = request.getParameter("senha"); String telefoneString = request.getParameter("telefone"); String cep = request.getParameter("cep"); String rua = request.getParameter("rua"); String bairro = request.getParameter("bairro"); String cidade = request.getParameter("cidade"); String uf = request.getParameter("uf"); String ibge = request.getParameter("ibge"); usuario.setId(!id.isEmpty() ? Long.parseLong(id) : null); usuario.setLogin(login); usuario.setPassword(senha); usuario.setNome(nome); usuario.setTelefone(!telefoneString.isEmpty() ? Long.parseLong(telefoneString) : null); usuario.setCep(cep); usuario.setRua(rua); usuario.setBairro(bairro); usuario.setCidade(cidade); usuario.setUf(uf); usuario.setIbge(ibge); List<String> msg = new ArrayList<String>(); try { if (ServletFileUpload.isMultipartContent(request)) { Part imagemFoto = request.getPart("foto"); if (imagemFoto != null) { String fotoBase64 = new Base64() .encodeBase64String(converteStremParaByte(imagemFoto.getInputStream())); usuario.setFotoBase64(fotoBase64); usuario.setContentType(imagemFoto.getContentType()); } /** * Processamento de pdf */ Part pdf = request.getPart("pdf"); if (pdf != null) { String pdf64 = new Base64().encodeBase64String(converteStremParaByte(pdf.getInputStream())); usuario.setPdfBase64(pdf64); usuario.setContentTypePdf(pdf.getContentType()); } } if (login == null || login.isEmpty()) { String msgLogin = "Campo obrigatrio: LOGIN"; msg.add(msgLogin); podeInserir = false; } else if (senha == null || senha.isEmpty()) { String msgSenha = "Campo obrigatrio: SENHA"; msg.add(msgSenha); podeInserir = false; } else if (telefoneString == null || telefoneString.isEmpty()) { String msgTelefone = "Campo obrigatrio: TELEFONE"; msg.add(msgTelefone); podeInserir = false; } else if (nome == null || nome.isEmpty()) { String msgNome = "Campo obrigatrio: NOME"; msg.add(msgNome); podeInserir = false; } else if (id == null || id.isEmpty() && !daoUsuario.validarLogin(login)) { String msgLogin = " Usurio j existe com o mesmo login. Cadastre outro login."; msg.add(msgLogin); podeInserir = false; } else if (id == null || id.isEmpty() && !daoUsuario.validarSenha(senha)) { String msgSenha = " Senha j existe para outro usurio."; msg.add(msgSenha); podeInserir = false; } if (msg != null && !podeInserir) { request.setAttribute("msg", msg); request.setAttribute("user", usuario); } else if (id == null || id.isEmpty() && daoUsuario.validarLogin(login) && podeInserir) { daoUsuario.salvar(usuario); String msgSalvo = "Salvo com sucesso"; msg.add(msgSalvo); podeInserir = true; System.out.println("Usuario salvo"); } else if (id != null && !id.isEmpty()) { if (!daoUsuario.validarLoginUpdate(login, id)) { String msgUpdate = " Login j existe em outra conta de usurio. Atualize outro login."; msg.add(msgUpdate); podeInserir = false; } else { daoUsuario.atualizar(usuario); System.out.println("Usuario Atualizado"); String msgAtualizado = "Atualizado com sucesso"; msg.add(msgAtualizado); podeInserir = true; } } if (msg != null && podeInserir) { request.setAttribute("msg", msg); } RequestDispatcher view = request.getRequestDispatcher("cadastroUsuario.jsp"); request.setAttribute("usuarios", daoUsuario.listarTodos()); request.setAttribute("podeInserir", podeInserir); view.forward(request, response); } catch (Exception e) { e.printStackTrace(); } } } /** * Converte para um array de Bytes * * @param imagem * @return * @throws IOException */ private byte[] converteStremParaByte(InputStream imagem) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); int reads = imagem.read(); while (reads != -1) { baos.write(reads); reads = imagem.read(); } return baos.toByteArray(); } }
true
536aea56c5190042533ea3cb03208c09c91af10e
Java
sirinath/Terracotta
/dso/branches/2.4.1/code/base/common/src/com/tc/bundles/RequiredBundleSpec.java
UTF-8
5,274
2.1875
2
[]
no_license
/* * All content copyright (c) 2003-2007 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved. */ package com.tc.bundles; import org.osgi.framework.BundleException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; final class RequiredBundleSpec { private static final String PROP_KEY_RESOLUTION = "resolution"; private static final String PROP_KEY_BUNDLE_VERSION = "bundle-version"; private static final String REQUIRE_BUNDLE_EXPR_MATCHER = "([A-Za-z0-9._\\-]+(;resolution:=\"optional\")?(;bundle-version:=(\"[A-Za-z0-9.]+\"|\"\\[[A-Za-z0-9.]+,[A-Za-z0-9.]+\\]\"))?)"; private final String symbolicName; private Map attributes; public static final String[] parseList(final String source) throws BundleException { ArrayList list = new ArrayList(); if (source != null) { final String spec = source.replaceAll(" ", ""); final String regex = REQUIRE_BUNDLE_EXPR_MATCHER; final Pattern pattern = Pattern.compile(regex); final Matcher matcher = pattern.matcher(spec); StringBuffer check = new StringBuffer(); while (matcher.find()) { final String group = matcher.group(); check.append("," + group); list.add(group); } if (!spec.equals(check.toString().replaceFirst(",", ""))) { throw new BundleException("Syntax error specifying required-bundles list: '" + source + "'"); } } return (String[])list.toArray(new String[0]); } public RequiredBundleSpec(final String spec) { attributes = new HashMap(); final String[] data = spec.split(";"); this.symbolicName = data[0]; for (int i = 1; i < data.length; i++) { final String[] pairs = data[i].replaceAll(" ", "").split(":="); attributes.put(pairs[0], pairs[1]); } } public final String getSymbolicName() { return this.symbolicName; } public final String getBundleVersion() { final String bundleversion = (String) attributes.get(PROP_KEY_BUNDLE_VERSION); return (bundleversion == null) ? "(any-version)" : bundleversion; } public final boolean isOptional() { final String resolution = (String) attributes.get(PROP_KEY_RESOLUTION); return (resolution != null) && resolution.equals("optional"); } public final boolean isCompatible(final String symbolicName, final String version) { // symbolic-names must match if (!this.symbolicName.equals(symbolicName)) { return false; } // if symbolic-names are matching, then check for version compatibility String spec = (String) attributes.get(PROP_KEY_BUNDLE_VERSION); // no specific bundle-version required/specified // so it must be compatible with the version if (spec == null) { return true; } // clean up the version spec a bit spec = spec.replaceAll("\\\"", ""); final VersionSpec target = new VersionSpec(version); // bundle-version:="1.0.0" // anything >= 1.0.0 if (!spec.startsWith("[") && !spec.startsWith("(")) { final VersionSpec v = new VersionSpec(spec); return (v.compareTo(target) <= 0); } // bundle-version:="[1.0.0, 1.0.1]" // anything within bounds of the given range final boolean inclusiveFloor = spec.startsWith("["); final boolean inclusiveCeiling = spec.endsWith("]"); spec = spec.replaceAll("\\[|\\]|\\(|\\)", ""); final String[] range = spec.replaceAll(" ", "").split(","); final VersionSpec floor = new VersionSpec(range[0]); final VersionSpec ceiling = new VersionSpec(range[1]); final boolean lowerBound = inclusiveFloor ? (floor.compareTo(target) >= 0) : (floor.compareTo(target) > 0); final boolean upperBound = inclusiveCeiling ? (target.compareTo(ceiling) <= 0) : (target.compareTo(ceiling) < 0); // it's compatible if version falls within the (lower|upper)-bound versions // according to the (in|ex)clusivity flags return (lowerBound && upperBound); } class VersionSpec { private String[] spec = new String[0]; public VersionSpec(final String version) { this.spec = version.split("\\."); } public final String getMajor() { return spec[0]; } public final String getMinor() { return spec.length > 1 ? spec[1] : ""; } public final String getRevision() { return spec.length > 2 ? spec[2] : ""; } public final String getBuild() { return spec.length > 3 ? spec[3] : ""; } public final int compareTo(VersionSpec v) { int result = getMajor().compareTo(v.getMajor()); if (result == 0) { result = getMinor().compareTo(v.getMinor()); if (result == 0) { result = getRevision().compareTo(v.getRevision()); if (result == 0) { result = getBuild().compareTo(v.getBuild()); } } } return result; } public final String toString() { StringBuffer buffer = new StringBuffer(this.spec[0]); for (int i = 1; i < this.spec.length; i++) { buffer.append(".").append(this.spec[i]); } return buffer.toString(); } } }
true
3506717b9feb5d03aceefe57a5f3d90196d9e50f
Java
mwlevin/HeatedPavement
/src/heatedpavement/Gate.java
UTF-8
1,263
2.453125
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 heatedpavement; import ilog.concert.IloException; import ilog.cplex.IloCplex; /** * flow in = flow out * @author micha */ public class Gate extends Taxiway { private char size; public Gate(String name, Node dest, double area, char size) { // no source node, the gate is the end point super(name, null, dest, area); this.size = size; } public void addConstraints(IloCplex cplex) throws IloException { super.addConstraints(cplex); double capacity = getCapacity()/2; for (Configuration c : Airport.configurations) { cplex.addLe(dep_flow_ij.get(c), capacity); cplex.addLe(arr_flow_ji.get(c), capacity); cplex.addEq(dep_flow_ji.get(c), 0); cplex.addEq(arr_flow_ij.get(c), 0); } } public char getSize() { return size; } public Type getType() { return Type.gate; } }
true
67e09cf318c2b923c4ae696f19665c3eee8b4abf
Java
owenlejeune/IOU
/app/src/main/java/com/owenlejeune/iou/MyAppWidgetProvider.java
UTF-8
2,219
2.203125
2
[]
no_license
package com.owenlejeune.iou; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.widget.RemoteViews; import android.widget.Toast; import java.util.ArrayList; /** * Created by owenlejeune on 2017-05-25. */ public class MyAppWidgetProvider extends AppWidgetProvider { public static final String REFRESH_ACTION = "com.owenlejeune.REFRESH_ACTION"; @Override public void onReceive(Context context, Intent intent){ AppWidgetManager mgr = AppWidgetManager.getInstance(context); if(intent.getAction().equals(REFRESH_ACTION)){ int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); this.onUpdate(context, AppWidgetManager.getInstance(context), appWidgetIds); //Toast.makeText(context, "onReceive()", Toast.LENGTH_SHORT).show(); } super.onReceive(context, intent); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){ final int N = appWidgetIds.length; for(int i = 0; i < N; i++){ //int appWidgetId = appWidgetIds[i]; RemoteViews remoteViews = updateWidgetListView(context, appWidgetIds[i]); appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews); } //Toast.makeText(context, "onUpdate()", Toast.LENGTH_SHORT).show(); super.onUpdate(context, appWidgetManager, appWidgetIds); } private RemoteViews updateWidgetListView(Context context, int appWidgetId){ RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.appwidget_layout); Intent svcIntent = new Intent(context, WidgetService.class); svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); svcIntent.setData(Uri.parse(svcIntent.toUri(Intent.URI_INTENT_SCHEME))); remoteViews.setRemoteAdapter(R.id.appwidget_listview, svcIntent); remoteViews.setEmptyView(R.id.appwidget_listview, R.id.empty_widget_view); return remoteViews; } }
true
d4fdf1bd05dd4750db5da296a20a1dc42773b6da
Java
Karuna595/HO-T2March2020
/app01/src/main/java/com/mastek/app/App.java
UTF-8
899
2.421875
2
[]
no_license
package com.mastek.app; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import com.mastek.app.config.AppConfig; import com.mastek.app.service.CustomerService; /** * Hello world! * */ public class App { private static final Logger LOGGER = Logger.getLogger("confLogger"); public static void main(String[] args) { try { ApplicationContext context=new AnnotationConfigApplicationContext(AppConfig.class); CustomerService service=(CustomerService)context.getBean(CustomerService.class); service.setName("CustomService"); service.setUrl("/CustomService"); service.printName(); service.printUrl(); service.printException(); } catch (Exception e) { LOGGER.log(Level.INFO,e.getMessage()); } } }
true
9198e4c8e3af1ca82631431edd8dd089d1594706
Java
grenouille82/etreegcs
/src/main/java/de/ovgu/dke/clustering/msctest/SampleDataset.java
UTF-8
2,048
2.609375
3
[]
no_license
package de.ovgu.dke.clustering.msctest; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Random; import de.ovgu.dke.util.ObjectSet; import de.ovgu.dke.util.ObjectWrapper; import de.ovgu.dke.util.SimpleObjectSet; import de.ovgu.dke.util.SimpleObjectWrapper; public class SampleDataset { public static void main(String args[]) { ObjectSet dataset = createDataset(); try { dataset.writeToFile("/home/grenouille/irg_workspace/datasets/uniform_4cluster.csv"); } catch(IOException e) { e.printStackTrace(); } } public static ObjectSet createDataset() { Random rnd = new Random(1); ObjectWrapper[] wrapper = new ObjectWrapper[800]; for(int i=0; i<200; i++) { wrapper[i] = new SimpleObjectWrapper(null, new double[] {(rnd.nextDouble()*3d+5d), rnd.nextDouble()*3d+5d}); wrapper[i].setClassLabel("cluster1"); wrapper[i].setLabel("None"); } for(int i=200; i<400; i++) { wrapper[i] = new SimpleObjectWrapper(null, new double[] {(rnd.nextDouble()*3d+5d), rnd.nextDouble()*3d+10d} ); wrapper[i].setClassLabel("cluster2"); wrapper[i].setLabel("None"); } for(int i=400; i<600; i++) { wrapper[i] = new SimpleObjectWrapper(null, new double[] {(rnd.nextDouble()*3d+5d), rnd.nextDouble()*3d+15d}); wrapper[i].setClassLabel("cluster3"); wrapper[i].setLabel("None"); } for(int i=600; i<800; i++) { wrapper[i] = new SimpleObjectWrapper(null, new double[] {(rnd.nextDouble()*3d+5d), rnd.nextDouble()*3d+20d}); wrapper[i].setClassLabel("cluster4"); wrapper[i].setLabel("None"); } /* for(int i=800; i<1000; i++) { wrapper[i] = new SimpleObjectWrapper(null, new double[] {(rnd.nextDouble()*3d+5d), rnd.nextDouble()*3d+40d}); wrapper[i].setClassLabel("cluster5"); wrapper[i].setLabel("None"); }*/ /* for(int i=450; i<500; i++) wrapper[i] = new SimpleObjectWrapper(null, new double[] {(rnd.nextDouble()*20d+200d), rnd.nextDouble()*20d+200d}); */ //TODO: set Attributes return new SimpleObjectSet(wrapper, null); } }
true
53d9984db86cb7c43b68d152a6a4345bca16eeda
Java
nagaikenshin/schemaOrg
/schemaOrgDomaConv/src/org/kyojo/schemaOrg/m3n3/doma/core/container/ExifDataConverter.java
UTF-8
553
2.140625
2
[ "Apache-2.0" ]
permissive
package org.kyojo.schemaorg.m3n3.doma.core.container; import org.seasar.doma.ExternalDomain; import org.seasar.doma.jdbc.domain.DomainConverter; import org.kyojo.schemaorg.m3n3.core.impl.EXIF_DATA; import org.kyojo.schemaorg.m3n3.core.Container.ExifData; @ExternalDomain public class ExifDataConverter implements DomainConverter<ExifData, String> { @Override public String fromDomainToValue(ExifData domain) { return domain.getNativeValue(); } @Override public ExifData fromValueToDomain(String value) { return new EXIF_DATA(value); } }
true
3731ec87a2f6bade72e15b692a27b0c1f7a28514
Java
cbodi/ALC-4.0-Challenge-2
/app/src/main/java/net/zealtechconsulting/travelmantics/TravelDeal.java
UTF-8
1,733
2.875
3
[]
no_license
package net.zealtechconsulting.travelmantics; import java.io.Serializable; //The TravelDeal class implements the Serializable class so that the TravelDeal class can be passed in the putExtra //method of an Intent. For performance reasons, it will be better to use the Parcelable interface public class TravelDeal implements Serializable { private String id; private String title; private String description; private String price; private String imageUrl; private String imagePath; public TravelDeal(String title, String description, String price, String imageUrl, String imagePath) { this.setId(id); this.setTitle(title); this.setDescription(description); this.setPrice(price); this.setImageUrl(imageUrl); this.setImagePath(imagePath); } public TravelDeal() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } }
true
8c79f00f865b9cdb74f5112e1696281f70d4b7f3
Java
chanyaz/ewe-android-hack
/project/src/main/java/com/expedia/bookings/data/trips/CustomerSupport.java
UTF-8
2,452
2.25
2
[]
no_license
package com.expedia.bookings.data.trips; import org.json.JSONException; import org.json.JSONObject; import com.mobiata.android.Log; import com.mobiata.android.json.JSONable; public class CustomerSupport implements JSONable { private static final String JSON_SUPPORT_URL = "customerSupportURL"; private static final String JSON_SUPPORT_PHONE_INFO = "customerSupportPhoneInfo"; private static final String JSON_SUPPORT_PHONE_DOMESTIC = "customerSupportPhoneNumberDomestic"; private static final String JSON_SUPPORT_PHONE_INTERNATIONAL = "customerSupportPhoneNumberInternational"; private String mCustomerSupportUrl; private String mCustomerSupportPhoneInfo; private String mCustomerSupportPhoneNumberDomestic; private String mCustomerSupportPhoneNumberInternational; public CustomerSupport() { } public void setSupportUrl(String url) { mCustomerSupportUrl = url; } public String getSupportUrl() { return mCustomerSupportUrl; } public void setSupportPhoneInfo(String phoneInfo) { mCustomerSupportPhoneInfo = phoneInfo; } public String getSupportPhoneInfo() { return mCustomerSupportPhoneInfo; } public void setSupportPhoneNumberDomestic(String number) { mCustomerSupportPhoneNumberDomestic = number; } public String getSupportPhoneNumberDomestic() { return mCustomerSupportPhoneNumberDomestic; } public void setSupportPhoneNumberInternational(String number) { mCustomerSupportPhoneNumberInternational = number; } public String getSupportPhoneNumberInternational() { return mCustomerSupportPhoneNumberInternational; } @Override public JSONObject toJson() { JSONObject json = new JSONObject(); try { json.putOpt(JSON_SUPPORT_URL, mCustomerSupportUrl); json.putOpt(JSON_SUPPORT_PHONE_INFO, mCustomerSupportPhoneInfo); json.putOpt(JSON_SUPPORT_PHONE_DOMESTIC, mCustomerSupportPhoneNumberDomestic); json.putOpt(JSON_SUPPORT_PHONE_INTERNATIONAL, mCustomerSupportPhoneNumberInternational); } catch (JSONException ex) { Log.e("JSONException", ex); } return json; } @Override public boolean fromJson(JSONObject json) { mCustomerSupportUrl = json.optString(JSON_SUPPORT_URL, null); mCustomerSupportPhoneInfo = json.optString(JSON_SUPPORT_PHONE_INFO, null); mCustomerSupportPhoneNumberDomestic = json.optString(JSON_SUPPORT_PHONE_DOMESTIC, null); mCustomerSupportPhoneNumberInternational = json.optString(JSON_SUPPORT_PHONE_INTERNATIONAL, null); return true; } }
true
a354c224982ada0803f019cf5f3b066902a3deb3
Java
AliakseiLasevich/ggau
/src/main/java/app/model/dto/request/BuildingRequest.java
UTF-8
322
1.835938
2
[]
no_license
package app.model.dto.request; import jakarta.validation.constraints.NotEmpty; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @Getter @Builder @NoArgsConstructor @AllArgsConstructor public class BuildingRequest { @NotEmpty private String name; }
true
42dfaa48b3f588b70c6447eb3f40c3bab778deef
Java
myrddian/9X-Pasta
/ciotola/src/main/java/ciotola/implementation/DefaultCiotolaContainer.java
UTF-8
13,384
1.664063
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2021. Enzo Reyes 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 ciotola.implementation; import ciotola.Ciotola; import ciotola.CiotolaConnectionService; import ciotola.CiotolaContext; import ciotola.CiotolaServiceInterface; import ciotola.actor.CiotolaDirector; import ciotola.annotations.CiotolaAutowire; import ciotola.annotations.CiotolaBean; import ciotola.annotations.CiotolaService; import ciotola.pools.CiotolaConnectionPool; import ciotola.pools.CiotolaKeyPool; import io.github.classgraph.ClassGraph; import io.github.classgraph.ClassInfo; import io.github.classgraph.ClassInfoList; import io.github.classgraph.ScanResult; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DefaultCiotolaContainer implements CiotolaContext { private final Logger logger = LoggerFactory.getLogger(DefaultCiotolaContainer.class); private ExecutorService executorService = Executors.newCachedThreadPool(); private Map<String, CiotolaServiceInterface> serviceInterfaceMap = new ConcurrentHashMap<>(); private Map<String, Class> candidateService = new ConcurrentHashMap<>(); private Map<String, Object> autoWires = new ConcurrentHashMap<>(); private Map<String, Object> beans = new ConcurrentHashMap<>(); private Map<String, Logger> loggerMap = new ConcurrentHashMap<>(); private List<String> loadedJars = new ArrayList<>(); private List<String> scanAnnotations = new ArrayList<>(); private Map<Integer, PooledServiceRunner> serviceRunners = new ConcurrentHashMap<>(); private CiotolaKeyPool keyPoolExecutor; private CiotolaConnectionPool connectionPool; private long connectionTimeOut = 240; private CiotolaDirector ciotolaDirector; public DefaultCiotolaContainer() { resetDefaults(); } private void resetDefaults() { int physicalCores = getNumberOfCPUCores(); /* Default schema for this is 1/4 Connection Min 2 3/4 For the remaining key pool min 2 */ // Initialise pools - some default allocations int connectionPoolCounter = physicalCores / 4; int keyPool = connectionPoolCounter * 3; if (connectionPoolCounter <= 1) { connectionPoolCounter = 2; } if (keyPool <= 1) { keyPool = 2; } connectionPool = new CiotolaConnectionPool(connectionPoolCounter); keyPoolExecutor = new CiotolaKeyPool(keyPool); ciotolaDirector = new CiotolaDirector(physicalCores); // Setup the system scanAnnotations.clear(); scanAnnotations.add(CiotolaAutowire.class.getName()); scanAnnotations.add(CiotolaService.class.getName()); scanAnnotations.add(CiotolaBean.class.getName()); addDependency(CiotolaContext.class, this); connectionPool.setIdleTimeout(connectionTimeOut); } @Override public void addAnnotation(Class annotation) { scanAnnotations.add(annotation.getName()); } @Override public List<String> getAnnotations() { return scanAnnotations; } @Override public List<String> getLoadedJars() { return loadedJars; } @Override public void submitJob(Runnable job) { executorService.submit(job); } @Override public Collection<CiotolaServiceInterface> getServices() { return serviceInterfaceMap.values(); } @Override public void addService(CiotolaServiceInterface newService) { serviceInterfaceMap.put(newService.serviceName(), newService); } @Override public void addService(Object newService) { AnnotatedJavaServiceRunner newRunner = new AnnotatedJavaServiceRunner(newService); serviceInterfaceMap.put(newRunner.serviceName(), newRunner); } @Override public void removeService(int serviceId) { serviceRunners.remove(serviceId); } @Override public int injectService(CiotolaServiceInterface newService, boolean skipInjection) { int svcCounter = serviceRunners.size() + 1; PooledServiceRunner runner = new PooledServiceRunner(newService, svcCounter); if (!skipInjection) { serviceInterfaceMap.put(newService.serviceName(), newService); processInjection(newService.serviceName()); } else { logger.debug( "No injection for " + newService.serviceName() + " Mapped to ID [ " + Integer.toString(svcCounter) + " ] "); } runner.start(); executorService.execute(runner); serviceRunners.put(svcCounter, runner); return svcCounter; } @Override public int injectService(Object newService, boolean skipInjection) { AnnotatedJavaServiceRunner runner = new AnnotatedJavaServiceRunner(newService); return injectService(runner, skipInjection); } @Override public int injectService(CiotolaServiceInterface newService) { return injectService(newService, false); } @Override public int injectService(Object newService) { return injectService(newService, false); } @Override public void injectDependencies(Object newService) { processInjection(newService); } @Override public void addDependency(Object dependency) { beans.put(dependency.getClass().getName(), dependency); } @Override public void addDependency(Class name, Object wire) { beans.put(name.getName(), wire); } @Override public ExecutorService getExecutorService() { return executorService; } @Override public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } @Override public int threadCapacity() { int capacity = Runtime.getRuntime().availableProcessors() / 2; if (capacity < 1) { return 1; } return capacity; } @Override public void execute(Runnable job, long key) { keyPoolExecutor.addJob(job, key); } @Override public void execute(CiotolaConnectionService connectionService) { connectionPool.addConnection(connectionService); } @Override public void stop() { connectionPool.shutDownPool(); keyPoolExecutor.shutdown(); executorService.shutdownNow(); } @Override public CiotolaDirector getDirector() { return ciotolaDirector; } @Override public long getConnectionTimeOut() { return connectionTimeOut; } @Override public void setConnectionTimeOut(long connectionTimeOut) { this.connectionTimeOut = connectionTimeOut; } @Override public boolean startContainer() { // Assumption we are embedded some how - dont do additional parsing logger.debug("Ciotola Container - Running"); try (ScanResult scanResult = new ClassGraph().enableAllInfo().scan()) { ClassInfoList classInfos = scanResult.getAllClasses(); for (ClassInfo info : classInfos) { for (ClassInfo annotation : info.getAnnotations()) { if (scanAnnotations.contains(annotation.getName())) { if (annotation.getName().equals(CiotolaService.class.getName())) { candidateService.put(info.getName(), info.loadClass()); } else { autoWires.put(info.getName(), info.loadClass()); } } } } } if (!processServices()) { return false; } if (!processDependencies()) { return false; } return startServices(); } private boolean startServices() { int counter = serviceRunners.size(); for (String key : serviceInterfaceMap.keySet()) { PooledServiceRunner runner = new PooledServiceRunner(serviceInterfaceMap.get(key), counter); runner.start(); executorService.execute(runner); ++counter; serviceRunners.put(counter, runner); } return true; } private boolean processServices() { for (String cService : candidateService.keySet()) { logger.debug("Creating Service " + cService); try { Constructor constructor = candidateService.get(cService).getConstructor(); Object newServiceInstance = constructor.newInstance(); AnnotatedJavaServiceRunner runner = new AnnotatedJavaServiceRunner(newServiceInstance); serviceInterfaceMap.put(cService, runner); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { logger.error(Ciotola.CLASS_LOADING_ERROR, e); return false; } } return true; } private boolean processInjection(Object wiringComponent) { for (Field objField : wiringComponent.getClass().getDeclaredFields()) { objField.setAccessible(true); for (Annotation annotation : objField.getDeclaredAnnotations()) { if (annotation instanceof CiotolaAutowire) { Object autoWrite = serviceInterfaceMap.get(objField.getType().getName()); Object beanWire = beans.get(objField.getType().getName()); if (autoWrite == null && beanWire != null) { autoWrite = beanWire; } else { logger.error(Ciotola.UNKNOWN_COMPONENT_SPECIFIED); break; } if (autoWrite.getClass().getName().equals(AnnotatedJavaServiceRunner.class.getName())) { AnnotatedJavaServiceRunner runner = (AnnotatedJavaServiceRunner) autoWrite; autoWrite = runner.getObject(); } logger.debug( "Autowiring: " + wiringComponent.getClass().getName() + " ( " + objField.getName() + " , " + autoWrite.getClass().getName() + " )"); try { objField.set(wiringComponent, autoWrite); } catch (IllegalAccessException e) { logger.error(Ciotola.CLASS_LOADING_ERROR, e); return false; } } } } return true; } private boolean processInjection(String serviceClass) { Object wiringComponent = serviceInterfaceMap.get(serviceClass).getObject(); return processInjection(wiringComponent); } private boolean processDependencies() { logger.debug("Injecting Dependencies"); // Scan Components and autowire the requested attributes for (String service : serviceInterfaceMap.keySet()) { if (processInjection(service) == false) { logger.error(Ciotola.UNKNOWN_COMPONENT_SPECIFIED); return false; } } return true; } private int getNumberOfCPUCores() { OSValidator osValidator = new OSValidator(); String command = ""; if (osValidator.isMac()) { logger.debug("System is running Mac OS"); command = "sysctl -n machdep.cpu.core_count"; } else if (osValidator.isUnix()) { logger.debug("System is running a Linux/Unix variant - trying lscpu"); command = "lscpu"; } else if (osValidator.isWindows()) { logger.debug("System is running Microsoft Windows"); command = "cmd /C WMIC CPU Get /Format:List"; } Process process = null; int numberOfCores = 0; int sockets = 0; try { if (osValidator.isMac()) { String[] cmd = {"/bin/sh", "-c", command}; process = Runtime.getRuntime().exec(cmd); } else { process = Runtime.getRuntime().exec(command); } } catch (IOException e) { logger.error("Unable to determine physical processor layout - returning default", e); return threadCapacity(); } BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; try { while ((line = reader.readLine()) != null) { if (osValidator.isMac()) { numberOfCores = line.length() > 0 ? Integer.parseInt(line) : 0; } else if (osValidator.isUnix()) { if (line.contains("Core(s) per socket:")) { numberOfCores = Integer.parseInt(line.split("\\s+")[line.split("\\s+").length - 1]); } if (line.contains("Socket(s):")) { sockets = Integer.parseInt(line.split("\\s+")[line.split("\\s+").length - 1]); } } else if (osValidator.isWindows()) { if (line.contains("NumberOfCores")) { numberOfCores = Integer.parseInt(line.split("=")[1]); } } } } catch (IOException e) { logger.error("Unable to determine physical processor layout - returning default", e); return threadCapacity(); } if (osValidator.isUnix()) { return numberOfCores * sockets; } return numberOfCores; } }
true
264d11a51144426c5e0cd709753555b28fc942ea
Java
DarrickAZ/rsbi
/src/main/java/com/ruisi/ext/engine/view/rules/cross/TotalDsRule.java
UTF-8
815
1.648438
2
[]
no_license
// // Source code recreated from a .class file by IntelliJ IDEA // (powered by Fernflower decompiler) // package com.ruisi.ext.engine.view.rules.cross; import com.ruisi.ext.engine.init.TemplateManager; import com.ruisi.ext.engine.view.context.cross.CrossReportContext; import org.apache.commons.digester.Rule; public class TotalDsRule extends Rule { public TotalDsRule() { } public void body(String var1, String var2, String var3) { if (var3 != null && var3.length() != 0) { CrossReportContext var4 = (CrossReportContext)this.digester.peek(); if (var4.getRef() == null || var4.getRef().length() == 0) { String var5 = TemplateManager.getInstance().createTemplate(var3); var4.setTotalTemplateName(var5); } } } }
true
eebc4513bb0eeae85c31fe8caf1bfb4b81960718
Java
bangjeongjin/flowstudent
/src/flowctrl/java/exam06/finalFieldsAndConstants/Person.java
UHC
285
2.703125
3
[]
no_license
package flowctrl.java.exam06.finalFieldsAndConstants; public class Person { //finalʵ ʱȭ final String nation = "Koera"; final String ssn; String name; public Person (String ssn, String name) { this.ssn = ssn; this.name = name; } }
true
d144e2c08004d05efb223ef324a0625f39c8bd6b
Java
DndyDev/JavaItis9
/Projects/18. Recursion/src/ru/itis/MainRecursion.java
UTF-8
780
3.53125
4
[]
no_license
package ru.itis; /** * 28.02.2019 * MainRecursion * * @author Sidikov Marsel (First Software Engineering Platform) * @version v1.0 */ public class MainRecursion { public static int step = 0; public static int fact(int n) { System.out.println(">>> " + step + ", in fact(" + n + ")"); step++; if (n == 0) { System.out.println("<<< " + step + ", from fact(" + n + ") with result = " + 1); step++; return 1; } // n! = (n - 1)! * n int result = fact(n - 1) * n; System.out.println("<<< " + step + ", from fact(" + n + ") with result = " + result); step++; return result; } public static void main(String[] args) { System.out.println(fact(6)); } }
true
249eb4905575173235ae27e9df542922746b3d0a
Java
amkimian/OG-Platform
/projects/OG-Web/src/main/java/com/opengamma/web/analytics/AnalyticsViewClientConnection.java
UTF-8
9,976
1.6875
2
[ "Apache-2.0" ]
permissive
/** * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.web.analytics; import java.util.List; import com.google.common.collect.Lists; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.engine.marketdata.NamedMarketDataSpecificationRepository; import com.opengamma.engine.marketdata.spec.LiveMarketDataSpecification; import com.opengamma.engine.marketdata.spec.MarketDataSpecification; import com.opengamma.engine.view.ViewComputationResultModel; import com.opengamma.engine.view.ViewDeltaResultModel; import com.opengamma.engine.view.ViewResultModel; import com.opengamma.engine.view.calc.EngineResourceReference; import com.opengamma.engine.view.calc.ViewCycle; import com.opengamma.engine.view.client.ViewClient; import com.opengamma.engine.view.client.ViewResultMode; import com.opengamma.engine.view.compilation.CompiledViewDefinition; import com.opengamma.engine.view.execution.ExecutionFlags; import com.opengamma.engine.view.execution.ExecutionOptions; import com.opengamma.engine.view.execution.InfiniteViewCycleExecutionSequence; import com.opengamma.engine.view.execution.ViewCycleExecutionOptions; import com.opengamma.engine.view.execution.ViewExecutionOptions; import com.opengamma.engine.view.listener.AbstractViewResultListener; import com.opengamma.id.UniqueId; import com.opengamma.livedata.UserPrincipal; import com.opengamma.master.marketdatasnapshot.MarketDataSnapshotMaster; import com.opengamma.util.ArgumentChecker; import com.opengamma.web.server.AggregatedViewDefinitionManager; /** * Connects the engine to an {@link AnalyticsView}. Contains the logic for setting up a {@link ViewClient}, * connecting it to a view process, handling events from the engine and forwarding data to the {@code ViewClient}. */ /* package */ class AnalyticsViewClientConnection { private final AnalyticsView _view; private final ViewClient _viewClient; private final AggregatedViewDefinition _aggregatedViewDef; private final ViewExecutionOptions _executionOptions; private final NamedMarketDataSpecificationRepository _marketDataSpecRepo; private EngineResourceReference<? extends ViewCycle> _cycleReference = EmptyViewCycle.REFERENCE; /** * @param viewRequest Defines the view that should be created * @param viewClient Connects this class to the calculation engine * @param view The object that encapsulates the state of the view user interface * @param marketDataSpecRepo For looking up sources of market data * @param aggregatedViewDefManager For looking up view definitions * @param snapshotMaster For looking up snapshots */ /* package */ AnalyticsViewClientConnection(ViewRequest viewRequest, ViewClient viewClient, AnalyticsView view, NamedMarketDataSpecificationRepository marketDataSpecRepo, AggregatedViewDefinitionManager aggregatedViewDefManager, MarketDataSnapshotMaster snapshotMaster) { ArgumentChecker.notNull(viewRequest, "viewRequest"); ArgumentChecker.notNull(viewClient, "viewClient"); ArgumentChecker.notNull(view, "view"); ArgumentChecker.notNull(marketDataSpecRepo, "marketDataSpecRepo"); ArgumentChecker.notNull(aggregatedViewDefManager, "aggregatedViewDefManager"); ArgumentChecker.notNull(snapshotMaster, "snapshotMaster"); _view = view; _viewClient = viewClient; _aggregatedViewDef = new AggregatedViewDefinition(aggregatedViewDefManager, viewRequest); _marketDataSpecRepo = marketDataSpecRepo; List<MarketDataSpecification> requestedMarketDataSpecs = viewRequest.getMarketDataSpecs(); List<MarketDataSpecification> actualMarketDataSpecs = fixMarketDataSpecs(requestedMarketDataSpecs); ViewCycleExecutionOptions defaultOptions = new ViewCycleExecutionOptions(viewRequest.getValuationTime(), actualMarketDataSpecs); _executionOptions = ExecutionOptions.of(new InfiniteViewCycleExecutionSequence(), defaultOptions, // this recalcs periodically or when market data changes. might need to give // the user the option to specify the behaviour ExecutionFlags.triggersEnabled().get(), viewRequest.getPortfolioVersionCorrection()); } /** * This is a temporary hack to allow the old and new web interfaces to run side by side. The old UI shows a mixture * of data sources including live sources, multiple live sources combined, live sources backed by historical data * and pure historical data. The new UI only shows live sources, and the names of those sources don't match the * names in the old UI (which include something to tell the user it's a live source). The real data sources * are looked up using the old names so this method rebuilds the list of data sources and replaces the new source * specs with the old ones. * @param requestedMarketDataSpecs The market data sources requested by the user * @return The specs needed to look up the sources the user requested */ private List<MarketDataSpecification> fixMarketDataSpecs(List<MarketDataSpecification> requestedMarketDataSpecs) { List<MarketDataSpecification> specs = Lists.newArrayListWithCapacity(requestedMarketDataSpecs.size()); for (MarketDataSpecification spec : requestedMarketDataSpecs) { if (spec instanceof LiveMarketDataSpecification) { LiveMarketDataSpecification liveSpec = (LiveMarketDataSpecification) spec; MarketDataSpecification oldSpec = _marketDataSpecRepo.getSpecification(liveSpec.getDataSource()); if (oldSpec == null) { throw new IllegalArgumentException("No live data source found called " + liveSpec.getDataSource()); } specs.add(oldSpec); } else { specs.add(spec); } } return specs; } /** * Connects to the engine in order to start receiving results. This should only be called once. */ /* package */ void start() { _viewClient.setResultListener(new Listener()); _viewClient.setViewCycleAccessSupported(true); _viewClient.setResultMode(ViewResultMode.FULL_THEN_DELTA); try { _viewClient.attachToViewProcess(_aggregatedViewDef.getUniqueId(), _executionOptions); } catch (Exception e) { _aggregatedViewDef.close(); throw new OpenGammaRuntimeException("Failed to attach view client to view process", e); } } /** * Disconects from the engine and releases all resources. This should only be called once. */ /* package */ void close() { try { _viewClient.detachFromViewProcess(); } finally { _cycleReference.release(); _aggregatedViewDef.close(); } } /** * @return The view to which this object sends data received from the engine. */ /* package */ AnalyticsView getView() { return _view; } /** * Listener for view results. This is an inner class to avoid polluting the interface of the parent class with * public callback methods. */ private class Listener extends AbstractViewResultListener { @Override public void cycleCompleted(ViewComputationResultModel fullResult, ViewDeltaResultModel deltaResult) { _cycleReference.release(); ViewResultModel results = deltaResult != null ? deltaResult : fullResult; // always retain a reference to the most recent cycle so the dependency graphs are available at all times. // without this it would be necessary to wait at least one cycle before it would be possible to access the graphs. // this allows dependency graphs grids to be opened and populated without any delay EngineResourceReference<? extends ViewCycle> cycleReference = _viewClient.createCycleReference(results.getViewCycleId()); if (cycleReference == null) { // this shouldn't happen if everything in the engine is working as it should _cycleReference = EmptyViewCycle.REFERENCE; } else { _cycleReference = cycleReference; } _view.updateResults(results, _cycleReference.get()); } @Override public UserPrincipal getUser() { return _viewClient.getUser(); } @Override public void viewDefinitionCompiled(CompiledViewDefinition compiledViewDefinition, boolean hasMarketDataPermissions) { _view.updateStructure(compiledViewDefinition); } } /** * Wrapper that hides a bit of the ugliness of {@link AggregatedViewDefinitionManager}. */ private static final class AggregatedViewDefinition { private final AggregatedViewDefinitionManager _aggregatedViewDefManager; private final UniqueId _baseViewDefId; private final List<String> _aggregatorNames; private final UniqueId _id; private AggregatedViewDefinition(AggregatedViewDefinitionManager aggregatedViewDefManager, ViewRequest viewRequest) { ArgumentChecker.notNull(aggregatedViewDefManager, "aggregatedViewDefManager"); ArgumentChecker.notNull(viewRequest, "viewRequest"); _aggregatedViewDefManager = aggregatedViewDefManager; _baseViewDefId = viewRequest.getViewDefinitionId(); _aggregatorNames = viewRequest.getAggregators(); try { _id = _aggregatedViewDefManager.getViewDefinitionId(_baseViewDefId, _aggregatorNames); } catch (Exception e) { close(); throw new OpenGammaRuntimeException("Failed to get aggregated view definition", e); } } private UniqueId getUniqueId() { return _id; } private void close() { _aggregatedViewDefManager.releaseViewDefinition(_baseViewDefId, _aggregatorNames); } } }
true
12eabbb1ec53486da89211b28ce6f352f05f7d0f
Java
taidangit/springframework
/spring-webflow-demo/src/main/java/com/luv2code/dao/MessageDAO.java
UTF-8
259
1.914063
2
[]
no_license
package com.luv2code.dao; import java.util.List; import com.luv2code.entity.Messages; public interface MessageDAO { List<Messages> getMessages(); Messages getMessageById(int id); void saveMessage(Messages message); void deleteMessage(int id); }
true
19913a0224897d04923a01c983a2d743b42465b0
Java
larzm42/dom3editor
/org.larz.dom3.dm/src-gen/org/larz/dom3/dm/dm/GeneralInst1.java
UTF-8
18,361
1.78125
2
[]
no_license
/** * <copyright> * </copyright> * */ package org.larz.dom3.dm.dm; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>General Inst1</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#getValue <em>Value</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isPoppergold <em>Poppergold</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isResourcemult <em>Resourcemult</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isSupplymult <em>Supplymult</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isUnresthalfinc <em>Unresthalfinc</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isUnresthalfres <em>Unresthalfres</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isEventisrare <em>Eventisrare</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isTurmoilincome <em>Turmoilincome</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isTurmoilevents <em>Turmoilevents</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isDeathincome <em>Deathincome</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isDeathsupply <em>Deathsupply</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isDeathdeath <em>Deathdeath</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isSlothincome <em>Slothincome</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isSlothresources <em>Slothresources</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isColdincome <em>Coldincome</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isColdsupply <em>Coldsupply</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isMisfortune <em>Misfortune</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isLuckevents <em>Luckevents</em>}</li> * <li>{@link org.larz.dom3.dm.dm.GeneralInst1#isResearchscale <em>Researchscale</em>}</li> * </ul> * </p> * * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1() * @model * @generated */ public interface GeneralInst1 extends GeneralPattern1 { /** * Returns the value of the '<em><b>Value</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Value</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Value</em>' attribute. * @see #setValue(int) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Value() * @model * @generated */ int getValue(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#getValue <em>Value</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Value</em>' attribute. * @see #getValue() * @generated */ void setValue(int value); /** * Returns the value of the '<em><b>Poppergold</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Poppergold</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Poppergold</em>' attribute. * @see #setPoppergold(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Poppergold() * @model * @generated */ boolean isPoppergold(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isPoppergold <em>Poppergold</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Poppergold</em>' attribute. * @see #isPoppergold() * @generated */ void setPoppergold(boolean value); /** * Returns the value of the '<em><b>Resourcemult</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Resourcemult</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Resourcemult</em>' attribute. * @see #setResourcemult(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Resourcemult() * @model * @generated */ boolean isResourcemult(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isResourcemult <em>Resourcemult</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Resourcemult</em>' attribute. * @see #isResourcemult() * @generated */ void setResourcemult(boolean value); /** * Returns the value of the '<em><b>Supplymult</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Supplymult</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Supplymult</em>' attribute. * @see #setSupplymult(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Supplymult() * @model * @generated */ boolean isSupplymult(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isSupplymult <em>Supplymult</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Supplymult</em>' attribute. * @see #isSupplymult() * @generated */ void setSupplymult(boolean value); /** * Returns the value of the '<em><b>Unresthalfinc</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Unresthalfinc</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Unresthalfinc</em>' attribute. * @see #setUnresthalfinc(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Unresthalfinc() * @model * @generated */ boolean isUnresthalfinc(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isUnresthalfinc <em>Unresthalfinc</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Unresthalfinc</em>' attribute. * @see #isUnresthalfinc() * @generated */ void setUnresthalfinc(boolean value); /** * Returns the value of the '<em><b>Unresthalfres</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Unresthalfres</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Unresthalfres</em>' attribute. * @see #setUnresthalfres(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Unresthalfres() * @model * @generated */ boolean isUnresthalfres(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isUnresthalfres <em>Unresthalfres</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Unresthalfres</em>' attribute. * @see #isUnresthalfres() * @generated */ void setUnresthalfres(boolean value); /** * Returns the value of the '<em><b>Eventisrare</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Eventisrare</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Eventisrare</em>' attribute. * @see #setEventisrare(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Eventisrare() * @model * @generated */ boolean isEventisrare(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isEventisrare <em>Eventisrare</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Eventisrare</em>' attribute. * @see #isEventisrare() * @generated */ void setEventisrare(boolean value); /** * Returns the value of the '<em><b>Turmoilincome</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Turmoilincome</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Turmoilincome</em>' attribute. * @see #setTurmoilincome(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Turmoilincome() * @model * @generated */ boolean isTurmoilincome(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isTurmoilincome <em>Turmoilincome</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Turmoilincome</em>' attribute. * @see #isTurmoilincome() * @generated */ void setTurmoilincome(boolean value); /** * Returns the value of the '<em><b>Turmoilevents</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Turmoilevents</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Turmoilevents</em>' attribute. * @see #setTurmoilevents(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Turmoilevents() * @model * @generated */ boolean isTurmoilevents(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isTurmoilevents <em>Turmoilevents</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Turmoilevents</em>' attribute. * @see #isTurmoilevents() * @generated */ void setTurmoilevents(boolean value); /** * Returns the value of the '<em><b>Deathincome</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Deathincome</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Deathincome</em>' attribute. * @see #setDeathincome(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Deathincome() * @model * @generated */ boolean isDeathincome(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isDeathincome <em>Deathincome</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deathincome</em>' attribute. * @see #isDeathincome() * @generated */ void setDeathincome(boolean value); /** * Returns the value of the '<em><b>Deathsupply</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Deathsupply</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Deathsupply</em>' attribute. * @see #setDeathsupply(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Deathsupply() * @model * @generated */ boolean isDeathsupply(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isDeathsupply <em>Deathsupply</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deathsupply</em>' attribute. * @see #isDeathsupply() * @generated */ void setDeathsupply(boolean value); /** * Returns the value of the '<em><b>Deathdeath</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Deathdeath</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Deathdeath</em>' attribute. * @see #setDeathdeath(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Deathdeath() * @model * @generated */ boolean isDeathdeath(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isDeathdeath <em>Deathdeath</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Deathdeath</em>' attribute. * @see #isDeathdeath() * @generated */ void setDeathdeath(boolean value); /** * Returns the value of the '<em><b>Slothincome</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Slothincome</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Slothincome</em>' attribute. * @see #setSlothincome(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Slothincome() * @model * @generated */ boolean isSlothincome(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isSlothincome <em>Slothincome</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Slothincome</em>' attribute. * @see #isSlothincome() * @generated */ void setSlothincome(boolean value); /** * Returns the value of the '<em><b>Slothresources</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Slothresources</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Slothresources</em>' attribute. * @see #setSlothresources(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Slothresources() * @model * @generated */ boolean isSlothresources(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isSlothresources <em>Slothresources</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Slothresources</em>' attribute. * @see #isSlothresources() * @generated */ void setSlothresources(boolean value); /** * Returns the value of the '<em><b>Coldincome</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Coldincome</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Coldincome</em>' attribute. * @see #setColdincome(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Coldincome() * @model * @generated */ boolean isColdincome(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isColdincome <em>Coldincome</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Coldincome</em>' attribute. * @see #isColdincome() * @generated */ void setColdincome(boolean value); /** * Returns the value of the '<em><b>Coldsupply</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Coldsupply</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Coldsupply</em>' attribute. * @see #setColdsupply(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Coldsupply() * @model * @generated */ boolean isColdsupply(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isColdsupply <em>Coldsupply</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Coldsupply</em>' attribute. * @see #isColdsupply() * @generated */ void setColdsupply(boolean value); /** * Returns the value of the '<em><b>Misfortune</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Misfortune</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Misfortune</em>' attribute. * @see #setMisfortune(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Misfortune() * @model * @generated */ boolean isMisfortune(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isMisfortune <em>Misfortune</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Misfortune</em>' attribute. * @see #isMisfortune() * @generated */ void setMisfortune(boolean value); /** * Returns the value of the '<em><b>Luckevents</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Luckevents</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Luckevents</em>' attribute. * @see #setLuckevents(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Luckevents() * @model * @generated */ boolean isLuckevents(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isLuckevents <em>Luckevents</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Luckevents</em>' attribute. * @see #isLuckevents() * @generated */ void setLuckevents(boolean value); /** * Returns the value of the '<em><b>Researchscale</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Researchscale</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Researchscale</em>' attribute. * @see #setResearchscale(boolean) * @see org.larz.dom3.dm.dm.DmPackage#getGeneralInst1_Researchscale() * @model * @generated */ boolean isResearchscale(); /** * Sets the value of the '{@link org.larz.dom3.dm.dm.GeneralInst1#isResearchscale <em>Researchscale</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Researchscale</em>' attribute. * @see #isResearchscale() * @generated */ void setResearchscale(boolean value); } // GeneralInst1
true
3035da51a613f7290f196d6f90e270f19eb66398
Java
houzhanwu/ycej
/ycej-workflow/src/main/java/com/yicheejia/workflow/service/ActivitiBaseService.java
UTF-8
2,295
2.15625
2
[ "Apache-2.0" ]
permissive
package com.yicheejia.workflow.service; import java.util.List; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.engine.task.Task; /** * Activiti 常用service * @author hunk * */ public interface ActivitiBaseService { /** * 获取用户当前处于代办人的任务集合 只查user * * @param userId * 用户 * @return 任务集合 */ public List<Task> getUserHaveTasksUser(String userId); /** * 验证工作流是不是已经停止 * * @param instanceId * 工作流id * @return true:已经停止,false:没有停止 */ public Boolean validateActiviti(String instanceId); /** * 完成任务 * * @param taskId * 任务id */ public void completeTask(String taskId) ; /** * 根据任务id得到Form key * @param taskId * @return */ public String getFormKey(String taskId); /** * 根据TaskID 获取 FormID * @param taskID * @return */ public String getFormIDByTaskID(String taskID) ; /** * 根据表单ID获取Task * * @param formid * @return */ public Task getTaskByFormID(String formid); /** * 根据表单ID获取Task * * @param processKey 流程定义key * @param formid * @return */ public Task getTaskByFormID(String processKey,String formid); /** * 根据Task 获取 FormID * @param task * @return */ public String getFormIDByTask(Task task); /** * 根据Task 获取 ProcessInstance * @param task * @return */ public ProcessInstance getProcessInstanceByTask(Task task) ; /** * 获取参数 * @param executionId * @param variableName * @param variableClass * @return */ public <T> T getVariable(String executionId, String variableName, Class<String> variableClass); /** * 获取用户当前处于代办人的任务集合 ,根据用户,单据主键查询 * * @param userId * 用户 * @param billID * 业务单据主键 * @return 任务集合 */ public Boolean getUserHaveTasksUser(String userId, String formID); }
true
6d8e30c05a08720a36a4dd36b1577cca2e00a643
Java
Kai2314/SL314
/src/servlet_examples/MessageSource.java
UTF-8
479
2.40625
2
[]
no_license
package servlet_examples; import java.io.*; import java.net.*; import java.rmi.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; import com.oreilly.servlet.RemoteDaemonHttpServlet; // MessageSource acts as the source for new messages. // Clients interested in receiving new messages can // observe this object. class MessageSource extends Observable { public void sendMessage(String message) { setChanged(); notifyObservers(message); } }
true
04c1f426a65c312145371fd6540809b7812acba7
Java
impuls93/Design-Patterns-Practice-Strategy
/src/com/impuls/designpatterns/practice/classimplementation/DecoyImp.java
UTF-8
450
2.671875
3
[]
no_license
package com.impuls.designpatterns.practice.classimplementation; import com.impuls.designpatterns.practice.abstractclasses.Decoy; import com.impuls.designpatterns.practice.interfaceimplementation.NoQuacking; public class DecoyImp extends Decoy{ public DecoyImp() { quackinterface = new NoQuacking(); } @Override public void show() { // TODO Auto-generated method stub System.out.println("Implementing decoy..."); } }
true
d658ff09ae8ecc75fc9f610506ec9d18e34028b6
Java
mosamo/Image_Sharing_App_Android
/app/src/main/java/com/example/image_sharing_app/FriendsActivity.java
UTF-8
2,595
2.40625
2
[]
no_license
package com.example.image_sharing_app; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseQuery; import com.parse.ParseUser; import java.util.ArrayList; import java.util.List; public class FriendsActivity extends AppCompatActivity { String username; TextView pane; ArrayAdapter arrayAdapter; final ArrayList<String> userList = new ArrayList<String>(); ListView friendList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_friends); // links xml to this activity username = ParseUser.getCurrentUser().getUsername(); // upper widget pane = findViewById(R.id.userPane); pane.setText(username + " account:"); // greetings bar TextView temp = findViewById(R.id.greeting); temp.setText(username + "'s Friend list:"); // ArrayAdapter boiler arrayAdapter = new ArrayAdapter(this, R.layout.hopefully_white, userList); friendList = findViewById(R.id.friendList); friendList.setAdapter(arrayAdapter); // query boiler ParseQuery<ParseUser> query = ParseUser.getQuery(); query.whereNotEqualTo("username", username); query.findInBackground(new FindCallback<ParseUser>() { @Override public void done(List<ParseUser> objects, ParseException e) { if (e == null) { if (objects.size() > 0) { for (ParseUser foundUser : objects) { userList.add("\u2022 " + foundUser.getUsername()); } arrayAdapter.notifyDataSetChanged(); } } else { Log.i("QueryError", e.toString()); } } }); } public void signOut(View view) { Intent intent = new Intent(this, MainActivity.class); startActivity(intent); finish(); ParseUser.logOut(); } public void feedList(View view) { Intent intent = new Intent(this, SecondActivity.class); startActivity(intent); finish(); } }
true
80f47a16fee2b96d72acb45fb2e5d1505869560f
Java
ReutAttar/Android-studio-app
/Android5778_0920_9377_01/app/src/main/java/com/example/inbal/android5778_0920_9377_01/model/entities/Client.java
UTF-8
1,483
2.6875
3
[]
no_license
package com.example.inbal.android5778_0920_9377_01.model.entities; /** * Created by inbal on 19/11/2017. */ public class Client { private String lastName; private String firstName; private String ID; private String phoneNumber; private String email; private String creditCardNumber; public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCreditCardNumber() { return creditCardNumber; } public void setCreditCardNumber(String creditCardNumber) { this.creditCardNumber = creditCardNumber; } @Override public String toString() { return ("ID: "+ID+" First name: "+firstName+" Last name: "+lastName+"\nPhone number: "+phoneNumber+"\nEmail: "+email+"\nCredit card number: "+creditCardNumber+"\n"); } }
true
7600470761eae4bed8dee8fbe1ed3e938d88e6e2
Java
leinadlime/oulipo
/oulipo-streams/src/main/java/org/oulipo/streams/opcodes/SwapVariantOp.java
UTF-8
3,166
2.484375
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * OulipoMachine licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. *******************************************************************************/ package org.oulipo.streams.opcodes; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.oulipo.streams.MalformedSpanException; import org.oulipo.streams.VariantSpan; /** * Swaps the text and media in one document region with the text and media of * another document region. */ public final class SwapVariantOp extends Op { public final VariantSpan v1; public final VariantSpan v2; /** * * @param dis * @throws MalformedSpanException * @throws IOException */ public SwapVariantOp(DataInputStream dis) throws MalformedSpanException, IOException { this(new VariantSpan(dis), new VariantSpan(dis)); } /** * Creates a <code>SwapVariantOp</code> with the specified variant spans. This * operation swaps v1 with position v2. The variantSpans can't intersect each * other. * * @param v1 * the variant span to swap * @param v2 * the variant span to swap */ public SwapVariantOp(VariantSpan v1, VariantSpan v2) { super(Op.SWAP); if (v1 == null) { throw new IllegalArgumentException("variant span 1 is null"); } if (v2 == null) { throw new IllegalArgumentException("variant span 2 is null"); } this.v1 = v1; this.v2 = v2; } @Override public byte[] encode() throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); try (DataOutputStream dos = new DataOutputStream(os)) { dos.writeByte(Op.SWAP); dos.writeLong(v1.start); dos.writeLong(v1.width); dos.writeLong(v2.start); dos.writeLong(v2.width); } os.flush(); return os.toByteArray(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; SwapVariantOp other = (SwapVariantOp) obj; if (!v1.equals(other.v1)) return false; if (!v2.equals(other.v2)) return false; return true; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + v1.hashCode(); result = prime * result + v2.hashCode(); return result; } @Override public String toString() { return "SwapVariantOp [v1=" + v1 + ", v2=" + v2 + "]"; } }
true
8f8e0238052a4781731b9d99504f348a51842e63
Java
HowDeliveryWorks/Delivery
/Delivery/src/main/java/Delivery/enums/ConstructorCategory.java
UTF-8
568
2.78125
3
[]
no_license
/** * Created by Max on 02.05.2017. */ /** * TODO: Do total ingredients review and refactor. * TODO: Wire enums {@link BreadType} {@link MeatType} etc. to generic class/interface */ /** package Delivery.model; public class ConstructorCategory<T> { private T category; public ConstructorCategory(T arg) { category = arg; } @Override public String toString() { return "{" + category + "}"; } } */ package Delivery.enums; public enum ConstructorCategory { BreadType, Meat, Roasting, Sauce, Misc }
true
5612530e44705650e0ec03a7b6c42b39c98d860f
Java
Aarteksoftwaresolutions2013/Citibreak
/pocket-site/src/main/java/fr/littlereddot/pocket/site/dto/WeatherDataResponse.java
UTF-8
576
2.078125
2
[]
no_license
package fr.littlereddot.pocket.site.dto; import java.util.List; /** * @author Guillaume Le Biller (<i>guillaume.lebiller@gmail.com</i>) * @version $Id$ */ public class WeatherDataResponse { private List<WeatherData> weather; private MainData main; public WeatherDataResponse() { } public List<WeatherData> getWeather() { return weather; } public void setWeather(List<WeatherData> weather) { this.weather = weather; } public MainData getMain() { return main; } public void setMain(MainData main) { this.main = main; } }
true
493ec0cb3f8065b48fa9b313b696bbb5fd2d78a1
Java
lakhlifi-sdk/psycho_app_android
/app/src/main/java/com/lakhlifi/blog/Fragments/HomeFragment.java
UTF-8
5,278
2.03125
2
[]
no_license
package com.lakhlifi.blog.Fragments; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import android.widget.Toolbar; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.android.volley.AuthFailureError; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import com.google.android.material.appbar.MaterialToolbar; import com.lakhlifi.blog.Adapters.PostAdapter; import com.lakhlifi.blog.AuthActivity; import com.lakhlifi.blog.Constant; import com.lakhlifi.blog.HomeActivity; import com.lakhlifi.blog.Models.Post; import com.lakhlifi.blog.Models.User; import com.lakhlifi.blog.R; import com.lakhlifi.blog.UserInfoActivity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class HomeFragment extends Fragment { View view; private RecyclerView recyclerView; private ArrayList<Post> arrayListPost; private SwipeRefreshLayout refreshLayout; private PostAdapter postsAdapter; //private Toolbar toolbar; private MaterialToolbar toolbar; private SharedPreferences sharedPreferences; public HomeFragment(){} @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view= inflater.inflate(R.layout.layout_home,container,false); init(); return view; } private void init() { sharedPreferences=getActivity().getApplicationContext().getSharedPreferences("user",getContext().MODE_PRIVATE); recyclerView=view.findViewById(R.id.recycleHome); refreshLayout=view.findViewById(R.id.swipHome); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setHasFixedSize(true); toolbar=view.findViewById(R.id.toolbarHome); ((HomeActivity)getContext()).setSupportActionBar(toolbar); getPost(); refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { } }); } public void getPost(){ arrayListPost=new ArrayList<>(); refreshLayout.setRefreshing(true); StringRequest request=new StringRequest(Request.Method.GET,Constant.POSTS,response -> { try { JSONObject object = new JSONObject(response); if(object.getBoolean("success")){ JSONArray array=new JSONArray(object.getString("posts")); for (int i = 0; i <array.length() ; i++) { JSONObject postObject=array.getJSONObject(i); JSONObject userObject=postObject.getJSONObject("user"); User user=new User(); user.setId(userObject.getInt("id")); user.setLastName(userObject.getString("lastname")); user.setUserName(userObject.getString("name")); user.setPhoto(userObject.getString("photo")); Post post=new Post(); post.setId(postObject.getInt("id")); post.setUser(user); post.setComments(postObject.getInt("commentsCount")); post.setLikes(postObject.getInt("likesCount")); post.setDesc(postObject.getString("desc")); post.setDate(postObject.getString("created_at")); post.setSelfLikes(postObject.getBoolean("selfLike")); post.setPhoto(postObject.getString("photo")); arrayListPost.add(post); } } postsAdapter = new PostAdapter(getContext(),arrayListPost); recyclerView.setAdapter(postsAdapter); } catch (JSONException e) { e.printStackTrace(); } refreshLayout.setRefreshing(false); }, error -> { error.printStackTrace(); refreshLayout.setRefreshing(false); }){ @Override public Map<String, String> getHeaders() throws AuthFailureError { String token= sharedPreferences.getString("token",""); HashMap<String,String> map= new HashMap<>(); map.put("Authorization","Bearer"+token); return map; } }; RequestQueue queue=Volley.newRequestQueue(getContext()); queue.add(request); } }
true
b495234498e1beedd315718237fadce106c15c04
Java
MrArliton/SOM
/core/src/com/arli/som/GameElement/GameClass.java
UTF-8
4,851
2.546875
3
[]
no_license
package com.arli.som.GameElement; import com.arli.som.Constants; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.input.GestureDetector; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.Viewport; import java.util.ConcurrentModificationException; import java.util.Map; // Основной класс игры public class GameClass implements Screen { MAP map; HUD hud; SpriteBatch batch; InputController input; Map<String,String> options; // Настройки при запуске игры InfoCountry infoCountry; // Тут информация о старанах их ресурсах. Viewport view = new FitViewport(Constants.width,Constants.heigth); MapController MCont; int day = 1; int month = 1; float buffer = 0; public GameClass(Map<String,String> options) { // Создаём основные части игры batch = new SpriteBatch(); infoCountry = new InfoCountry(); infoCountry.addNewInfo(-1); // Общая информация infoCountry.addNewInfo(1); // Информация о стране игрока /// Сделать для разных игроков и ботов /// infoCountry.putInfoCountry(1,"energy","0"); infoCountry.putInfoCountry(1,"matter","0"); infoCountry.putInfoCountry(1,"research","0"); infoCountry.putInfoCountry(1,"transformation","0"); this.options = options; // Подключение основных систем map = new MAP(options.get("map"),infoCountry); hud = new HUD(MCont,infoCountry); MCont = new MapController(map,hud); // Управляет картой // Система контроля input = new InputController(map,hud,MCont); // Создаём коректировку для нужных разрешений int h = Constants.heigth; int w = Constants.width; int h1 = Constants.resolutionWindowH; int w1 = Constants.resolutionWindowW; float correct = Math.max(1-(float)h/h1,1-(float)w/w1)+0.05f; if(correct<0){ correct = 0; } map.cameraMap.zoom = 1f-correct; // Переключение на систему управления игрой Gdx.input.setInputProcessor(new GestureDetector(input)); } @Override public void show() { } private void update(float delta){ updateMonthEffects(); MCont.update(delta); if(buffer<Constants.timeDayCycle){ buffer+=delta; }else { if (day + 1 < 30) { day += 1; } else { day = 0; month += 1; activateMonthEffects(); } buffer = 0; } // Используется для строительства Map<String,String> effects = map.getEffects(1); infoCountry.putInfoCountry(1, "transformation",effects.get("t")); infoCountry.putInfoCountry(-1,"day",day+""); infoCountry.putInfoCountry(-1,"month",month+""); } public void updateMonthEffects(){ Map<String,String> effects = map.getEffects(1); // Для игрока infoCountry.putInfoCountry(1, "energyE", effects.get("e")); infoCountry.putInfoCountry(1, "matterE", effects.get("m")); infoCountry.putInfoCountry(1, "researchE", effects.get("r")); } public void activateMonthEffects(){ Map<String,String> effects = map.getEffects(1); // Для игрока infoCountry.putInfoCountryPlus(1, "energy", effects.get("e")); infoCountry.putInfoCountryPlus(1, "matter", effects.get("m")); infoCountry.putInfoCountryPlus(1, "research", effects.get("r")); infoCountry.putInfoCountry(1, "transformation",effects.get("t")); } @Override public void render(float delta) { // update update(delta); map.update(delta); hud.update(delta); // render batch.begin(); Gdx.gl.glClearColor(0f,0f,0f,0.5f); Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT); map.render(batch); hud.render(batch); batch.end(); } @Override public void resize(int width, int height) { view.update(width,height); map.resize(width,height); hud.resize(width,height); } @Override public void pause() { } @Override public void resume() { } @Override public void hide() { } @Override public void dispose() { } }
true
daeba4e6d147c45365f1e31fb96df75ce44c9827
Java
alibaba/metrics
/metrics-os/src/test/java/com/alibaba/metrics/os/linux/SystemLoadGaugeSetTest.java
UTF-8
1,962
1.960938
2
[ "Apache-2.0", "CC0-1.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.metrics.os.linux; import com.alibaba.metrics.Gauge; import com.alibaba.metrics.Metric; import com.alibaba.metrics.MetricName; import org.junit.Assert; import org.junit.Test; import java.util.Map; import java.util.concurrent.TimeUnit; public class SystemLoadGaugeSetTest { @Test public void testSystemLoadMetrics() { SystemLoadGaugeSet systemLoadGaugeSet = new SystemLoadGaugeSet( 10, TimeUnit.MILLISECONDS, "src/test/resources/proc_loadavg"); Map<MetricName, Metric> metrics = systemLoadGaugeSet.getMetrics(); Assert.assertEquals(3, metrics.keySet().size()); try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } Gauge _1min = (Gauge)metrics.get(MetricName.build("load.1min")); Gauge _5min = (Gauge)metrics.get(MetricName.build("load.5min")); Gauge _15min = (Gauge)metrics.get(MetricName.build("load.15min")); Assert.assertEquals(0.08f, _1min.getValue()); Assert.assertEquals(0.06f, _5min.getValue()); Assert.assertEquals(0.05f, _15min.getValue()); } }
true
673c9e4704e335d5d2f6e3a35aa79136ef2bb30c
Java
rdanielmurphy/FundFind
/app/src/main/java/app/sbaloan/models/IndustrySearchOptionDto.java
UTF-8
384
2.140625
2
[ "CC-BY-3.0" ]
permissive
package app.sbaloan.models; /** * Created by danielmurphy on 10/10/15. */ public class IndustrySearchOptionDto extends SearchOptionDto { private String fullTitle; public IndustrySearchOptionDto(int btnResource, String fullTitle) { super(btnResource); this.fullTitle = fullTitle; } public String getFullTitle() { return fullTitle; } }
true
6f20d05e1bde1e3f3c3f3eb3ceae6c8d22bbc278
Java
jsoliman/spam
/com/drin/java/metrics/ITSRegionMedianMetric.java
UTF-8
2,492
2.390625
2
[]
no_license
package com.drin.java.metrics; import com.drin.java.biology.ITSRegion; import com.drin.java.biology.Pyroprint; import com.drin.java.metrics.ITSRegionMetric; import com.drin.java.metrics.PyroprintComparator; import com.drin.java.metrics.PyroprintMetric; import java.util.List; import java.util.ArrayList; import com.drin.java.util.Logger; public class ITSRegionMedianMetric extends ITSRegionMetric { private static final boolean TRANSFORM = false; private List<Double> mPyroComparisons; public ITSRegionMedianMetric(double alpha, double beta, ITSRegion appliedRegion, PyroprintComparator pyroComp, PyroprintMetric pyroMetric) { super(alpha, beta, appliedRegion, pyroComp, pyroMetric); this.reset(); } public ITSRegionMedianMetric(ITSRegion appliedRegion, PyroprintComparator pyroComp, PyroprintMetric pyroMetric) { super(appliedRegion, pyroComp, pyroMetric); this.reset(); } @Override public void reset() { super.reset(); mPyroComparisons = new ArrayList<Double>(); } @Override public void apply(ITSRegion elem_A, ITSRegion elem_B) { if (elem_A.isSimilarRegion(elem_B)) { for (Pyroprint pyro_A : elem_A.getPyroprints()) { for (Pyroprint pyro_B : elem_B.getPyroprints()) { addComparison(mPyroComp.compare(mPyroMetric, pyro_A, pyro_B)); } } } } private void addComparison(double result) { int compareNdx = 0; for (; compareNdx < mPyroComparisons.size(); compareNdx++) { double tmp_val = mPyroComparisons.get(compareNdx).doubleValue(); if (tmp_val - result > 0) { break; } } mPyroComparisons.add(compareNdx, result); } @Override public double result() { double median = 0; if (!mPyroComparisons.isEmpty()) { int low_ndx = mPyroComparisons.size()/2; int high_ndx = (mPyroComparisons.size()/2) + 1; median += mPyroComparisons.get(low_ndx); if (mPyroComparisons.size() % 2 == 0) { median = (median + mPyroComparisons.get(high_ndx)) / 2; } } else { setError(-1); } Logger.error(getError(), "Error computing ITSRegionMedianMetric"); if (TRANSFORM) { median = transformResult(median); } this.reset(); return median; } }
true
eec3999d0e54915de8e3f828ea870fcf7e369943
Java
saurabh5788/bank-parent
/bank-soap-ws/src/main/java/com/bank/service/dto/response/AccountTypeDTO.java
UTF-8
510
2.046875
2
[]
no_license
package com.bank.service.dto.response; public class AccountTypeDTO { private String code; private String value; private String description; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
true
df455edd19d15985a42c149a5fb8d7d8fc126451
Java
rbnpantha/HackerrankSolutions
/HackerrankDataStructure/src/edu/hackerrank/tree/HuffmanDecoding.java
UTF-8
530
3.03125
3
[]
no_license
package edu.hackerrank.tree; public class HuffmanDecoding { void decode(String S ,Node root) { Node node = root; for (int i = 0; i < S.length(); i++) { node = S.charAt(i) == '0' ? node.left : node.right; if (node.left == null && node.right == null) { System.out.print(node.data); node = root; } } } } class Node{ public int frequency; // the frequency of this tree public char data; public Node left, right; }
true
3138659920855e196dc7ee3dcf6d0a584b8757b8
Java
fanchaojian/FanBlog_java
/src/java/com/fanchaojian/utils/ResultUtils.java
UTF-8
646
2.265625
2
[]
no_license
package com.fanchaojian.utils; /** * 统一返回结果工具类 * @author fanchaojian * @date 2020-9-29 - 15:48 */ public class ResultUtils { public static JsonResult success(Object object) { JsonResult result = new JsonResult(); result.setCode(0); result.setMsg("成功"); result.setData(object); return result; } public static JsonResult success() { return success(null); } public static JsonResult error(Integer code, String msg) { JsonResult result = new JsonResult(); result.setCode(code); result.setMsg(msg); return result; } }
true
84bb47f3cf704fc20be7c093a32ff16b2d2c433f
Java
iism-code/iism-measure
/java/iism-measure/src/org/iism/measure/TimeMeasure.java
UTF-8
1,498
2.546875
3
[ "MIT" ]
permissive
package org.iism.measure; import java.util.HashMap; import java.util.HashSet; public class TimeMeasure implements AutoCloseable { static HashMap<String, TimeMeasureData> timeMeasureMap = new HashMap<String, TimeMeasureData>(); private TimeMeasure(TimeMeasureData timeMeasureData) { this.timeMeasureData = timeMeasureData; } TimeMeasureData timeMeasureData; long startTime; public void startMeasure() { startTime = System.currentTimeMillis(); } public void endMeasure() { long delta = System.currentTimeMillis() - startTime; timeMeasureData.addMeasurement(delta); } synchronized public static TimeMeasure get(String measureName) { if (timeMeasureMap.containsKey(measureName)) { TimeMeasure measure = new TimeMeasure(timeMeasureMap.get(measureName)); measure.startMeasure(); return measure; } TimeMeasureData timeMeasureData = new TimeMeasureData(measureName); TimeMeasure measure = new TimeMeasure(timeMeasureData); timeMeasureMap.put(measureName, timeMeasureData); measure.startMeasure(); return measure; } @Override public void close() { endMeasure(); } public void addMeasure(long delta) { timeMeasureData.addMeasurement(delta); } synchronized public static HashSet<RollupData> snapshotTimeMeasureData(HashSet<RollupData> exportData) { for (TimeMeasureData timeMeasureData : timeMeasureMap.values()) { for (RollupData data : timeMeasureData.getExportData()) { exportData.add(data); } } return exportData; } }
true
60edd53916068766088cb9bfe88fedc453fde2b4
Java
RebortBoss/KPlayer
/KPlayer/src/com/xk/player/ui/VoiceBody.java
UTF-8
797
2.359375
2
[]
no_license
package com.xk.player.ui; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.GC; import com.xk.player.uilib.JBody; public class VoiceBody implements JBody { @Override public void draw(GC gc,int pointX,int width,int height) { boolean adv=gc.getAdvanced(); gc.setAdvanced(true); gc.setAntialias(SWT.ON); Color back=gc.getBackground(); Color fore=gc.getForeground(); Color color=new Color(null, 255, 255, 255); gc.setBackground(color); gc.setForeground(color); int[]arr=new int[]{height/2,height/2+3,width-height/2,height/2,width-height/2,height/2+3}; gc.fillPolygon(arr); gc.drawPolygon(arr); gc.setBackground(back); gc.setForeground(fore); gc.setAdvanced(adv); color.dispose(); } }
true
2e02ec8bc079e8e26be7b9d5b7350a4fbdd32fb1
Java
murongfeng66/platform
/platform-common/src/main/java/com/jwzhu/platform/common/enums/YesOrNo.java
UTF-8
1,308
2.8125
3
[]
no_license
package com.jwzhu.platform.common.enums; import java.util.HashMap; import java.util.Map; import com.jwzhu.platform.common.exception.SystemException; import com.jwzhu.platform.plugs.jsonescape.bind.JsonEscapeInterface; /** * 是否枚举 **/ public enum YesOrNo implements JsonEscapeInterface<Short> { Yes((short) 1, "是"), No((short) 0, "否"); public static Map<Short, String> map = new HashMap<>(); static { for (YesOrNo item : YesOrNo.values()) { map.put(item.code, item.message); } } /** * 编码 */ private short code; /** * 描述 */ private String message; YesOrNo(short code, String message) { this.code = code; this.message = message; } public static String message(short code) { return map.get(code); } public static YesOrNo get(short code) { for (YesOrNo item : YesOrNo.values()) { if (item.code == code) { return item; } } throw new SystemException("无此[" + code + "]枚举"); } public short getCode() { return code; } public String getMessage() { return message; } @Override public Object getMessage(Short id) { return null; } }
true
f17c568c0bf11c417244fb00ff3cbcf3b09f39cc
Java
r2bapps/BaseProject
/BaseProject/src/r2b/apps/lib/taskmanager/BaseSyncTask.java
UTF-8
3,410
2.859375
3
[ "MIT" ]
permissive
/* * BaseSyncTask * * 0.2 * * 2014/06/21 * * (The MIT License) * * Copyright (c) R2B Apps <r2b.apps@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * 'Software'), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ package r2b.apps.lib.taskmanager; /** * This class is useful for packaging any task implementation and * run on a task pool with multithreading and priority support. * * Run a task with a synchronous functionality. It means that this can have * several asynchronous/synchronous processes but these must be sequential, * this class wraps this functionality. It means also that this class have * a callback to send to its executor that this has finished and retrieves * its result. * * WARNING: If you cancel this kind of task you will not receive a 'completed' event. * * @param <V> Void or any other object. */ public abstract class BaseSyncTask<V> extends Task<V> { /** * The observable task. */ private final BaseSyncTaskObservable<V> observable = new BaseSyncTaskObservable<V>(this); /** * Builder. * @param id The task identifier. * @param priority The task priority. */ public BaseSyncTask(long id, PRIORITY priority) { super(id); init(this, priority); } /** * Builder, with the task default priority and identifier value zero. */ public BaseSyncTask() { super(0); init(this, PRIORITY.DEFAULT); } /** * Adds the specified observer to the list of observers. If it is already * registered, it is not added a second time. * * WARNING: The notify is made in the same thread as the task is running, * you can not make gui calls on the observer. * * @param observer The observer. */ public void addObserver(BaseSyncTaskObserver<V> observer) { this.observable.addObserver(observer); } /* (non-Javadoc) * @see r2b.apps.lib.taskmanager.Task#call() */ @Override public final V call() throws Exception { final V result = super.call(); // Call to Observers this.observable.setChanged(); this.observable.notifyObservers(result); // Clear info this.observable.deleteObservers(); return result; } /* (non-Javadoc) * @see r2b.apps.lib.taskmanager.Task#cancel(boolean) */ @Override public boolean cancel(boolean mayInterruptIfRunning) { boolean exit = super.cancel(mayInterruptIfRunning); // Delete observer callbacks this.observable.deleteObservers(); return exit; } }
true
1d3baba81307fba328fbcd4142eb9eaa4c94d180
Java
adelgadillog/adn-backend-ceiba
/microservicio/dominio/src/test/java/com/ceiba/pedido/servicio/testdatabuilder/DtoTrmTestDataBuilder.java
UTF-8
395
2.25
2
[]
no_license
package com.ceiba.pedido.servicio.testdatabuilder; import com.ceiba.trm.modelo.DtoTrm; public class DtoTrmTestDataBuilder { private String mensaje; private String valor; public DtoTrmTestDataBuilder(String mensaje,String valor) { this.mensaje = mensaje; this.valor = valor; } public DtoTrm build() { return new DtoTrm(valor, mensaje); } }
true
ceee9b4cf6c23b8eaddc70e4e2c519b1cbb5e579
Java
LuboViluda/loyalty-service
/src/main/java/com/playground/loyalitypointsservice/UserLoyaltyDto.java
UTF-8
968
2.03125
2
[]
no_license
package com.playground.loyalitypointsservice; import com.fasterxml.jackson.annotation.JsonInclude; import static com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL; public class UserLoyaltyDto { private String id; private String href; @JsonInclude(NON_NULL) private Long points; @JsonInclude(NON_NULL) private Long pendingPoints; UserLoyaltyDto() { } public String getid() { return id; } public void setUuid(String id) { this.id = id; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public Long getPoints() { return points; } public void setPoints(Long points) { this.points = points; } public Long getPendingPoints() { return pendingPoints; } public void setPendingPoints(Long pendingPoints) { this.pendingPoints = pendingPoints; } }
true
366cfdb18f2f2090284538a49d9ef414c6080b2f
Java
seungyean/kobook_final
/kobook_final/src/main/java/com/kobook/controller/CommunityController.java
UTF-8
26,810
1.773438
2
[]
no_license
package com.kobook.controller; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.List; import javax.annotation.Resource; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.apache.commons.io.IOUtils; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.kobook.alarm.domain.AlarmVO; import com.kobook.alarm.service.AlarmService; import com.kobook.book.domain.PageMaker; import com.kobook.book.domain.SearchCriteria; import com.kobook.community.domain.BlackVO; import com.kobook.community.domain.DonateVO; import com.kobook.community.domain.PhotoHeartVO; import com.kobook.community.domain.PhotoVO; import com.kobook.community.domain.ReplyVO; import com.kobook.community.service.BlackService; import com.kobook.community.service.DonateService; import com.kobook.community.service.PhotoReviewService; import com.kobook.message.domain.MessageVO; import com.kobook.message.service.MessageService; import com.kobook.sidebar.domain.TodayVO; import com.kobook.sidebar.service.TodayService; import com.kobook.util.MediaUtils; import com.kobook.util.UploadFileUtils; @Controller @RequestMapping("/community/*") public class CommunityController { @Inject private BlackService blackService; @Inject private DonateService donateService; @Inject private PhotoReviewService photoService; @Inject private TodayService todayService; @Inject private MessageService mService; @Inject private AlarmService alarmService; @Resource(name = "uploadPath") private String uploadPath; // 파일 업로드 @ResponseBody @RequestMapping(value = "/uploadAjax", method = RequestMethod.POST, produces = "text/plain;charset=UTF-8") public ResponseEntity<String> uploadAjax(MultipartFile file) throws Exception { System.out.println("originalName: " + file.getOriginalFilename()); return new ResponseEntity<>(UploadFileUtils.uploadFile(uploadPath, file.getOriginalFilename(), file.getBytes()), HttpStatus.CREATED); } // 파일(이미지) 출력 @ResponseBody @RequestMapping("/displayFile") public ResponseEntity<byte[]> displayFile(String fileName) throws Exception { InputStream in = null; ResponseEntity<byte[]> entity = null; System.out.println("FILE NAME: " + fileName); try { String formatName = fileName.substring(fileName.lastIndexOf(".") + 1); MediaType mType = MediaUtils.getMediaType(formatName); HttpHeaders headers = new HttpHeaders(); in = new FileInputStream(uploadPath + fileName); if (mType != null) { headers.setContentType(mType); } else { fileName = fileName.substring(fileName.indexOf("_") + 1); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.add("Content-Disposition", "attachment; filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + "\""); } entity = new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED); } catch (Exception e) { e.printStackTrace(); entity = new ResponseEntity<byte[]>(HttpStatus.BAD_REQUEST); } finally { in.close(); } return entity; } // attach 테이블에서 업로드된 파일 삭제 @ResponseBody @RequestMapping(value = "/deleteFile", method = RequestMethod.POST) public ResponseEntity<String> deleteFile(String fileName) { System.out.println("delete file: " + fileName); String formatName = fileName.substring(fileName.lastIndexOf(".") + 1); MediaType mType = MediaUtils.getMediaType(formatName); if (mType != null) { String front = fileName.substring(0, 12); String end = fileName.substring(14); new File(uploadPath + (front + end).replace('/', File.separatorChar)).delete(); } new File(uploadPath + fileName.replace('/', File.separatorChar)).delete(); return new ResponseEntity<String>("deleted", HttpStatus.OK); } @ResponseBody @RequestMapping(value = "/deleteAllFiles", method = RequestMethod.POST) public ResponseEntity<String> deleteFile(@RequestParam("files[]") String[] files) { System.out.println("delete all files: " + files); if (files == null || files.length == 0) { return new ResponseEntity<String>("deleted", HttpStatus.OK); } for (String fileName : files) { String formatName = fileName.substring(fileName.lastIndexOf(".") + 1); MediaType mType = MediaUtils.getMediaType(formatName); if (mType != null) { String front = fileName.substring(0, 12); String end = fileName.substring(14); new File(uploadPath + (front + end).replace('/', File.separatorChar)).delete(); } new File(uploadPath + fileName.replace('/', File.separatorChar)).delete(); } return new ResponseEntity<String>("deleted", HttpStatus.OK); } // 자주묻는질문 @RequestMapping(value = "/qna", method = RequestMethod.GET) public void qna() throws Exception { } // 신고게시판 글 등록 폼 이동 @RequestMapping(value = "blackRegist", method = RequestMethod.GET) public void blackRegistGet(@ModelAttribute("blackCommand") BlackVO vo) throws Exception { } // 신고게시판 글 등록(DB) @RequestMapping(value = "blackRegist", method = RequestMethod.POST) public String blackRegistPost(@ModelAttribute("blackCommand") @Valid BlackVO vo, BindingResult errors, Model model) throws Exception { if (errors.hasErrors()) { return "/community/blackRegist"; } MessageVO message = new MessageVO(); message.setPerson_id(vo.getPerson_id()); message.setReceiver_id(1); message.setMessage_content(" '" + vo.getBlack_title() + "' 이(가) 신고게시판에 새로 등록 되었습니다."); mService.messageSend(message); AlarmVO alarmVO = new AlarmVO(); alarmVO.setAlarm_kind("Message"); alarmVO.setAlarm_content("신고게시판 새 글 등록 알림쪽지"); alarmVO.setPerson_id(1); alarmService.alarmMessage(alarmVO); blackService.blackRegist(vo); return "redirect:/community/blackList"; } // 신고 게시판 List출력 @RequestMapping(value = "blackList", method = RequestMethod.GET) public void blackList(@ModelAttribute("cri") SearchCriteria cri, Model model) throws Exception { List<BlackVO> list = blackService.blackList(cri); HashMap<Integer, String> userMap = new HashMap<Integer, String>(); int black_id; for (int index = 0; index < list.size(); index++) { black_id = list.get(index).getBlack_id(); userMap.put(black_id, blackService.blackWriter(black_id)); } model.addAttribute("list", list); model.addAttribute("userMap", userMap); PageMaker pageMaker = new PageMaker(); pageMaker.setCri(cri); pageMaker.setTotalCount(blackService.blackCount(cri)); model.addAttribute("pageMaker", pageMaker); } // 신고게시판 미리보기 @ResponseBody @RequestMapping(value = "blackPreviewContent", method = RequestMethod.GET, produces = "application/text; charset=utf8") public String blackPreviewContent(@RequestParam("black_id") Integer black_id) throws Exception { System.out.println("preview controller......"); return blackService.blackPreviewContent(black_id); } // 신고게시판 상세보기 @RequestMapping("blackRead") public void blackRead(@RequestParam("black_id") int black_id, Model model, @ModelAttribute("cri") SearchCriteria cri) throws Exception { model.addAttribute(blackService.blackRead(black_id)); model.addAttribute("writer", blackService.blackWriter(black_id)); } // 신고게시판 이전 글 이동 @ResponseBody @RequestMapping(value = "blackPrev/{black_id}", method = RequestMethod.GET) public Integer blackPrev(@PathVariable("black_id") int black_id) throws Exception { Integer blackId = null; if (blackService.blackPrev(black_id) != null) { blackId = blackService.blackPrev(black_id); } else { blackId = -1; } return blackId; } // 신고게시판 다음 글 이동 @ResponseBody @RequestMapping(value = "blackNext/{black_id}", method = RequestMethod.GET) public Integer blackNext(@PathVariable("black_id") int black_id) throws Exception { Integer blackId = null; if (blackService.blackNext(black_id) != null) { blackId = blackService.blackNext(black_id); } else { blackId = -1; } return blackId; } // 신고게시판 수정 폼 이동 @RequestMapping(value = "blackModify", method = RequestMethod.GET) public void blackModifyGet(@RequestParam("black_id") int black_id, Model model, @ModelAttribute("cri") SearchCriteria cri) throws Exception { model.addAttribute(blackService.blackRead(black_id)); model.addAttribute("writer", blackService.blackWriter(black_id)); } // 신고게시판 글 수정(DB) @RequestMapping(value = "blackModify", method = RequestMethod.POST) public String blackModifyPost(RedirectAttributes rtts, BlackVO vo, SearchCriteria cri) throws Exception { blackService.blackModify(vo); rtts.addAttribute("page", cri.getPage()); rtts.addAttribute("perPageNum", cri.getPerPageNum()); rtts.addAttribute("searchType", cri.getSearchType()); rtts.addAttribute("keyword", cri.getKeyword()); return "redirect:/community/blackList"; } // 신고게시판 글 삭제(DB) @RequestMapping("blackRemove") public String blackRemove(RedirectAttributes rtts, SearchCriteria cri, @RequestParam("black_id") Integer black_id) throws Exception { blackService.blackRemove(black_id); rtts.addAttribute("page", cri.getPage()); rtts.addAttribute("perPageNum", cri.getPerPageNum()); rtts.addAttribute("searchType", cri.getSearchType()); rtts.addAttribute("keyword", cri.getKeyword()); return "redirect:/community/blackList"; } // black_attach 파일명 추출 @RequestMapping("/blackGetAttach/{black_id}") @ResponseBody public List<String> blackGetAttach(@PathVariable("black_id") Integer black_id) throws Exception { return blackService.blackGetAttach(black_id); } // 무료나눔 게시판 글 등록 폼 이동 @RequestMapping(value = "/donateRegist", method = RequestMethod.GET) public void donateRegistGet(@ModelAttribute("donateCommand") DonateVO vo) throws Exception { } // 무료나눔 글 등록(DB) @RequestMapping(value = "/donateRegist", method = RequestMethod.POST) public String donateRegistPost(@ModelAttribute("donateCommand") @Valid DonateVO vo, BindingResult errors, @RequestParam("file") MultipartFile file) throws Exception { if (errors.hasErrors()) { return "/community/donateRegist"; } String donate_thumbnail = UploadFileUtils.uploadFile(uploadPath, file.getOriginalFilename(), file.getBytes()); String[] donate_thumbnail1 = donate_thumbnail.split("_"); if (donate_thumbnail1.length > 2) { String donate_img = donate_thumbnail.substring(0, 12); String donate_img2 = donate_thumbnail.substring(14); vo.setDonate_thumbnail((donate_img + donate_img2)); } donateService.donateRegist(vo); return "redirect:/community/donateList"; } // 무료나눔 List 출력 @RequestMapping("donateList") public void donateList(@ModelAttribute("cri") SearchCriteria cri, Model model) throws Exception { List<DonateVO> list = donateService.donateList(cri); HashMap<Integer, String> userMap = new HashMap<Integer, String>(); int donate_id; for (int index = 0; index < list.size(); index++) { donate_id = list.get(index).getDonate_id(); userMap.put(donate_id, donateService.donateWriter(donate_id)); } model.addAttribute("list", list); model.addAttribute("userMap", userMap); PageMaker pageMaker = new PageMaker(); pageMaker.setCri(cri); pageMaker.setTotalCount(donateService.donateCount(cri)); model.addAttribute("pageMaker", pageMaker); } // 무료나눔 내용 미리보기 @ResponseBody @RequestMapping(value = "donatePreviewContent", method = RequestMethod.GET, produces = "application/text; charset=utf8") public String donatePreviewContent(@RequestParam("donate_id") Integer donate_id) throws Exception { System.out.println("preview controller......"); return donateService.donatePreviewContent(donate_id); } // 무료나눔 첨부파일 추출 @RequestMapping(value = "/donateGetAttach/{donate_id}") @ResponseBody public List<String> donateGetAttach(@PathVariable("donate_id") Integer donate_id) throws Exception { return donateService.donateGetAttach(donate_id); } // 무료나눔 게시판 상세보기 @RequestMapping("donateRead") public void donateRead(@RequestParam("donate_id") Integer donate_id, Model model, @ModelAttribute("cri") SearchCriteria cri, DonateVO donateVO, ReplyVO vo, HttpServletRequest request) throws Exception { model.addAttribute(donateService.donateRead(donate_id, true)); model.addAttribute("writer", donateService.donateWriter(donate_id)); model.addAttribute("replyList", donateService.donateReplyList(donate_id)); HttpSession session = request.getSession(false); if (session.getAttribute("person_id") != null) { TodayVO todayVO = new TodayVO(); Integer person_id = Integer.parseInt((String) session.getAttribute("person_id")); if (donateService.getPersonId(donate_id) != person_id) { if (todayService.checkPersonIdByDonateID(donate_id, person_id) == 0) { todayVO.setPerson_id(person_id); todayVO.setDonate_id(donate_id); todayService.todayRegist(todayVO); } } } } // 무료나눔 이전 글 이동 @ResponseBody @RequestMapping(value = "donatePrev/{donate_id}", method = RequestMethod.GET) public Integer donatePrev(@PathVariable("donate_id") int donate_id) throws Exception { Integer donateId = null; if (donateService.donatePrev(donate_id) != null) { donateId = donateService.donatePrev(donate_id); } else { donateId = -1; } return donateId; } // 무료나눔 다음 글 이동 @ResponseBody @RequestMapping(value = "donateNext/{donate_id}", method = RequestMethod.GET) public Integer donateNext(@PathVariable("donate_id") int donate_id) throws Exception { Integer donateId = null; if (donateService.donateNext(donate_id) != null) { donateId = donateService.donateNext(donate_id); } else { donateId = -1; } return donateId; } // 무료나눔 글 수정 폼 이동 @RequestMapping(value = "donateModify", method = RequestMethod.GET) public void donateModifyGet(@RequestParam("donate_id") int donate_id, Model model, @ModelAttribute("cri") SearchCriteria cri) throws Exception { model.addAttribute(donateService.donateRead(donate_id, false)); model.addAttribute("writer", donateService.donateWriter(donate_id)); } // 무료나눔 글 수정(DB) @RequestMapping(value = "donateModify", method = RequestMethod.POST) public String donateModifyPost(RedirectAttributes rtts, DonateVO vo, SearchCriteria cri, @RequestParam("file") MultipartFile file) throws Exception { System.out.println("Modify Post 컨트롤러 진입"); String donate_thumbnail = UploadFileUtils.uploadFile(uploadPath, file.getOriginalFilename(), file.getBytes()); String[] donate_thumbnail1 = donate_thumbnail.split("_"); if (donate_thumbnail1.length > 2) { String donate_img = donate_thumbnail.substring(0, 12); String donate_img2 = donate_thumbnail.substring(14); vo.setDonate_thumbnail((donate_img + donate_img2)); } donateService.donateModify(vo); rtts.addAttribute("page", cri.getPage()); rtts.addAttribute("perPageNum", cri.getPerPageNum()); rtts.addAttribute("searchType", cri.getSearchType()); rtts.addAttribute("keyword", cri.getKeyword()); return "redirect:/community/donateList"; } // 무료나눔 글 삭제(DB) @RequestMapping("donateRemove") public String donateRemove(RedirectAttributes rtts, SearchCriteria cri, @RequestParam("donate_id") Integer donate_id) throws Exception { if (todayService.todayCountByDonateId(donate_id) > 0) { todayService.todayAllRemoveByDonateId(donate_id); } donateService.donateRemove(donate_id); rtts.addAttribute("page", cri.getPage()); rtts.addAttribute("perPageNum", cri.getPerPageNum()); rtts.addAttribute("searchType", cri.getSearchType()); rtts.addAttribute("keyword", cri.getKeyword()); return "redirect:/community/donateList"; } // 무료나눔 댓글 등록(DB) @RequestMapping(value = "donateReplyRegist", method = RequestMethod.POST) public String donateReplyRegist(ReplyVO vo, Model model, @ModelAttribute("cri") SearchCriteria cri) throws Exception { donateService.donateReplyRegist(vo); int donate_id = vo.getDonate_id(); model.addAttribute(donateService.donateRead(donate_id, false)); model.addAttribute("writer", donateService.donateWriter(donate_id)); model.addAttribute("replyList", donateService.donateReplyList(donate_id)); MessageVO message = new MessageVO(); message.setPerson_id(vo.getPerson_id()); // 댓글 작성자의 person_id message.setReceiver_id(donateService.getPersonId(donate_id)); // donate원본 글 작성자의 person_id message.setMessage_content(" '" + donateService.getPersonName(vo.getPerson_id()) + "'님께서 회원님의 '" + donateService.getDonateTitle(donate_id) + "' 글에 댓글을 남겼습니다.");// 댓글 작성자의 person_name, //원본 donate글의 제목 mService.messageSend(message); AlarmVO alarmVO = new AlarmVO(); alarmVO.setAlarm_kind("Message"); alarmVO.setAlarm_content("댓글 등록 알림 쪽지"); alarmVO.setPerson_id(donateService.getPersonId(donate_id)); alarmService.alarmMessage(alarmVO); return "/community/donateRead"; } // 무료나눔 게시판 댓글 수정 폼 이동 @RequestMapping(value = "donateReplyModify", method = RequestMethod.GET) public void donateReplyModifyGET(Model model, @ModelAttribute("cri") SearchCriteria cri, @RequestParam("donate_id") Integer donate_id, @RequestParam("reply_id") Integer reply_id) throws Exception { model.addAttribute("reply_id", reply_id); model.addAttribute(donateService.donateRead(donate_id, false)); model.addAttribute("writer", donateService.donateWriter(donate_id)); model.addAttribute("replyList", donateService.donateReplyList(donate_id)); } // 무료나눔 게시판 댓글 수정(DB) @RequestMapping(value = "donateReplyModify", method = RequestMethod.POST) public String donateReplyModifyPOST(Model model, ReplyVO vo, @ModelAttribute("cri") SearchCriteria cri) throws Exception { donateService.replyModify(vo); System.out.println(vo.toString()); model.addAttribute(donateService.donateRead(vo.getDonate_id(), false)); model.addAttribute("writer", donateService.donateWriter(vo.getDonate_id())); model.addAttribute("replyList", donateService.donateReplyList(vo.getDonate_id())); return "/community/donateRead"; } // 무료나눔 댓글 삭제 @RequestMapping("donateReplyRemove") public String donateReplyRemove(Model model, @RequestParam("reply_id") Integer reply_id, @ModelAttribute("cri") SearchCriteria cri, @RequestParam("donate_id") Integer donate_id) throws Exception { donateService.replyRemove(reply_id); model.addAttribute(donateService.donateRead(donate_id, false)); model.addAttribute("writer", donateService.donateWriter(donate_id)); model.addAttribute("replyList", donateService.donateReplyList(donate_id)); return "/community/donateRead"; } // 포토리뷰 글 등록 폼 이동 @RequestMapping(value = "photoReviewRegist", method = RequestMethod.GET) public void photoReviewRegistGet(@ModelAttribute("photoCommand") PhotoVO vo) throws Exception { } // 포토리뷰 글 등록(DB) @RequestMapping(value = "photoReviewRegist", method = RequestMethod.POST) public String photoReviewRegistPost(@ModelAttribute("photoCommand") @Valid PhotoVO vo, BindingResult errors, @RequestParam("file") MultipartFile file) throws Exception { if (errors.hasErrors()) { return "/community/photoReviewRegist"; } String photo_thumbnail = UploadFileUtils.uploadFile(uploadPath, file.getOriginalFilename(), file.getBytes()); String[] photo_thumbnail1 = photo_thumbnail.split("_"); if (photo_thumbnail1.length > 2) { String photo_img = photo_thumbnail.substring(0, 12); String photo_img2 = photo_thumbnail.substring(14); vo.setPhoto_thumbnail((photo_img + photo_img2)); } photoService.photoRegist(vo); return "redirect:/community/photoReviewList"; } // 포토리뷰 List 출력 @RequestMapping("photoReviewList") public void photoList(@ModelAttribute("cri") SearchCriteria cri, Model model) throws Exception { List<PhotoVO> list = photoService.photoList(cri); HashMap<Integer, String> userMap = new HashMap<Integer, String>(); int photo_id; for (int index = 0; index < list.size(); index++) { photo_id = list.get(index).getPhoto_id(); userMap.put(photo_id, photoService.photoWriter(photo_id)); } model.addAttribute("list", list); model.addAttribute("userMap", userMap); PageMaker pageMaker = new PageMaker(); pageMaker.setCri(cri); pageMaker.setTotalCount(photoService.photoCount(cri)); model.addAttribute("pageMaker", pageMaker); } // 포토리뷰 상세보기 @RequestMapping("photoReviewRead") public void photoReviewRead(@RequestParam("photo_id") Integer photo_id, Model model, @ModelAttribute("cri") SearchCriteria cri) throws Exception { model.addAttribute(photoService.photoReviewRead(photo_id, true)); model.addAttribute("writer", photoService.photoWriter(photo_id)); } // 포토리뷰 이전 글 이동 @ResponseBody @RequestMapping(value = "photoPrev/{photo_id}", method = RequestMethod.GET) public Integer photoPrev(@PathVariable("photo_id") int photo_id) throws Exception { Integer photoId = null; if (photoService.photoPrev(photo_id) != null) { photoId = photoService.photoPrev(photo_id); } else { photoId = -1; } return photoId; } // 포토리뷰 다음 글 이동 @ResponseBody @RequestMapping(value = "photoNext/{photo_id}", method = RequestMethod.GET) public Integer photoNext(@PathVariable("photo_id") int photo_id) throws Exception { Integer photoId = null; if (photoService.photoNext(photo_id) != null) { photoId = photoService.photoNext(photo_id); } else { photoId = -1; } return photoId; } // 포토리뷰 첨부파일 추출 @RequestMapping(value = "/photoGetAttach/{photo_id}") @ResponseBody public List<String> photoGetAttach(@PathVariable("photo_id") Integer photo_id) throws Exception { return photoService.photoGetAttach(photo_id); } // 포토리뷰 수정 폼 이동 @RequestMapping(value = "photoReviewModify", method = RequestMethod.GET) public void photoReviewModifyGet(@RequestParam("photo_id") Integer photo_id, Model model, @ModelAttribute("cri") SearchCriteria cri) throws Exception { model.addAttribute(photoService.photoReviewRead(photo_id, false)); model.addAttribute("writer", photoService.photoWriter(photo_id)); } // 포토리뷰 수정(DB) @RequestMapping(value = "photoReviewModify", method = RequestMethod.POST) public String photoReviewModifyPost(RedirectAttributes rtts, PhotoVO vo, SearchCriteria cri, @RequestParam("file") MultipartFile file) throws Exception { String photo_thumbnail = UploadFileUtils.uploadFile(uploadPath, file.getOriginalFilename(), file.getBytes()); String[] photo_thumbnail1 = photo_thumbnail.split("_"); if (photo_thumbnail1.length > 2) { String photo_img = photo_thumbnail.substring(0, 12); String photo_img2 = photo_thumbnail.substring(14); vo.setPhoto_thumbnail((photo_img + photo_img2)); } photoService.photoReviewModify(vo); rtts.addAttribute("page", cri.getPage()); rtts.addAttribute("perPageNum", cri.getPerPageNum()); rtts.addAttribute("searchType", cri.getSearchType()); rtts.addAttribute("keyword", cri.getKeyword()); return "redirect:/community/photoReviewList"; } // 포토리뷰 삭제 @RequestMapping("photoReviewRemove") public String photoReviewRemove(RedirectAttributes rtts, SearchCriteria cri, @RequestParam("photo_id") Integer photo_id) throws Exception { photoService.photoReviewRemove(photo_id); rtts.addAttribute("page", cri.getPage()); rtts.addAttribute("perPageNum", cri.getPerPageNum()); rtts.addAttribute("searchType", cri.getSearchType()); rtts.addAttribute("keyword", cri.getKeyword()); return "redirect:/community/photoReviewList"; } // 포토리뷰 추천 Up @ResponseBody @RequestMapping(value = "photoHeartUp/{photo_id}", method = RequestMethod.POST) public String photoHeartUp(@PathVariable("photo_id") Integer photo_id, HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); Integer person_id = Integer.parseInt((String) session.getAttribute("person_id")); PhotoHeartVO heartVO = new PhotoHeartVO(); heartVO.setPhoto_id(photo_id); heartVO.setPerson_id(person_id); photoService.heartInsert(heartVO); return "success"; } // 포토리뷰 추천 Down @ResponseBody @RequestMapping(value = "photoHeartDown/{photo_id}", method = RequestMethod.POST) public String photoHeartDown(@PathVariable("photo_id") Integer photo_id, HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); if (session.getAttribute("person_id") != null) { Integer person_id = Integer.parseInt((String) session.getAttribute("person_id")); Integer heart_id = photoService.getHeartId(person_id, photo_id); photoService.heartDelete(heart_id); } return "success"; } }
true
045b55098dda5d6e8e4acaa7e3d0eadedf30e4ab
Java
CodeLearner-ICU/ThinkInJava
/src/main/java/thinkinjava/date5/Circle.java
UTF-8
380
3.390625
3
[]
no_license
package thinkinjava.date5; class Shape{ void draw(){ System.out.println("Shape.draw()"); } } public class Circle extends Shape{ void draw(){ System.out.println("Circle.draw()"); } public static void main(String[] args) { Shape s = new Circle(); //Circle c = (Circle) new Shape(); s.draw(); //c.draw(); } }
true
0dc7f8251f8f875873ee7bb9473b9afedaa8de90
Java
Siyabulela/Java-Assignments-2017
/CHAPTER 8/EmployeeIDArray.java
UTF-8
624
3.390625
3
[]
no_license
/*Store 20 employee ID numbers in an integer array and 20 corresponding employee last names in a String array. Use dialog boxes to accept an ID number, and display the appropriate last name. Save the application as EmployeeIDArray.java.*/ import javax.swing.JOptionPane; public class EmployeeIDArray { public static void main(String[]args) { int []IDNumbers = {}; String []names = {"","","","","","","","","","","","","","","","","","","","",""}; for(int i = 0; i < names.length; i++) { names[i] = JOptionPane.showInputDialog(null, (i + 1)+ ". Enter ID number"); } } }
true
61a5bd1b0b210fdc370a5f0160cf948e36654b96
Java
s-manannikov/job4j_threads
/src/main/java/ru/job4j/concurrent/Wget.java
UTF-8
1,704
3.265625
3
[]
no_license
package ru.job4j.concurrent; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; public class Wget implements Runnable { private final String url; private final String destination; private final int speed; public Wget(String url, String destination, int speed) { this.url = url; this.destination = destination; this.speed = speed; } @Override public void run() { try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(destination)) { byte[] dataBuffer = new byte[1024]; int bytesRead; long startTime = System.nanoTime(); while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { long endTime = System.nanoTime(); fileOutputStream.write(dataBuffer, 0, bytesRead); long elapsedTime = endTime - startTime / 1000000000; long finalTime = speed * 100L; if (elapsedTime < finalTime) { Thread.sleep(finalTime - elapsedTime); } } } catch ( IOException | InterruptedException e) { e.printStackTrace(); Thread.currentThread().interrupt(); } } public static void main(String[] args) throws InterruptedException { String url = args[0]; String destination = args[1]; int speed = Integer.parseInt(args[2]); Thread wget = new Thread(new Wget(url, destination, speed)); wget.start(); wget.join(); } }
true
bc2c38d4c3f5db6a3ca636123cff84e7eb3bc935
Java
ElectricAegis/SoftDev3LABPodSearch
/src/pod_search/model/PodcastDAOModelTest.java
UTF-8
1,213
2.59375
3
[]
no_license
package pod_search.model; public class PodcastDAOModelTest extends PodcastDAOModel { private PodcastModel[] testInsert; public PodcastDAOModelTest() { super(""); } public PodcastModel[] selectQuery(String filter) { int total = 2; if (testInsert != null) { total += testInsert.length; } PodcastModel[] testModels = new PodcastModel[total]; testModels[0] = new PodcastModel("name1","link1",1); testModels[1] = new PodcastModel("name2","link2",2); for (int i = 2; i < total; i++){ testModels[i] = testInsert[i-2]; } return testModels; } public PodcastModel[] selectAll() { return selectQuery(""); } //TODO: return 2D array of results public void insertQuery(PodcastModel podcast) { if (testInsert == null) { testInsert = new PodcastModel[1]; testInsert[0] = podcast; return; } PodcastModel[] tempInsert = new PodcastModel[1 + testInsert.length]; for (int i = 0; i < tempInsert.length-1; i++){ tempInsert[i] = testInsert[i]; } tempInsert[tempInsert.length-1] = podcast; } }
true
fe0b5b3afe04c8958eda5d47181254714b521bad
Java
kimnamo0113/jdbc_study
/src/jdbc_study/jdbc/MySQLjdbcUtil.java
UTF-8
1,085
2.59375
3
[]
no_license
package jdbc_study.jdbc; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Map.Entry; import java.util.Properties; public class MySQLjdbcUtil { // public static void main(String[] args) throws SQLException { // Connection con=getConnection(); // System.out.println(con); // System.out.println(con.getCatalog()); // } public static Connection getConnection(){ Connection con=null; try(InputStream is=ClassLoader.getSystemResourceAsStream("db.properties")){ Properties prop = new Properties(); prop.load(is); for(Entry<Object,Object> e : prop.entrySet()) { System.out.printf("%s - %s%n",e.getKey(),e.getValue()); } con=DriverManager.getConnection(prop.getProperty("url"), prop); }catch (IOException e) { System.err.println(e.getMessage()); } catch (SQLException e1) { System.err.println("해당 데이터베이스 연결정보가 잘못되었슴 확인요망한년"); } return con; } }
true
2a6acb6b9c327480262cffeb1d94ce6c762fbfba
Java
peavers-archive/terrible-api-service
/src/main/java/io/terrible/api/controller/SearchController.java
UTF-8
893
1.859375
2
[]
no_license
/* Licensed under Apache-2.0 */ package io.terrible.api.controller; import io.terrible.api.domain.MediaFile; import io.terrible.api.services.SearchService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.*; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @Slf4j @CrossOrigin @RestController @RequestMapping("/search") @RequiredArgsConstructor public class SearchController { private final SearchService searchService; @GetMapping("/index") public Mono<String> index() { return searchService.createIndex("media").then(searchService.populate("media")); } @GetMapping public Flux<MediaFile> search(@RequestParam final String query) { return searchService.search(query); } @DeleteMapping public Mono<Void> deleteAll() { return searchService.deleteIndex(); } }
true
608f86140f7eb1e08fdd29b8e4efb474b75fbf70
Java
OscarMiddagh/Gestion-de-usuarios-UMSS
/src/main/java/com/qualityhunters/Model/DetPerRol.java
UTF-8
996
2.421875
2
[]
no_license
package com.qualityhunters.Model; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; @Entity public class DetPerRol { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long idDetalle; @ManyToOne(optional = false, fetch = FetchType.EAGER) private Rol rol; @ManyToOne(optional = false, fetch = FetchType.EAGER) private Permiso permiso; protected DetPerRol(){} public DetPerRol(Rol rol,Permiso permiso){ this.rol=rol; this.permiso=permiso; } public void setRol(Rol rol){ this.rol=rol; } public void setPermiso(Permiso permiso){ this.permiso=permiso; } public Long getId(){ return idDetalle; } public Rol getRol(){ return rol; } public Permiso getPermiso(){ return permiso; } }
true
ed94c53890c192a3129c3f8266e2a1417f6a948d
Java
kkjy0519/bouncycastle
/Crypto/SimpleSymmetricExample.java
UTF-8
2,051
2.78125
3
[]
no_license
import java.security.Security; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import org.bouncycastle.jce.provider.BouncyCastleProvider; public class SimpleSymmetricExample { public static void main(String args[]) throws Exception { Security.addProvider(new BouncyCastleProvider()); byte[] input = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 }; byte[] keyBytes = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, }; byte[] ivBytes = new byte[] { 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00}; SecretKeySpec key = new SecretKeySpec(keyBytes, "AES"); IvParameterSpec iv = new IvParameterSpec(ivBytes); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC"); System.out.println("input : " + Utils.toHexString(input)); cipher.init(Cipher.ENCRYPT_MODE, key, iv); byte[] output = new byte[cipher.getOutputSize(input.length)]; int processLen; processLen = cipher.update(input, 0, input.length, output, 0); processLen += cipher.doFinal(output, processLen); System.out.println("output : " +Utils.toHexString(output)); cipher.init(Cipher.DECRYPT_MODE, key, iv); byte[] plainText = new byte[cipher.getOutputSize(output.length)]; int decryptedLen = cipher.update(output, 0, output.length, plainText,0); decryptedLen += cipher.doFinal(plainText, decryptedLen); System.out.println ("plaintext :" + Utils.toHexString(plainText,decryptedLen)); //modification } //modify
true
a58f5bb0a89e189f1834ee80c0afd4bc7aff5794
Java
huuhan2507/C1020G1-Tranhuuhan
/Module2/Java/src/ss11_dsa_queue_stack/exercise/PalindromeCheck.java
UTF-8
1,163
4.125
4
[]
no_license
package ss11_dsa_queue_stack.exercise; import java.util.Deque; import java.util.LinkedList; import java.util.Scanner; import java.util.Stack; public class PalindromeCheck { public static void main(String[] args) { Scanner input = new Scanner( System.in ); System.out.println( "Enter your string: " ); String string = input.nextLine(); if (isPalindrome( string )) { System.out.println( "This is palindrome" ); } else { System.out.println( "This is not palindrome" ); } } public static boolean isPalindrome(String string) { Stack<Character> stack = new Stack<>(); Deque<Character> queue = new LinkedList<>(); boolean isPalindrome = false; for (int i = 0; i < string.length(); i++) { stack.push( string.charAt( i ) ); queue.add( string.charAt( i ) ); } while (!stack.isEmpty()) { if (stack.pop()== queue.poll() ) { isPalindrome = true; } else { isPalindrome = false; break; } } return isPalindrome; } }
true
9616d74c66ab3ffbc3cae8322db1434c4fbcf3e5
Java
billee1011/LGameQiPai
/LCommModule/src/main/java/com/module/SortType.java
UTF-8
505
2.5
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.module; /** * 排序类型 * * @author leroy */ public enum SortType { /** * 升序 */ Asc(1), /** * 降序 */ Desc(2); private SortType(int key) { this.key = key; } private final int key; public int getKey() { return key; } }
true
50a482af88b5dd7911c6cc4b4efadbb4caa5138c
Java
nipulgurupatel/optmay2016
/opt-may-2016/dayana/com/chapter4/assignment4/Developer.java
UTF-8
629
3.265625
3
[]
no_license
package com.chapter4.assignment4; public class Developer extends Employee { private String technology; public Developer() { super(); } public Developer(String firstName, String lastName, int employeeId, String salary, String role, String technology) { super(firstName, lastName, employeeId, salary, role); this.technology = technology; } public void jobDescription() { System.out.println(" Developer designs and code and develops the software in" + this.technology); } public void accessToCode() { System.out.println("Developer has access to code in" + this.technology); } }
true
f189acc6f370a5ba9dc4a0833134bb097489f2a5
Java
camearle20/Monopoly
/src/net/came20/monopoly/run/server/RunServer.java
UTF-8
1,761
2.015625
2
[]
no_license
package net.came20.monopoly.run.server; import net.came20.camecommand.CameCommand; import net.came20.camecommand.command.Command; import net.came20.camecommand.command.DefaultCommands; import net.came20.camecommand.parameter.Parameter; import net.came20.camecommand.parameter.ParameterNone; import net.came20.monopoly.command.AnnounceWrapper; import net.came20.monopoly.command.join.Join; import net.came20.monopoly.command.join.parameter.JoinAnnounceParameter; import net.came20.monopoly.command.join.parameter.JoinReplyParameter; import net.came20.monopoly.command.join.parameter.JoinRequestParameter; import net.came20.monopoly.common.Player; import net.came20.monopoly.common.data.Expense; import net.came20.monopoly.run.server.manager.BankManager; import net.came20.monopoly.run.server.manager.PlayerManager; import net.came20.monopoly.run.server.manager.RealEstateManager; import net.came20.monopoly.run.server.manager.TradeManager; import net.came20.monopoly.run.server.sequence.PlayerJoinSequence; import org.zeromq.ZMQ; /** * Created by cameronearle on 12/27/16. */ public class RunServer implements Runnable { @Override public void run() { //RUN INIT ON ALL MANAGERS BankManager.init(); PlayerManager.init(); RealEstateManager.init(); TradeManager.init(); //CONNECT SOCKETS CommSocket.init(); //Initialize the comm socket, binding it to this thread. CommSocket.connect("tcp://*:8100"); AnnounceSocket announceSocket = new AnnounceSocket("tcp://*:8101"); Thread announceSocketThread = new Thread(announceSocket); announceSocketThread.start(); PlayerJoinSequence.joinPlayers(1); //Join 1 player, we now have a valid registered player } }
true
a09874b7cb7396c2dea024005a491bef07087787
Java
Autilite/News-With-Reddit
/app/src/main/java/com/autilite/newswithreddit/util/ThumbnailUtil.java
UTF-8
776
2.609375
3
[]
no_license
package com.autilite.newswithreddit.util; import com.autilite.newswithreddit.R; /** * Created by kelvin on 6/9/15. */ public class ThumbnailUtil { /** * Returns the resource id of the static reddit thumbnails. * @param thumbnail * The thumbnail resource to retrieve * @return * The resource id of the thumbnail or -1 if it doesn't apply */ public static int getStaticThumbnail(String thumbnail) { switch (thumbnail) { case "nsfw": return R.drawable.nsfw2; case "self": case "default": return R.drawable.self_default2; case "": return R.drawable.noimage; default: return -1; } } }
true
f8919b7fdb290fd0ffc0049eb15cc1c6eacec974
Java
RyanFu/AndroidCamera2Focus
/app/src/main/java/com/example/openandroid/view/focus/FocusViewController.java
UTF-8
8,346
2.15625
2
[]
no_license
package com.example.openandroid.view.focus; import android.app.Activity; import android.graphics.RectF; import android.util.Log; import android.widget.FrameLayout; import com.example.openandroid.ICameraImp; import com.example.openandroid.R; import com.example.openandroid.util.Camera2Utils; /** * The focus controller interacts with the focus UI. */ public class FocusViewController { private static final int ORIENTATION_UNKNOWN = -1; private FocusView mFocusView; private Activity mActivity; private RectF mPreviewRect = new RectF(); private ICameraImp mICameraImp; private FrameLayout mFeatureRootView; /** * Constructor of focus view. * * @param iCameraImp The application app level controller */ public FocusViewController(final ICameraImp iCameraImp) { mICameraImp = iCameraImp; mActivity = mICameraImp.getActivity(); } public void setRootView(FrameLayout frameLayout){ mFeatureRootView = frameLayout; } /** * Show a passive focus animation at the center of the active area. */ public void showPassiveFocusAtCenter() { Log.d("showPassive","showPassiveFocusAtCenter------------------------------>"); mActivity.runOnUiThread(new Runnable() { @Override public void run() { Log.d("showPassive","mFocusView--------------->"+mFocusView); if (mFocusView == null) { return; } makeSureViewOnTree(); setFocusLocation(mFeatureRootView.getWidth() / 2, mFeatureRootView.getHeight() / 2); mFocusView.startPassiveFocus(); mFocusView.centerFocusLocation(); } }); } /** * Show an active focus animation at the given viewX and viewY position. * This is normally initiated by the user touching the screen at a given * point. * <p> * * @param viewX the view's x coordinate * @param viewY the view's y coordinate */ public void showActiveFocusAt(final int viewX, final int viewY) { Log.d("addFocusView","mFocusViewController showActiveFocusAt-----------------"); if (mFocusView == null) { return; } makeSureViewOnTree(); mActivity.runOnUiThread(new Runnable() { @Override public void run() { setFocusLocation(viewX, viewY); mFocusView.setFocusLocation(viewX, viewY); mFocusView.startActiveFocus(); } }); } /** * Stop any currently executing focus animation. */ public void stopFocusAnimations() { mActivity.runOnUiThread(new Runnable() { @Override public void run() { if (mFocusView == null) { return; } makeSureViewOnTree(); Log.d("stopFocusAnimations","stopFocusAnimations---------------------------->"); mFocusView.stopFocusAnimations(); } }); } public void clearFocusUi() { mActivity.runOnUiThread(new Runnable() { @Override public void run() { if (mFocusView == null) { return; } makeSureViewOnTree(); mFocusView.clearFocusUi(); } }); } public void highlightFocusView() { mActivity.runOnUiThread(new Runnable() { @Override public void run() { if (mFocusView == null) { return; } makeSureViewOnTree(); mFocusView.highlightFocusView(); } }); } public void lowlightFocusView() { mActivity.runOnUiThread(new Runnable() { @Override public void run() { if (mFocusView == null) { return; } makeSureViewOnTree(); mFocusView.lowlightFocusView(); } }); } public void addFocusView() { mActivity.runOnUiThread(new Runnable() { @Override public void run() { Log.d("addFocusView","addFocusView-------------------->"+mFeatureRootView); // focus view may inflate by other instance or exposure view. mFocusView = (FocusView) mFeatureRootView.findViewById(R.id.focus_view); if (mFocusView == null) { mFocusView = (FocusView) mActivity.getLayoutInflater().inflate(R.layout.focus_view, mFeatureRootView,false); mFeatureRootView.addView(mFocusView); } mFocusView.setPreviewRect(mPreviewRect); int orientation = mFocusView.getOrientation(); if (orientation != ORIENTATION_UNKNOWN) { int compensation = Camera2Utils.getDisplayRotation(mActivity); orientation = orientation + compensation; Camera2Utils.rotateViewOrientation(mFocusView, orientation, false); } else { Log.d("FocusviewC", "[addFocusView] unknown orientation"); } setFocusLocation(mFeatureRootView.getWidth() / 2, mFeatureRootView.getHeight() / 2); Log.d("touch_view", "[addFocusView] unknown getWidth="+mFeatureRootView.getWidth() / 2); Log.d("touch_view", "[addFocusView] unknown getWidth="+mFeatureRootView.getHeight() / 2); } }); } public void removeFocusView() { mActivity.runOnUiThread(new Runnable() { @Override public void run() { if (mFocusView != null) { mFeatureRootView.removeView(mFocusView); mFocusView = null; } } }); } public IFocusView.FocusViewState getFocusState() { if (mFocusView == null) { return IFocusView.FocusViewState.STATE_IDLE; } makeSureViewOnTree(); return mFocusView.getFocusState(); } public void onPreviewChanged(RectF previewRect) { mPreviewRect = previewRect; if (mFocusView != null) { mFocusView.setPreviewRect(previewRect); } } public boolean isReadyTodoFocus() { if (mFocusView == null) { return false; } if (mFocusView.getWidth() == 0 || mFocusView.getHeight() == 0) { return false; } return true; } public boolean isActiveFocusRunning() { if (mFocusView == null) { return false; } return mFocusView.isActiveFocusRunning(); } public void setOrientation(final int orientation) { mActivity.runOnUiThread(new Runnable() { @Override public void run() { if (mFocusView == null) { return; } int compensation = Camera2Utils.getDisplayRotation(mActivity); final int compensationOrientation = orientation + compensation; Camera2Utils.rotateViewOrientation(mFocusView, compensationOrientation, true); } }); } public void setFocusLocation(int x, int y) { Log.d("setFocusLocation","setFocusLocation----->"+x+" mFocusViewY---"+y); if (mFocusView == null) { return; } // Use margin to set the focus indicator to the touched area. FrameLayout.LayoutParams p = (FrameLayout.LayoutParams) mFocusView.getLayoutParams(); int left = 0; int top = 0; left = x - mFocusView.getWidth() / 2; top = y - mFocusView.getHeight() / 2; p.setMargins(left, top, 0, 0); mFocusView.requestLayout(); } /** * Make sure focus view be added to root view when it is not null. */ public void makeSureViewOnTree() { // All focus and exposure are share one View, PIP may don't ensure add-remove life cycle. if (mFeatureRootView.findViewById(R.id.focus_view) == null && mFocusView != null) { mFeatureRootView.addView(mFocusView); } } }
true
c823f1a56666ae758fc8ea8e52ade4c64cf52b86
Java
project-ncl/bacon
/pig/src/test/java/org/jboss/pnc/bacon/pig/impl/addons/quarkus/QuarkusCommunityDepAnalyzerTest.java
UTF-8
3,006
1.6875
2
[ "Apache-2.0" ]
permissive
package org.jboss.pnc.bacon.pig.impl.addons.quarkus; import org.assertj.core.util.Files; import org.jboss.pnc.bacon.config.Config; import org.jboss.pnc.bacon.config.ConfigProfile; import org.jboss.pnc.bacon.config.DaConfig; import org.jboss.pnc.bacon.config.PigConfig; import org.jboss.pnc.bacon.pig.impl.PigContext; import org.jboss.pnc.bacon.pig.impl.config.Flow; import org.jboss.pnc.bacon.pig.impl.config.PigConfiguration; import org.jboss.pnc.bacon.pig.impl.config.RepoGenerationData; import org.jboss.pnc.bacon.pig.impl.documents.Deliverables; import org.jboss.pnc.bacon.pig.impl.repo.RepositoryData; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.File; import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static java.util.Arrays.asList; public class QuarkusCommunityDepAnalyzerTest { public static final String REPO_ZIP_PATH = null; public static final String INDY_URL = null; public static final String DA_URL = null; @Test @Disabled void test() { File tempFolder = Files.newTemporaryFolder(); System.out.println(tempFolder.getAbsolutePath()); File extras = new File(tempFolder, "extras"); extras.mkdir(); RepositoryData repositoryData = new RepositoryData(); repositoryData.setRepositoryPath(Paths.get(REPO_ZIP_PATH)); PigContext context = new PigContext(); PigConfiguration pigConfig = new PigConfiguration(); Flow flow = new Flow(); RepoGenerationData repositoryGeneration = new RepoGenerationData(); repositoryGeneration.setBomArtifactId("quarkus-bom"); flow.setRepositoryGeneration(repositoryGeneration); pigConfig.setFlow(flow); Map<String, Map<String, ?>> addons = new HashMap<>(); Map<String, Object> depAnalyzerConfig = new HashMap<>(); depAnalyzerConfig .put("skippedExtensions", asList("quarkus-resteasy-reactive-kotlin", "quarkus-mongodb-client")); addons.put(QuarkusCommunityDepAnalyzer.NAME, depAnalyzerConfig); pigConfig.setAddons(addons); context.setPigConfiguration(pigConfig); context.setRepositoryData(repositoryData); PigContext.setInstance(context); Config instance = new Config(); ConfigProfile configProfile = new ConfigProfile(); PigConfig pig = new PigConfig(); pig.setIndyUrl(INDY_URL); configProfile.setPig(pig); DaConfig da = new DaConfig(); da.setUrl(DA_URL); configProfile.setDa(da); instance.setActiveProfile(configProfile); Config.setInstance(instance); QuarkusCommunityDepAnalyzer analyzer = new QuarkusCommunityDepAnalyzer( pigConfig, Collections.emptyMap(), tempFolder.getAbsolutePath(), extras.getAbsolutePath(), new Deliverables()); analyzer.trigger(); } }
true
c3ce7703666dfee81cf4840934f931df7677d931
Java
udbhavgarg/E-dac2020
/Assignment_01 By Udbhav_Garg/assg_12.java
UTF-8
283
2.515625
3
[]
no_license
import java.util.Scanner; public class assg_12 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int i, j,k; i = sc.nextInt(); j = sc.nextInt(); k=sc.nextInt(); int avg=(i+j+k)/3; System.out.print(avg); sc.close(); } }
true
1dd32c9487ffe49369e04da3d0eeff57f242be15
Java
Ho-Lee-Schitt/ConcurrentAssign2
/src/Question2/MathServerHttp.java
UTF-8
908
2.46875
2
[]
no_license
package Question2; /** * Created by cgf13hun on 07/04/2017. */ import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.net.InetSocketAddress; import java.util.logging.Level; import java.util.logging.Logger; public class MathServerHttp { // static logger public static final Logger LOG = Logger.getLogger(MathServerHttp.class.getName()); // start web server public static void main(String[] args) throws Exception { try { HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); LOG.info("HTTP: Server started."); server.createContext("/calc", new MathContextHandler()); server.setExecutor(null); // creates a default executor server.start(); } catch (IOException ex) { LOG.log(Level.ALL, ex.getMessage()); } } // end main } // MathServerHttp
true
bf9894800e38d60f3f8e2374c8524eae11026b7b
Java
theunreplicated/coloradocollegegame
/ElementStack.java
UTF-8
1,285
3.546875
4
[]
no_license
public class ElementStack<K> { private LinkedHolder<K> first = null; public synchronized void push(K _newElement) { LinkedHolder<K> newElement = new LinkedHolder<K>(_newElement); if(first == null) { first = newElement; first.next = first.prev = first; } else { first.insertBefore(newElement); first = newElement; } } public synchronized void unshift(K _newElement) { LinkedHolder<K> newElement = new LinkedHolder<K>(_newElement); if(first == null) { first = newElement; first.next = first.prev = first; } else { first.insertBefore(newElement); } } @SuppressWarnings("unchecked") public synchronized K pop() { if(first == null) return null; LinkedHolder<K> popped = first; if(first.next == first) { first = null; } else { first = first.next; popped.removeFromList(); } return popped.get(); } @SuppressWarnings("unchecked") public synchronized int size() { int i = 0; if(first == null) return 0; LinkedHolder<K> current = first; do { i++; /** * current.next * Type safety: The expression of tyhpe LinkedHolder needs * unchecked conversion to conform to LinkedHolder<K> */ }while( (current = (LinkedHolder<K>) current.next) != first); return i; } }
true
ade457e8647cc33a8c4d94fd3caa946a8ee577e7
Java
iondv/ion-old-java-version-20140819
/liquibase-service-plugin/src/com/svcdelivery/liquibase/eclipse/v3/LiquibaseServiceV3.java
UTF-8
6,534
1.6875
2
[ "Apache-2.0" ]
permissive
package com.svcdelivery.liquibase.eclipse.v3; import java.io.File; import java.io.IOException; import java.sql.Connection; import java.util.ArrayList; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import liquibase.CatalogAndSchema; import liquibase.Liquibase; import liquibase.change.CheckSum; import liquibase.changelog.RanChangeSet; import liquibase.database.Database; import liquibase.database.DatabaseConnection; import liquibase.database.DatabaseFactory; import liquibase.database.jvm.JdbcConnection; import liquibase.diff.DiffGeneratorFactory; import liquibase.diff.DiffResult; import liquibase.diff.compare.CompareControl; import liquibase.diff.output.DiffOutputControl; import liquibase.diff.output.changelog.DiffToChangeLog; import liquibase.exception.LiquibaseException; import liquibase.resource.FileSystemResourceAccessor; import liquibase.resource.ResourceAccessor; import liquibase.servicelocator.CustomResolverServiceLocator; import liquibase.servicelocator.PackageScanClassResolver; //import liquibase.servicelocator.CustomResolverServiceLocator; //import liquibase.servicelocator.PackageScanClassResolver; import liquibase.servicelocator.ServiceLocator; import liquibase.snapshot.DatabaseSnapshot; import liquibase.snapshot.SnapshotControl; import liquibase.snapshot.SnapshotGeneratorFactory; import org.eclipse.core.runtime.Platform; import org.osgi.framework.BundleContext; import com.svcdelivery.liquibase.eclipse.api.ChangeSetItem; import com.svcdelivery.liquibase.eclipse.api.LiquibaseApiException; import com.svcdelivery.liquibase.eclipse.api.LiquibaseService; public class LiquibaseServiceV3 implements LiquibaseService { /** * Service activator. * * @param ctx * The bundle context. */ public void activate(BundleContext ctx) { PackageScanClassResolver resolver = new LbPluginClassResolver(Platform.getBundle("liquibase.core")); ServiceLocator.setInstance(new CustomResolverServiceLocator(resolver)); /*PackageScanClassResolver resolver = new EmbeddedJarPackageScanClassResolver(Platform.getBundle("liquibase.eclipse.ui")); ServiceLocator.setInstance(new CustomResolverServiceLocator(resolver));*/ } public void deactivate(BundleContext ctx) { ServiceLocator.reset(); } public List<ChangeSetItem> getRanChangeSets(Connection connection) throws LiquibaseApiException { List<ChangeSetItem> items = new ArrayList<ChangeSetItem>(); try { final DatabaseConnection database = new JdbcConnection(connection); Database targetDb = DatabaseFactory.getInstance() .findCorrectDatabaseImplementation(database); List<RanChangeSet> changeSets = targetDb.getRanChangeSetList(); for (RanChangeSet changeSet : changeSets) { ChangeSetItem item = new ChangeSetItem(); item.setAuthor(changeSet.getAuthor()); item.setChangeLog(changeSet.getChangeLog()); item.setDateExecuted(changeSet.getDateExecuted()); item.setExecType(changeSet.getExecType().name()); item.setId(changeSet.getId()); CheckSum lastCheckSum = changeSet.getLastCheckSum(); if (lastCheckSum != null) { item.setLastCheckSum(lastCheckSum.toString()); } item.setTag(changeSet.getTag()); items.add(item); } } catch (LiquibaseException e) { throw new LiquibaseApiException(e); } return items; } public void dropAll(Connection connection, String schema) throws LiquibaseApiException { try { final DatabaseConnection database = new JdbcConnection(connection); Database targetDb = DatabaseFactory.getInstance() .findCorrectDatabaseImplementation(database); CatalogAndSchema cas = new CatalogAndSchema(schema, schema); targetDb.dropDatabaseObjects(cas); } catch (Exception e) { throw new LiquibaseApiException(e); } } public void update(final File changeLogFile, final Connection connection) throws LiquibaseApiException { try { final ResourceAccessor resourceAccessor = new FileSystemResourceAccessor( changeLogFile.getParent()); final DatabaseConnection database = new JdbcConnection(connection); final Liquibase lb = new Liquibase(changeLogFile.getName(), resourceAccessor, database); lb.update(""); } catch (Exception e) { throw new LiquibaseApiException(e); } } public void diff(final Connection connection, final String schema, final File target) throws LiquibaseApiException { try { final DatabaseConnection database = new JdbcConnection(connection); Database targetDb = DatabaseFactory.getInstance() .findCorrectDatabaseImplementation(database); String snapshotTypes = null; SnapshotControl snapshotControl = new SnapshotControl(targetDb, snapshotTypes); CompareControl compareControl = new CompareControl( new CompareControl.SchemaComparison[] { new CompareControl.SchemaComparison( new CatalogAndSchema(null, schema), new CatalogAndSchema(null, schema)) }, snapshotTypes); // diffOutputControl.setDataDir(dataDir); DatabaseSnapshot originalDatabaseSnapshot = SnapshotGeneratorFactory .getInstance() .createSnapshot( compareControl .getSchemas(CompareControl.DatabaseRole.REFERENCE), targetDb, snapshotControl); DiffResult diffResult = DiffGeneratorFactory .getInstance() .compare( originalDatabaseSnapshot, SnapshotGeneratorFactory .getInstance() .createSnapshot( compareControl .getSchemas(CompareControl.DatabaseRole.REFERENCE), null, snapshotControl), compareControl); if (target.exists()) { target.delete(); } DiffOutputControl diffOutputControl = new DiffOutputControl(); DiffToChangeLog dtc = new DiffToChangeLog(diffResult, diffOutputControl); dtc.print(target.getPath()); } catch (LiquibaseException e) { throw new LiquibaseApiException(e); } catch (IOException e) { throw new LiquibaseApiException(e); } catch (ParserConfigurationException e) { throw new LiquibaseApiException(e); } } public void rollback(File changeLogFile, int count, Connection connection) throws LiquibaseApiException { try { final ResourceAccessor resourceAccessor = new FileSystemResourceAccessor( changeLogFile.getParent()); final DatabaseConnection database = new JdbcConnection(connection); final Liquibase lb = new Liquibase(changeLogFile.getName(), resourceAccessor, database); lb.rollback(count, ""); } catch (LiquibaseException e) { throw new LiquibaseApiException(e); } } }
true
88da3de73c54a53dce2908790bd1153d2bd4dae1
Java
tomelf/Entree-Android
/app/src/main/java/edu/purdue/entreemobile/entreeproject/util/db/CacheImageHelper.java
UTF-8
2,773
2.28125
2
[ "Apache-2.0" ]
permissive
package edu.purdue.entreemobile.entreeproject.util.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by kane on 3/9/15. */ public class CacheImageHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "cache.db"; public static final int DATABASE_ID_IMAGE_CACHE = 1; public static final int DATABASE_ID_QUERY_CACHE = 2; public static final String IMAGE_CACHE_TABLE_NAME = "CacheImage"; public static final String IMAGE_CACHE_COLUMN_URL = "url"; public static final String IMAGE_CACHE_COLUMN_FILENAME = "filename"; public static final String IMAGE_CACHE_COLUMN_TIME = "time"; public static final String QUERY_RESULT_TABLE_NAME = "CacheQuery"; public static final String QUERY_RESULT_COLUMN_QUERYURL = "queryurl"; public static final String QUERY_RESULT_COLUMN_RESULT = "result"; public static final String QUERY_RESULT_COLUMN_TIME = "time"; private static final String IMAGE_CACHE_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS "+IMAGE_CACHE_TABLE_NAME+"("+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"+ IMAGE_CACHE_COLUMN_URL+" VARCHAR,"+ IMAGE_CACHE_COLUMN_FILENAME+" VARCHAR,"+ IMAGE_CACHE_COLUMN_TIME+" TIMESTAMP DEFAULT CURRENT_TIMESTAMP);"; private static final String IMAGE_CACHE_DELETE_TABLE = "DROP TABLE IF EXISTS "+IMAGE_CACHE_TABLE_NAME; private static final String QUERY_CACHE_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS "+QUERY_RESULT_TABLE_NAME+"("+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"+ QUERY_RESULT_COLUMN_QUERYURL+" VARCHAR,"+ QUERY_RESULT_COLUMN_RESULT+" VARCHAR,"+ QUERY_RESULT_COLUMN_TIME+" TIMESTAMP DEFAULT CURRENT_TIMESTAMP);"; private static final String QUERY_CACHE_DELETE_TABLE = "DROP TABLE IF EXISTS "+QUERY_RESULT_TABLE_NAME; private int databaseId; public CacheImageHelper(Context context, int databaseId) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.databaseId = databaseId; } public void onCreate(SQLiteDatabase db) { db.execSQL(IMAGE_CACHE_CREATE_TABLE); db.execSQL(QUERY_CACHE_CREATE_TABLE); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(IMAGE_CACHE_DELETE_TABLE); db.execSQL(QUERY_CACHE_DELETE_TABLE); onCreate(db); } public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } }
true
5aa52456bae0a90854835d6b7877e02c346ac303
Java
kamleshbadgujar/POC
/src/main/java/com/poc/service/RestApiCall.java
UTF-8
244
1.804688
2
[]
no_license
package com.poc.service; import java.util.Map; import org.springframework.stereotype.Service; @Service public interface RestApiCall { public void callRestApi(String url, String method); public Map<String, String> getResponseMap(); }
true
e2f9e08a89aeeb43908c81bd0e9e3be027e23b32
Java
Jhenerson/banksys
/src/login/LoginFuncionario.java
UTF-8
758
2.40625
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 login; import entidades.Funcionario; import persistencia.PFuncionario; /** * * @author rodolpho.repezza */ public class LoginFuncionario extends Login { @Override public boolean logar(String cpf, String senha) { boolean acesso = false; try { PFuncionario pf = new PFuncionario(); Funcionario f = pf.consultar(cpf); if(f.getSenha().equals(senha)) { acesso = true; } } catch (Exception e) { e.printStackTrace(); } return acesso; } }
true
b4f712df1228bcf5103e29014151b74847571692
Java
coderandyli/dynamic-thread-pool
/dtp-admin/src/main/java/com/coderandyli/dtp/monitor/alert/notification/UrgencyNotification.java
UTF-8
737
2.265625
2
[]
no_license
package com.coderandyli.dtp.monitor.alert.notification; import com.coderandyli.dtp.monitor.alert.sender.MsgSender; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; /** * 【紧急】通知 * - send email * * @Date 2021/8/26 3:25 下午 * @Created by lizhenzhen */ @Component("urgencyNotification") public class UrgencyNotification extends Notification{ @Autowired public UrgencyNotification(@Qualifier("emailMsgSender") MsgSender msgSender) { super(msgSender); } @Override public void notify(String msg) { this.msgSender.send("【Urgency alert】" + msg); } }
true