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
5e141c5d7525a605606168f394e3d44adc46d4a0
Java
anujaKumthekar/InventoryManagementSystem
/MaterialService/src/main/java/com/accenture/lkm/controller/MaterialController.java
UTF-8
2,126
2.546875
3
[]
no_license
package com.accenture.lkm.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import com.accenture.lkm.business.bean.MaterialCategoryBean; import com.accenture.lkm.service.MaterialService; @RestController public class MaterialController { /* * Autowire the MaterialService object * * */ @Autowired private MaterialService service; @GetMapping("/") public String index() { return "Welcome to Spring Boot Material Service API!"; } /* * Method - getMaterialCategories() * Fetch all the material categories details using MaterialService and store it inside a List * Return a ResponseEntity object passing the list of material categories * */ @GetMapping(value = "/material/controller/getMaterialCategories", produces=MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<List<MaterialCategoryBean>> getMaterialCategories() { List<MaterialCategoryBean> categoryBeansList=service.getMaterialCategories(); return new ResponseEntity<List<MaterialCategoryBean>>(categoryBeansList, HttpStatus.OK); } /* * Method - getMaterialCategoryById() * Fetch a single MaterialCategoryBean using MaterialService object and passing --> categoryId * Return a ResponseEntity object passing the MaterialCategoryBean object * */ @GetMapping(value = "/material/controller/getMaterialCategoryById/{categoryId}", produces=MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<MaterialCategoryBean> getMaterialCategoryById(@PathVariable String categoryId) { MaterialCategoryBean categoryBeans=service.getMaterialCategoryById(categoryId); return new ResponseEntity<MaterialCategoryBean>(categoryBeans, HttpStatus.OK); } }
true
84820a2c456c9894ea777b274f437071e72f40a9
Java
rzs840707/Analysis-of-Clustering-Algorithms
/K-means/src/main/java/JavaKMeansExample.java
UTF-8
5,299
2.625
3
[]
no_license
package my.spark; import java.util.regex.Pattern; import java.util.*; import java.io.*; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.function.Function; import org.apache.spark.mllib.clustering.KMeans; import org.apache.spark.mllib.clustering.KMeansModel; import org.apache.spark.mllib.linalg.Vector; import org.apache.spark.mllib.linalg.Vectors; public class JavaKMeansExample { public static void main(String[] args) throws IOException { SparkConf conf = new SparkConf().setAppName("JavaKMeansExample"); JavaSparkContext jsc = new JavaSparkContext(conf); String path = "/home/vpinnaka/HDFS-K-means/K-means/Phones_accelerometer.txt"; File file =new File("out.txt"); file.createNewFile(); long starttime = System.nanoTime(); FileWriter writer = new FileWriter(file); JavaRDD<String> data = jsc.textFile(path); JavaRDD<Vector> parsedData = data.map( new Function<String, Vector>() { public Vector call(String s) { String[] sarray = s.split(","); String decimalPattern = "([0-9]*)\\.([0-9]*)"; double[] values = new double[12]; for (int i = 0; i < sarray.length; i++) { if(i==0) continue; boolean match = Pattern.matches(decimalPattern, sarray[i]); if(match) values[i-1] = Double.parseDouble(sarray[i]); else { if(i == 6 || i == 8 || i==7){ continue; } /* else if(i == 7) { if(sarray[i].equals("nexus4")) { values[6] = 1.0; values[7] = 0.0; values[8] = 0.0; values[9] = 0.0; values[10] = 0.0; } else if(sarray[i].equals("s3")) { values[6] = 0.0; values[7] = 1.0; values[8] = 0.0; values[9] = 0.0; values[10] = 0.0; } else if(sarray[i].equals("s3mini")) { values[6] = 0.0; values[7] = 0.0; values[8] = 1.0; values[9] = 0.0; values[10] = 0.0; } else if(sarray[i].equals("samsungold")) { values[6] = 0.0; values[7] = 0.0; values[8] = 0.0; values[9] = 1.0; values[10] = 0.0; } else{ values[6] = 0.0; values[7] = 0.0; values[8] = 0.0; values[9] = 0.0; values[10] = 1.0; } } */ else if(i == 9) { if(sarray[i].equals("bike")) { values[5] = 1.0; values[6] = 0.0; values[7] = 0.0; values[8] = 0.0; values[9] = 0.0; values[10] = 0.0; values[11] = 0.0; } else if(sarray[i].equals("sit")) { values[5] = 0.0; values[6] = 1.0; values[7] = 0.0; values[8] = 0.0; values[9] = 0.0; values[10] = 0.0; values[11] = 0.0; } else if(sarray[i].equals("stand")) { values[5] = 0.0; values[6] = 0.0; values[7] = 1.0; values[8] = 0.0; values[9] = 0.0; values[10] = 0.0; values[11] = 0.0; } else if(sarray[i].equals("walk")) { values[5] = 0.0; values[6] = 0.0; values[7] = 0.0; values[8] = 1.0; values[9] = 0.0; values[10] = 0.0; values[11] = 0.0; } else if(sarray[i].equals("stairsup")) { values[5] = 0.0; values[6] = 0.0; values[7] = 0.0; values[8] = 0.0; values[9] = 1.0; values[10] = 0.0; values[11] = 0.0; } else if(sarray[i].equals("stairsdown")) { values[5] = 0.0; values[6] = 0.0; values[7] = 0.0; values[8] = 0.0; values[9] = 0.0; values[10] = 1.0; values[11] = 0.0; } else if(sarray[i].equals("null")) { values[5] = 0.0; values[6] = 0.0; values[7] = 0.0; values[8] = 0.0; values[9] = 0.0; values[10] = 0.0; values[11] = 1.0; } } } } return Vectors.dense(values); } } ); parsedData.cache(); int numClusters = 2; int numIterations = 5; //for(;numClusters < 7;numClusters++) //{ KMeansModel clusters = KMeans.train(parsedData.rdd(), numClusters, numIterations); System.out.println("Cluster centers:"); writer.write("Cluster centers:"); for (Vector center: clusters.clusterCenters()) { System.out.println(" " + center); writer.write(" " + center); } double cost = clusters.computeCost(parsedData.rdd()); System.out.println("Cost: " + cost); writer.write("Cost: " + cost); double WSSSE = clusters.computeCost(parsedData.rdd()); System.out.println("Within Set Sum of Squared Errors = " + WSSSE); writer.write("Within Set Sum of Squared Errors = " + WSSSE); //} //clusters.save(jsc.sc(), "target/"); //KMeansModel sameModel = KMeansModel.load(jsc.sc(), // "target/org/apache/spark/JavaKMeansExample/KMeansModel"); writer.flush(); writer.close(); jsc.stop(); } }
true
11d2f24b015c3d6665e04e343776f2b214137103
Java
gilglick/2Learn
/app/src/main/java/com/example/a2learn/model/Student.java
UTF-8
3,637
2.625
3
[]
no_license
package com.example.a2learn.model; import com.google.firebase.firestore.Exclude; import java.util.ArrayList; import java.util.List; @SuppressWarnings("WeakerAccess") public class Student { private String fullName; private String email; private String phoneNumber; private String dateOfBirth; private String academicInstitution; private String uri; private List<String> giveHelpList; private List<String> needHelpList; public Student() { } public Student(String fullName, String email, String academicInstitution, String dateOfBirth, String phoneNumber) { this.fullName = fullName; this.email = email; this.dateOfBirth = dateOfBirth; this.phoneNumber = phoneNumber; this.academicInstitution = academicInstitution; this.uri = ""; giveHelpList = new ArrayList<>(); needHelpList = new ArrayList<>(); } public String getFullName() { return fullName; } public String getEmail() { return email; } public String getDateOfBirth() { return dateOfBirth; } public String getPhoneNumber() { return phoneNumber; } public String setAcademicInstitution(){ return academicInstitution; } public List<String> getGiveHelpList() { return giveHelpList; } public List<String> getNeedHelpList() { return needHelpList; } public void setGiveHelpList(List<String> giveHelpList) { this.giveHelpList = giveHelpList; } public void setNeedHelpList(List<String> needHelpList) { this.needHelpList = needHelpList; } public void setDateOfBirth(String dateOfBirth) { this.dateOfBirth = dateOfBirth; } public void setFullName(String fullName) { this.fullName = fullName; } public void setAcademicInstitution(String academicInstitution) { this.academicInstitution = academicInstitution; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getAcademicInstitution() { return academicInstitution; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + email.hashCode(); return result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return email.equals(student.email); } @Exclude public String getUserNeedHelpListStringFormat() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < needHelpList.size(); i++) { if (i == needHelpList.size() - 1) { sb.append(needHelpList.get(i)); } else { sb.append(needHelpList.get(i)); sb.append(System.getProperty("line.separator")); } } return sb.toString(); } @Exclude public String getUserOfferListStringFormat() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < giveHelpList.size(); i++) { if (i == giveHelpList.size() - 1) { sb.append(giveHelpList.get(i)); } else { sb.append(giveHelpList.get(i)); sb.append(System.getProperty("line.separator")); } } return sb.toString(); } public void setUri(String uri) { this.uri = uri; } public String getUri() { return uri; } }
true
d777962f90d92b6c105914ffacecd52c5d1a726b
Java
soldiergit/science-innovate
/science-innovate-admin/src/main/java/com/soldier/modules/business/service/TeacherInfoService.java
UTF-8
1,777
2.078125
2
[ "Apache-2.0" ]
permissive
package com.soldier.modules.business.service; import com.baomidou.mybatisplus.extension.service.IService; import com.soldier.common.utils.PageUtils; import com.soldier.modules.business.entity.TeacherInfoEntity; import java.util.Collection; import java.util.List; import java.util.Map; /** * 教师信息 * @author soldier * @email 583403411@qq.com * @date 2020-05-28 10:33:27 */ public interface TeacherInfoService extends IService<TeacherInfoEntity> { PageUtils queryPage(Map<String, Object> params); /** * 教师业绩支撑选择负责人或者成员,为全体教师 * @return key:教师id;value:教师姓名-所属二级学院名称 */ List<TeacherInfoEntity> select(); /** * 超级管理员或学校管理员:选择教师,用于添加学院或教研室的成员和负责人 */ List<TeacherInfoEntity> adminSelect(); /** * 根据用户id查询教师工号及姓名 */ TeacherInfoEntity queryTeacherCodeAndNameByUserId(String userId); /** * 根据用户id查询教师id */ Long queryTeaIdByUserId(Long userId); /** * 根据所属二级学院及teacherIds查询列表,当stuIds为空是查询全部 */ List<TeacherInfoEntity> queryListByDeptAndIds(Long deptId, List<Long> teacherIds); /** * 批量添加教师 * @param teacherInfoEntities 教师数据 * @param userId 当前用户id */ List<TeacherInfoEntity> insertBatch(List<TeacherInfoEntity> teacherInfoEntities, Long userId); /** * 批量删除教师 * @param teaIds 教师id * @param userIds 教师对应的用户id */ void deleteBatch(List<Long> teaIds, List<Long> userIds); TeacherInfoEntity details(Long teacherId); }
true
bc77aea19328162b48163af2fa4723f3f00133b8
Java
wuwei152/Dzbp
/app/src/main/java/com/md/dzbp/utils/GlideImageLoader.java
UTF-8
960
2.3125
2
[]
no_license
package com.md.dzbp.utils; import android.content.Context; import android.widget.ImageView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.md.dzbp.R; /** * Created by Administrator on 2019/2/12. */ public class GlideImageLoader { // @Override extends ImageLoader // public void displayImage(Context context, Object path, ImageView imageView) { // // //Glide 加载图片简单用法 // Glide.with(context).load((String) path).error(R.drawable.pic_not_found).diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView); // // } // // //提供createImageView 方法,如果不用可以不重写这个方法,主要是方便自定义ImageView的创建 // @Override // public ImageView createImageView(Context context) { // RoundRectImageView simpleDraweeView = new RoundRectImageView(context); // return simpleDraweeView; // } }
true
6b5f68d0dcabace87046c6c9b4055b608625421f
Java
Glyphoid/math-handwriting-lib
/src/main/java/me/scai/handwriting/utils/DataIOHelper.java
UTF-8
1,453
3.09375
3
[ "Apache-2.0" ]
permissive
package me.scai.handwriting.utils; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.List; public class DataIOHelper { public static void printFloatDataToCsvFile(List<float[]> data, File f) { PrintWriter pw = null; try { pw = new PrintWriter(f); for (float[] dataRow : data) { for (int i = 0; i < dataRow.length; ++i) { pw.printf("%.9f", dataRow[i]); if (i < dataRow.length - 1) { pw.print(","); } } pw.print("\n"); } } catch (IOException e) { throw new RuntimeException(e.getMessage()); } finally { pw.close(); } } public static void printLabelsDataToOneHotCsvFile(List<Integer> labels, int nLabels, File f) { PrintWriter pw = null; try { pw = new PrintWriter(f); for (int label : labels) { for (int i = 0; i < nLabels; ++i) { pw.print(i == label ? "1" : "0"); if (i < nLabels - 1) { pw.print(","); } } pw.print("\n"); } } catch (IOException e) { throw new RuntimeException(e.getMessage()); } finally { pw.close(); } } }
true
2e286e58e78889d9515f8f8cfb8a784b9223e8e7
Java
moutainhigh/KayunPay
/KayunPay/src/com/dutiantech/model/Deposit.java
UTF-8
583
2.1875
2
[]
no_license
package com.dutiantech.model; public class Deposit { public enum authorization { PAYMENT_AUTH { public String val() { return "PAYMENT"; } public String desc() { return "缴费授权"; } }, PASSWORD_SET { public String val() { return "PWD"; } public String desc() { return "交易密码"; } }, CARD_BIND { public String val() { return "CARD"; } public String desc() { return "绑卡关系"; } }; public abstract String val(); public abstract String desc(); } }
true
9dcecafe55c3ecdb032ec64cd5d0ffcc6f10f5ea
Java
konczak/MyStartupApp
/src/main/java/pl/konczak/mystartupapp/web/restapi/questionnairetemplate/QuestionnaireTemplate.java
UTF-8
3,328
2.203125
2
[]
no_license
package pl.konczak.mystartupapp.web.restapi.questionnairetemplate; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.time.LocalDateTime; import java.util.Locale; import org.springframework.hateoas.ResourceSupport; import pl.konczak.mystartupapp.domain.employee.dto.EmployeeSnapshot; import pl.konczak.mystartupapp.domain.question.dto.QuestionnaireTemplateSnapshot; import com.fasterxml.jackson.annotation.JsonView; @ApiModel public class QuestionnaireTemplate extends ResourceSupport { @JsonView(View.Summary.class) private final Long questionnaireTemplateId; @JsonView(View.Summary.class) private final String name; @JsonView(View.Summary.class) private final Long authorId; @JsonView(View.Summary.class) private final Long updatedBy; @JsonView(View.Summary.class) private final LocalDateTime createdAt; @JsonView(View.Summary.class) private final LocalDateTime updatedAt; @JsonView(View.Summary.class) private final Locale language; @JsonView(View.List.class) private Employee employee; public QuestionnaireTemplate(QuestionnaireTemplateSnapshot questionnaireTemplateSnapshot) { this.questionnaireTemplateId = questionnaireTemplateSnapshot.getId(); this.name = questionnaireTemplateSnapshot.getName(); this.authorId = questionnaireTemplateSnapshot.getAuthorId(); this.updatedBy = questionnaireTemplateSnapshot.getUpdatedBy(); this.createdAt = questionnaireTemplateSnapshot.getCreatedAt(); this.updatedAt = questionnaireTemplateSnapshot.getUpdatedAt(); this.language = questionnaireTemplateSnapshot.getLanguage(); } public QuestionnaireTemplate(QuestionnaireTemplateSnapshot questionnaireTemplateSnapshot, EmployeeSnapshot employeeSnapshot) { this(questionnaireTemplateSnapshot); this.employee = new Employee(employeeSnapshot); } @ApiModelProperty( value = "Unique identifier of Questionnaire Template", required = true) public Long getQuestionnaireTemplateId() { return questionnaireTemplateId; } @ApiModelProperty( value = "Name of Questionnaire Template", required = true) public String getName() { return name; } @ApiModelProperty( value = "Unique identifier of Employee who created Questionnaire Template", required = true) public Long getAuthorId() { return authorId; } @ApiModelProperty( value = "Unique identifier of Employee who last updated Questionnaire Template", required = true) public Long getUpdatedBy() { return updatedBy; } @ApiModelProperty( value = "Date of Questionnaire Template creation", required = true) public LocalDateTime getCreatedAt() { return createdAt; } @ApiModelProperty( value = "Date of Questionnaire Template last update", required = true) public LocalDateTime getUpdatedAt() { return updatedAt; } @ApiModelProperty( value = "Language of Questionnaire Template", required = true) public Locale getLanguage() { return language; } @ApiModelProperty( value = "Employee who created or edited Questionnaire Template", required = true) public Employee getEmployee() { return employee; } }
true
470166775a82524129d4ecc72f5f590176c1ec00
Java
CactusCata/SignGenerator
/SignGenerator/src/fr/cactuscata/mcjson/MCClickEvent.java
UTF-8
1,160
2.796875
3
[]
no_license
package fr.cactuscata.mcjson; import fr.cactuscata.signgenerator.Utils; public class MCClickEvent { private MCClickAction action; private String value; public boolean equals(Object obj) { if (obj == null) return false; if (!(obj instanceof MCClickEvent)) return false; MCClickEvent event = (MCClickEvent) obj; return (event.action == this.action) && (event.value.equals(this.value)); } public String toString() { String json = "{"; json += Utils.createSafeString("\"action\"", this.action, true); json += Utils.createSafeString("\"value\"", this.value, true); json = Utils.removeLastComma(json); json += "}"; return json; } public MCClickAction getAction() { return this.action; } public void setAction(MCClickAction action) { this.action = action; } public String getValue() { return this.value; } public void setValue(String value) { this.value = value; } public MCClickEvent(MCClickAction action, String value) { this.action = action; this.value = value; } public MCClickEvent copy() { return new MCClickEvent(this.action, this.value); } }
true
adf423042be6821c924c35ff640fee40b7b48828
Java
liushiyun8/AppCust
/src/com/eke/cust/adapter/MenuAdapter.java
UTF-8
2,082
2.375
2
[]
no_license
package com.eke.cust.adapter; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.eke.cust.R; public class MenuAdapter extends BaseAdapter { Context context; LayoutInflater inflater; public List<MenuEntity> datalist = new ArrayList<MenuEntity>(); public MenuAdapter(Context context, List<MenuEntity> datalist) { this.context = context; inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.datalist = datalist; } public final class ViewHolder { public TextView tv; public ImageView iv1; public ImageView iv2; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); LayoutInflater mInflater = LayoutInflater.from(context); convertView = mInflater.inflate(R.layout.menulisttext, null); holder.tv = (TextView) convertView.findViewById(R.id.tv); holder.iv1 = (ImageView) convertView.findViewById(R.id.iv1); holder.iv2 = (ImageView) convertView.findViewById(R.id.iv2); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } MenuEntity menuentity = datalist.get(position); holder.tv.setText(menuentity.text); holder.iv1.setImageResource(menuentity.image); return convertView; } public void addWdItem(MenuEntity branch) { datalist.add(branch); } public void resetData() { // datalist.clear(); notifyDataSetChanged(); } public int getCount() { // return datalist.size(); return datalist.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public static class MenuEntity { public int image; public String text; public MenuEntity(int image, String text) { this.image = image; this.text = text; } } }
true
d654c409ef9ec6be114bf369b7ec1eb797e038b7
Java
einoorish/internet_provider_project
/src/main/java/controller/SaveTariff.java
UTF-8
2,142
2.484375
2
[]
no_license
package controller; import java.io.IOException; import java.math.BigDecimal; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import constants.Fields; import constants.URL; import dao.TariffDao; import dao.impl.TariffDaoImpl; import model.Tariff; import model.TariffType; public class SaveTariff extends HttpServlet { private static final long serialVersionUID = -5577566949314653715L; private final static Logger LOG = Logger.getLogger(SaveTariff.class.getSimpleName()); protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { TariffDao dao = new TariffDaoImpl(); if(request.getParameter("remove")!=null) { dao.delete(Long.valueOf(request.getParameter("remove"))); LOG.debug("Done removing tariff"); } response.sendRedirect(URL.REDIRECT_HOME); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.info("POST started"); TariffDao dao = new TariffDaoImpl(); LOG.debug(request.getParameter(Fields.TARIFF_TITLE_UK)); String title = request.getParameter(Fields.TARIFF_TITLE); String title_uk = request.getParameter(Fields.TARIFF_TITLE_UK); BigDecimal price = new BigDecimal(request.getParameter(Fields.TARIFF_PRICE)); TariffType type = TariffType.valueOf(request.getParameter(Fields.TARIFF_TYPE)); String description = request.getParameter(Fields.TARIFF_DESCRIPTION); String description_uk = request.getParameter(Fields.TARIFF_DESCRIPTION_UK); if(request.getParameter(Fields.TARIFF_ID)!=null) { long id = Long.valueOf(request.getParameter(Fields.TARIFF_ID)); dao.update(new Tariff(id, title, title_uk, type, price, description, description_uk)); LOG.debug("Done updating tariff"); } else { dao.insert(new Tariff(title, title_uk, type, price, description, description_uk)); LOG.debug("Done adding tariff"); } doGet(request, response); } }
true
27360cb77096afed0062b7cc4e14cedf942fa013
Java
dennisdegryse/rfcomm-sms
/src/be/dennisdegryse/rfcommsms/sms/Cursor.java
UTF-8
1,029
2.328125
2
[]
no_license
package be.dennisdegryse.rfcommsms.sms; import java.util.Date; /** * * @author Dennis Degryse <dennisdegryse@gmail.com> */ public class Cursor { private final android.database.Cursor wrappedCursor; protected Cursor(android.database.Cursor cursor) { this.wrappedCursor = cursor; } public final void close() { wrappedCursor.close(); } public final boolean moveToFirst() { return wrappedCursor.moveToFirst(); } public final boolean moveToNext() { return wrappedCursor.moveToNext(); } public final Sms read() { return new Sms( wrappedCursor.getInt(wrappedCursor.getColumnIndexOrThrow("_id")), wrappedCursor.getInt(wrappedCursor.getColumnIndexOrThrow("thread_id")), wrappedCursor.getInt(wrappedCursor.getColumnIndexOrThrow("read")) == 1, wrappedCursor.getString(wrappedCursor.getColumnIndexOrThrow("address")), new Date(wrappedCursor.getLong(wrappedCursor.getColumnIndexOrThrow("date"))), wrappedCursor.getString(wrappedCursor.getColumnIndexOrThrow("body"))); } }
true
d548d4eed556879dc784545299fc2c37f3915a82
Java
Bsandeep07/Codevita_Solutions
/Base6.java
UTF-8
1,050
3.671875
4
[]
no_license
import java.util.Scanner; public class Base6 { public static void main(String[] args) { //taking input Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int[] mainSequence = new int[n]; int[] derivedSequence = new int[n]; for (int i = 0; i < n; i++) { mainSequence[i] = scanner.nextInt(); //converting main to base6 int number = mainSequence[i]; int sum = 0; while (number > 0) { sum = sum + (number % 6); number =number / 6; } derivedSequence[i] = sum; } //comparing elements int inversions = 0; for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { if (derivedSequence[i] > derivedSequence[j]) { inversions++; } } } System.out.print(inversions); } }
true
118dbbfcee395a7e5186aa754634d19b1e55841a
Java
taphalow/PizzaPatronFabrique
/src/factories/FactoryUSA.java
UTF-8
735
2.390625
2
[]
no_license
package factories; import abstractFactory.AbstractFactory; import abstractProduits.AbstractOriental; import abstractProduits.AbstractReines; import abstractProduits.AbstractTroisFormages; import produits.OrientalUSA; import produits.ReinesUSA; import produits.TroisFromagesUSA; public class FactoryUSA extends AbstractFactory { @Override public AbstractOriental createProductOriental() { // TODO Auto-generated method stub return new OrientalUSA(); } @Override public AbstractReines createProductReines() { // TODO Auto-generated method stub return new ReinesUSA(); } @Override public AbstractTroisFormages createProductTroisFromages() { // TODO Auto-generated method stub return new TroisFromagesUSA(); } }
true
980179b9c15b2ce3b09eabb303650b0f281dca10
Java
bedatadriven/appengine-hibernate
/it/src/main/java/com/bedatadriven/appengine/cloudsql/LogResources.java
UTF-8
1,630
2.21875
2
[ "Apache-2.0" ]
permissive
package com.bedatadriven.appengine.cloudsql; import com.google.appengine.api.log.LogQuery; import com.google.appengine.api.log.LogService; import com.google.appengine.api.log.LogServiceFactory; import com.google.appengine.api.log.RequestLogs; import com.google.appengine.api.modules.ModulesService; import com.google.appengine.api.modules.ModulesServiceFactory; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import java.io.PrintWriter; import java.io.StringWriter; import java.util.concurrent.TimeUnit; @Path("/logs") public class LogResources { @GET @Path("/pending") @Produces("text/plain") public String getMedianPendingTime() { LogService logService = LogServiceFactory.getLogService(); LogQuery logQuery = LogQuery.Builder.withIncludeAppLogs(false) .startTimeMillis(System.currentTimeMillis() - TimeUnit.SECONDS.toMillis(60)) .endTimeMillis(System.currentTimeMillis()); StringBuilder content = new StringBuilder(); content.append("request.id,loading,pending,latency,mcycles\n"); Iterable<RequestLogs> logs = logService.fetch(logQuery); for (RequestLogs log : logs) { content.append(log.getRequestId()).append(","); content.append(log.isLoadingRequest() ? "TRUE" : "FALSE").append(","); content.append(log.getPendingTimeUsec()).append(","); content.append(log.getLatencyUsec()).append(","); content.append(log.getMcycles()); content.append("\n"); } return content.toString(); } }
true
3a978c93565bc30d19892fc633f7ea574138ce20
Java
xiang1912/Sunshine
/App/Java/app/src/main/java/com/example/tonjies/templateproject/module/weather/presenter/WeatherPresenter.java
UTF-8
1,879
2.484375
2
[]
no_license
package com.example.tonjies.templateproject.module.weather.presenter; import com.example.common.util.L; import com.example.tonjies.templateproject.module.weather.bean.Weather; import com.example.tonjies.templateproject.module.weather.model.WeatherModel; import com.example.tonjies.templateproject.module.weather.presenter.contract.WeatherContract; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; /** * Created by 舍长 on 2019/1/5 * describe: */ public class WeatherPresenter implements WeatherContract.WeatherIPresenter { private WeatherContract.WeatherView weatherView; private WeatherModel weatherModel; public WeatherPresenter(WeatherContract.WeatherView weatherView) { this.weatherView = weatherView; weatherModel = new WeatherModel(); } //请求网络数据 @Override public void requestWeather(final String weatherId) { L.d("requestWeather"); weatherModel.requestWeather(weatherId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Weather>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(Weather weather) { L.d("获取到的天气信息:" + weatherId); weatherView.getData(weather); } @Override public void onError(Throwable e) { L.d("----"+e.toString()); } @Override public void onComplete() { } }); } }
true
4091a3debfeafbaed570dd62236258ca64269ebc
Java
suongisme/Java_Basic
/src/theory/generic/InheritGenericAnothorClass.java
UTF-8
417
2.921875
3
[]
no_license
package theory.generic; public class InheritGenericAnothorClass<K, V, N> extends GenericClass<K,V>{ private N something; public InheritGenericAnothorClass(K key, V value, N something) { super(key, value); this.something = something; } public N getSomething() { return something; } public void setSomething(N something) { this.something = something; } }
true
bb9565d634b5331c6329560f49c577372ffd3f79
Java
Fate787/DA_Auction
/java/com/ImYourFate/Intake/require.java
UTF-8
524
2.34375
2
[]
no_license
package play.dahp.us.intake; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Annotates a method that requires a permission check to be satisfied before * it can be executed by the caller. */ @Retention(RetentionPolicy.RUNTIME) public @interface Require { /** * A list of permissions, evaluated as a union of the permissions to * test whether the caller is permitted to use the command * * @return a list of permissions */ String[] value(); }
true
45e308a6c711d4bdcb962c9827167135a3ac0c4a
Java
haloer111/lift
/src/main/java/com/gexiao/lift/config/SpringMvcConfig.java
UTF-8
4,870
2.21875
2
[]
no_license
package com.gexiao.lift.config; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.AbstractHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.client.RestTemplate; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; /** * Spring MVC 配置类(注入FastJson) * * @author : lzx * Created by lzx on 18/12/10. */ @Configuration public class SpringMvcConfig implements WebMvcConfigurer { /** * 添加跨域支持 */ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedHeaders("*") .allowedOrigins("*") .allowedMethods("*") .allowCredentials(true) .maxAge(3600L); } /** * 跨域配置 * spring boot 配置跨域的坑 https://segmentfault.com/a/1190000018018849 */ @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", corsConfig()); return new CorsFilter(source); } private CorsConfiguration corsConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); corsConfiguration.setAllowCredentials(true); corsConfiguration.setMaxAge(3600L); return corsConfiguration; } /** * 注入restTemplate(移除jackson并设置fastJson作为解析) */ @Bean public RestTemplate restTemplate() { return new RestTemplate() {{ List<HttpMessageConverter<?>> messageConverters = getMessageConverters(); messageConverters.removeIf(next -> next instanceof MappingJackson2HttpMessageConverter); messageConverters.add(fastJsonConverter()); }}; } /** * 添加拦截器 * * @param registry */ @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor()).addPathPatterns("/**"); } /** * 注入拦截器给spring管理,不然无法读取配置文件 */ @Bean public LoginInterceptor loginInterceptor() { return new LoginInterceptor(); } /** * 设置编码,解决中文乱码 */ @Bean public StringHttpMessageConverter stringHttpMessageConverter() { return new StringHttpMessageConverter(StandardCharsets.UTF_8); } /** * 添加到内置转换器之后(移除jackson,使用fastJson) */ @Override public void extendMessageConverters(List<HttpMessageConverter<?>> converters) { converters.removeIf(next -> next instanceof MappingJackson2HttpMessageConverter); converters.add(fastJsonConverter()); } /** * 配置fastJson */ private AbstractHttpMessageConverter fastJsonConverter() { final FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter(); final FastJsonConfig config = new FastJsonConfig(); config.setSerializerFeatures(SerializerFeature.IgnoreErrorGetter); config.setCharset(StandardCharsets.UTF_8); config.setDateFormat("yyyy-MM-dd HH:mm:ss"); fastJsonConverter.setFastJsonConfig(config); //spring要求Content-Type不能含有通配符,fastJson默认为MediaType.ALL不可使用,这应该是一种保护机制,并强制用户自己配置MediaType List<MediaType> supportedMediaTypes = new ArrayList<>(); supportedMediaTypes.add(MediaType.APPLICATION_JSON); supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8); fastJsonConverter.setSupportedMediaTypes(supportedMediaTypes); return fastJsonConverter; } }
true
a99af3bdc7b88b803bbc400c56337dcd4e70450e
Java
seNpAi-code/weatherForcast
/src/com/company/WindDirection.java
UTF-8
998
2.890625
3
[]
no_license
package com.company; public class WindDirection { protected Double latitude; protected Double longitude; private String weather; private Double temp; private String windDirection; private String precipitation; public WindDirection(double latitude, double longitude) { this.latitude = latitude; this.longitude = longitude; } public String getWeather() { return weather; } public void setWeather(String weather) { this.weather = weather; } public Double getTemp() { return temp; } public void setTemp(Double temp) { this.temp = temp; } public String getWindDirection() { return windDirection; } public void setWindDirection(String windDirection) { this.windDirection = windDirection; } public String getPrecipitation() { return precipitation;} public void setPrecipitation(String precipitation) { this.precipitation = precipitation; } }
true
e1cf8ba0540655e33edd8975d4e437c2e05bd5b6
Java
Paladin1412/device-manager
/src/test/java/com/baidu/iot/devicecloud/devicemanager/TestAddr.java
UTF-8
775
2.328125
2
[ "Apache-2.0" ]
permissive
package com.baidu.iot.devicecloud.devicemanager; import org.junit.Test; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; /** * Created by Yao Gang (yaogang@baidu.com) on 2019/3/28. * * @author <a href="mailto:yaogang AT baidu DOT com">Yao Gang</a> */ public class TestAddr { @Test public void testAddr() { String[] items = new String[]{"10.173.51.160", "8260"}; try { InetSocketAddress random = new InetSocketAddress(InetAddress.getByName(items[0]), Integer.valueOf(items[1])); System.out.println(random.toString()); System.out.println(random.getAddress().getHostAddress()); } catch (UnknownHostException e) { e.printStackTrace(); } } }
true
bbd2423169d45b50d6af3669b547649cd9712d49
Java
wjl7123093/RTZHDJ
/app/src/main/java/com/mytv/rtzhdj/di/component/MainComponent.java
UTF-8
423
1.632813
2
[]
no_license
package com.mytv.rtzhdj.di.component; import com.jess.arms.di.scope.ActivityScope; import dagger.Component; import com.jess.arms.di.component.AppComponent; import com.mytv.rtzhdj.di.module.MainModule; import com.mytv.rtzhdj.mvp.ui.activity.MainActivity; @ActivityScope @Component(modules = MainModule.class, dependencies = AppComponent.class) public interface MainComponent { void inject(MainActivity activity); }
true
d27340b26f7fab55367a27f88febec3fd75259bf
Java
LongRongZai/second_hand_shop
/src/main/java/com/shop/config/ShopProperties.java
UTF-8
428
1.578125
2
[]
no_license
package com.shop.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.List; @ConfigurationProperties(prefix = "shop") @Data public class ShopProperties { //无需验证的路由 private List<String> loginInterceptorExcludePath; //附件保存地址 private String attachSavePath; //附件预览地址 private String attachViewPath; }
true
e2df47b41b684ea00677f1a59c60316e52d39d86
Java
Kira332/fleamarket
/flea/src/main/java/com/market/service/AdminService.java
UTF-8
383
1.9375
2
[]
no_license
package com.market.service; import com.market.Dao.AdminDao; import com.market.pojo.Admin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class AdminService { @Autowired AdminDao adminDao; public Admin findByUsername(String username){ return adminDao.findByUsername(username); } }
true
a17934dc5a91d4ce27f27afe9db0802b01fbd529
Java
Boom618/LeetCode
/src/easy/LastWordLength.java
UTF-8
981
3.859375
4
[]
no_license
package easy; /** * Created by boomhe on 2018/2/28. */ public class LastWordLength { /** * 从一个只包含大小字母和空格字符的字符串中得到最后一个单词的长度 * * @param args */ public static void main(String[] args) { LastWordLength main = new LastWordLength(); String s = "Hello World"; int length = main.lastWordLength(s); System.out.println("最后一位单词的长度是 :" + length); } /** * 思路:总长度减去 遍历不为空的字符位置、 * * @param s * @return */ public int lastWordLength(String s) { int p = s.length() - 1; while (p >= 0 && s.charAt(p) == ' ') { p--; } int end = p; while (p >= 0 && s.charAt(p) != ' ') { p--; } // API 实现 // return s.trim().length() - s.trim().lastIndexOf(" ") - 1; return end - p; } }
true
2783e9ad2008a889fd85c0290f673a1f27d684b2
Java
yuktiyatish/Audio-Recorder
/app/src/main/java/com/scribie/recorder/audiorecorder/MainActivity.java
UTF-8
12,464
1.671875
2
[]
no_license
package com.scribie.recorder.audiorecorder; import android.content.ClipData; import android.content.Context; import android.content.Intent; import android.media.MediaRecorder; import android.net.Uri; import android.os.Handler; import android.support.design.widget.TabLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.media.MediaPlayer; import android.util.AttributeSet; import android.util.Base64; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.TabHost; import android.widget.Toast; import android.os.Environment; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.common.api.GoogleApiClient; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestParams; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.File; import java.io.IOException; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private static String mFileName = null; private Menu option_menu; private MenuItem menuItem; private MediaRecorder mMediaRecorder = null; private MediaPlayer mMediaPlayer = null; private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder"; boolean b_play_enable = true; boolean b_record_enable = true; boolean b_resume = false; private int current_pos = 0; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ //private GoogleApiClient client; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMediaRecorder = new MediaRecorder(); mMediaPlayer = new MediaPlayer(); final ImageButton img_record_btn = (ImageButton) findViewById(R.id.imageButton); final ImageButton img_play_btn = (ImageButton) findViewById(R.id.play_pause_imageButton); // final Button img_record_btn = (Button) findViewById(R.id.recordstop); // final Button img_play_btn = (Button) findViewById(R.id.playpause); img_record_btn.setEnabled(true); img_play_btn.setEnabled(false); img_record_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { System.out.println("brecord ename:" + b_record_enable); img_play_btn.setEnabled(false); // img_play_btn.setImageDrawable(R.drawable.ic // Toast.makeText(getApplicationContext(), " Recording Started " + getFilename(), Toast.LENGTH_SHORT).show(); if (b_record_enable) { if(mMediaPlayer.isPlaying()){ mMediaPlayer.stop(); mMediaPlayer.release(); } System.out.println("Hi 123"); mMediaRecorder = new MediaRecorder(); mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); mFileName = getFilename(); mMediaRecorder.setOutputFile(mFileName); mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); try { System.out.println("Hi 123 prepare"); mMediaRecorder.prepare(); mMediaRecorder.start(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } b_record_enable = false; // img_record_btn.setText("Stop"); System.out.println("Hi 123 false"); Toast.makeText(getApplicationContext(), "Recording Started", Toast.LENGTH_LONG).show(); } else { System.out.println("Hi 123 else"); mMediaRecorder.stop(); // mMediaRecorder.release(); //mMediaRecorder = null; b_record_enable=true; Toast.makeText(getApplicationContext(), "Recording Ended", Toast.LENGTH_LONG).show(); img_play_btn.setEnabled(true); img_record_btn.setEnabled(true); //img_record_btn.setText("Record"); b_play_enable = true; current_pos=0; } } }); img_play_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) throws IllegalArgumentException, SecurityException, IllegalStateException { if (b_play_enable) { img_record_btn.setEnabled(false); try { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource(mFileName); mMediaPlayer.prepare(); mMediaPlayer.seekTo(current_pos); mMediaPlayer.start(); } catch (IOException e) { e.printStackTrace(); } b_play_enable=false; b_record_enable= true; img_record_btn.setEnabled(true); //img_play_btn.setText("Pause"); //checkplaying(mMediaPlayer); Toast.makeText(getApplicationContext(), "Playing audio", Toast.LENGTH_LONG).show(); } else { current_pos = mMediaPlayer.getCurrentPosition(); mMediaPlayer.pause(); //mMediaPlayer.release(); //mMediaPlayer = null; b_play_enable=true; img_record_btn.setEnabled(true); b_record_enable = true; // img_play_btn.setText("Play"); } if(!mMediaPlayer.isPlaying()) img_record_btn.setEnabled(true); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu,menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.all_recorded_files: return true; case R.id.uploaded_files: getUploadedFiles(); return true; default: return super.onOptionsItemSelected(item); } } public void getUploadedFiles(){ AsyncHttpClient client = new AsyncHttpClient(); client.addHeader( "Authorization", "Basic " + Base64.encodeToString( ("4df3c042f94717a3906e47dfe2e784e5f3ace901" + ":" + "").getBytes(), Base64.NO_WRAP) ); client.get("https://api.scribie.com/v1/files", new AsyncHttpResponseHandler() { // When the response returned by REST has Http response code '200' @Override public void onSuccess(String response) { // JSON Object JSONArray arr = null; ArrayList<String> arrlst = new ArrayList<String>(); try { arr = new JSONArray(response); for (int i = 0; i < arr.length(); i++) { JSONObject obj = arr.getJSONObject(i); System.out.println("Object" + obj.getString("id")); arrlst.add((String) (obj.getString("id"))); } Utility utils = Utility.getInstance(); utils.setArrListHistory(arrlst); navigatetoHistoryActivity(); } catch (JSONException e) { e.printStackTrace(); } } // When the response returned by REST has Http response code other than '200' @Override public void onFailure(int statusCode, Throwable error, String content) { // Hide Progress Dialog //prgDialog.hide(); // When Http response code is '404' if (statusCode == 404) { Toast.makeText(getApplicationContext(), "Requested resource not found" + content, Toast.LENGTH_LONG).show(); error.printStackTrace(); } // When Http response code is '500' else if (statusCode == 500) { Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show(); } // When Http response code other than 404, 500 else { System.out.println(statusCode); Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show(); } } }); } private String getFilename() { String filepath = Environment.getExternalStorageDirectory().getPath(); File file = new File(filepath, AUDIO_RECORDER_FOLDER); if (!file.exists()) { file.mkdirs(); } return (file.getAbsolutePath() + "/" + System.currentTimeMillis() + ".3gp"); } public void navigatetoHistoryActivity() { Intent historyIntent = new Intent(getApplicationContext(), FileHistoryActivity.class); historyIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(historyIntent); } /* @Override public void onStart() { super.onStart(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.scribie.recorder.audiorecorder/http/host/path") ); AppIndex.AppIndexApi.start(client, viewAction); } @Override public void onStop() { super.onStop(); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. Action viewAction = Action.newAction( Action.TYPE_VIEW, // TODO: choose an action type. "Main Page", // TODO: Define a title for the content shown. // TODO: If you have web page content that matches this app activity's content, // make sure this auto-generated web page URL is correct. // Otherwise, set the URL to null. Uri.parse("http://host/path"), // TODO: Make sure this auto-generated app deep link URI is correct. Uri.parse("android-app://com.scribie.recorder.audiorecorder/http/host/path") ); AppIndex.AppIndexApi.end(client, viewAction); client.disconnect(); }*/ @Override public void onDestroy(){ super.onDestroy(); mMediaPlayer.release(); mMediaPlayer.release(); } }
true
88870e8393930202e391e67c45b8965d07f9f95e
Java
missaouib/livelance
/src/main/java/livelance/app/service/impl/JpaProfileService.java
UTF-8
3,413
2.28125
2
[ "MIT" ]
permissive
package livelance.app.service.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import livelance.app.model.Profile; import livelance.app.model.list.ProfileList; import livelance.app.repository.ProfileRepository; import livelance.app.service.ProfileService; @Service @Transactional public class JpaProfileService implements ProfileService { private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired ProfileRepository profileRepository; @Override public ProfileList findAll() { logger.info("> findAll"); ProfileList profiles = new ProfileList(profileRepository.findAll()); logger.info("< findAll"); return profiles; } @Override @Cacheable(value = "profiles", key = "#id") public Profile findOne(Long id) { logger.info("> findOne id:{}", id); Profile profile = profileRepository.findOne(id); if (profile == null) { logger.error("Profile not found."); } logger.info("< findOne id:{}", profile.getFirstname()); return profile; } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) @CacheEvict(value = "profiles", key = "#id") public Profile delete(Long id) { logger.info("> delete id:{}", id); Profile found = findOne(id); if (found == null) { logger.error("Attempted to delete a Profile, but the entity does not exist."); } else { profileRepository.delete(found); } logger.info("< delete id:{}", id); return found; } @Override @Transactional(propagation = Propagation.REQUIRED, readOnly = false) @CachePut(value = "profiles", key = "#result.id") public Profile save(Profile profile) { logger.info("> save"); if(profile == null) { return null; } Profile savedProfile = profileRepository.save(profile); if (savedProfile == null) { logger.error("Profile not saved."); } logger.info("< save"); return savedProfile; } @Override @Cacheable(value = "profiles", key="#namePart1.concat('-').concat(#namePart2)") public ProfileList findByFirstNameAndLastName(String namePart1, String namePart2) { logger.info("> findByFirstNameAndLastName namePart1:{}, namePart2:{}", namePart1, namePart2); ProfileList profiles = new ProfileList (profileRepository.findByFirstNameAndLastName(namePart1, namePart2)); logger.info("< findByFirstNameAndLastName namePart1:{}, namePart2:{}", namePart1, namePart2); return profiles; } @Override @Cacheable(value = "profiles", key = "#name") public ProfileList findByNameLike(String name) { logger.info("> findByNameLike name:{}", name); ProfileList profiles = new ProfileList(profileRepository.findByNameLike("%" + name + "%")); logger.info("< findByNameLike name:{}", name); return profiles; } @Override @CacheEvict( value = "profiles", allEntries = true) public void evictCache() { logger.info("> evictCache"); logger.info("< evictCache"); } }
true
a24c626b2d7fed3a41263fcf836539c070386f21
Java
ani03sha/Algorithms
/src/main/java/org/redquark/algorithms/datastructures/lists/ArrayList.java
UTF-8
7,112
4.09375
4
[ "MIT" ]
permissive
package org.redquark.algorithms.datastructures.lists; import java.util.Arrays; import java.util.Iterator; public class ArrayList<T> implements List<T>, Iterable<T> { // Default capacity of the list private static final int DEFAULT_CAPACITY = 1 << 3; // 8; // Internal array to store the elements private Object[] elements; // Represents length of the list, count of total elements in the list private int length; // Represents capacity of the list private int capacity; public ArrayList() { this(DEFAULT_CAPACITY); } public ArrayList(int capacity) { this.capacity = capacity; this.elements = new Object[this.capacity]; } /** * Size of the list * * @return number of elements in the list */ @Override public int size() { return this.length; } /** * Checks if the list is empty * * @return true, if there are no elements in the list, false otherwise */ @Override public boolean isEmpty() { return this.length == 0; } /** * Checks if the element is present in the list * * @param element to be checked in the list * @return true, if the element is present, false otherwise */ @Override public boolean contains(T element) { // Loop through the list for (Object o : this.elements) { // If the current element is equal to the given element, // then we will return true if (o != null && o.equals(element)) { return true; } } return false; } /** * Adds a new element in the list at the end of the list * * @param element to be added * @return added element */ @Override public T add(T element) { // Check if we have already reached the capacity of the list if (this.length >= this.capacity) { // Ensure the capacity of the list ensureCapacity(); } this.elements[length] = element; // Update the length pointer this.length++; return element; } /** * @param index index at which the element is to be added * @param element element to be added * @return element which is added */ public T addAtIndex(int index, T element) { // Check if the index is not out of bounds if (index < 0 || index >= this.length) { throw new ArrayIndexOutOfBoundsException("Index: " + index + " is out of bounds for length: " + this.length); } // Check if we need to increase the capacity if (this.length >= this.capacity) { ensureCapacity(); } // Move all elements after the given index one position right int i = index; while (i < this.length) { this.elements[i + 1] = this.elements[i]; i++; } // Add the elements at index this.elements[index] = element; this.length++; return element; } /** * Removes the given element in the list * * @param element element which is to be removed * @return removed element */ @Override public T remove(T element) { // Index of the element to be removed int index = -1; // Search for the element in the list for (int i = 0; i < elements.length; i++) { if (this.elements[i].equals(element)) { index = i; break; } } // Remove the element at index return removeAtIndex(index); } /** * @param index index at which the element is to be removed * @return removed element */ @SuppressWarnings("unchecked") public T removeAtIndex(int index) { // Check if the index is not out of bounds if (index < 0 || index >= this.length) { throw new ArrayIndexOutOfBoundsException("Index: " + index + " is out of bounds for length: " + this.length); } // Element at the given index Object elementToRemove = this.elements[index]; // Shift the elements after the removed elements to one place left int i = index; while (i < this.length - 1) { this.elements[i] = this.elements[i + 1]; i++; } this.length--; return (T) elementToRemove; } /** * @param index index at which the element is to be accessed * @return element at the given index */ @SuppressWarnings("unchecked") public T get(int index) { // Check if the index is not out of bounds if (index < 0 || index >= this.length) { throw new ArrayIndexOutOfBoundsException("Index: " + index + " is out of bounds for length: " + this.length); } return (T) this.elements[index]; } /** * Updates the element at the given index * * @param index index at which the element is to be set * @param element element to be set */ public void set(int index, T element) { // Check if the index is not out of bounds if (index < 0 || index >= this.length) { throw new ArrayIndexOutOfBoundsException("Index: " + index + " is out of bounds for length: " + this.length); } this.elements[index] = element; } /** * Removes all elements from the list */ @Override public void clear() { Arrays.fill(this.elements, null); this.length = 0; } /** * @return Iterator to traverse the list */ @Override @SuppressWarnings("unchecked") public Iterator<T> iterator() { return new Iterator<>() { // Cursor to keep track of the current element int cursor = 0; @Override public boolean hasNext() { return cursor != length; } @Override public T next() { return (T) elements[this.cursor++]; } }; } /** * @return String representation of all the elements in the list */ @Override public String toString() { StringBuilder output = new StringBuilder(); output.append("["); for (int i = 0; i < this.length - 1; i++) { output.append(this.elements[i]).append(", "); } output.append(this.elements[this.length - 1]).append("]"); return output.toString(); } private void ensureCapacity() { // New capacity - will be double of the previous capacity int newCapacity = 2 * this.capacity; // Create a new array with this capacity Object[] updatedElements = new Object[newCapacity]; // Copy all the elements from the current array to the new array System.arraycopy(elements, 0, updatedElements, 0, elements.length); // Assign this array to the original array this.elements = updatedElements; // Update the capacity this.capacity = newCapacity; } }
true
0daeddf69b07dda0318bcfe997d5e2d1ff34b692
Java
AndrewGeorge/CommonAdapter
/src/com/example/commonadapter/MainActivity.java
GB18030
2,707
2.296875
2
[]
no_license
package com.example.commonadapter; import java.util.ArrayList; import java.util.List; import com.example.bean.Bean; import com.example.utils.CommonAdapter; import com.example.utils.ViewHolder; import android.R.integer; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.ListView; public class MainActivity extends Activity { private ListView listview; private List<Bean> mDatas; private MyAdapter mMyadapter; private MyAdapterWidthCommonViewHolder myAdapterWidthCommonViewHolder; private List<Integer> mPos = new ArrayList<Integer>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initDatas(); initView(); } /** * ʼUI */ private void initView() { listview = (ListView) findViewById(R.id.listview); // ֱʹcommonAdapterʵ listview.setAdapter(new CommonAdapter<Bean>(MainActivity.this, mDatas,R.layout.item_listview) { @Override public void convert(final ViewHolder viewHolder, final Bean bean) { viewHolder.setText(R.id.id_title, bean.getTitle()) .setText(R.id.id_dec, bean.getDes()) .setText(R.id.id_time, bean.getTime()) .setText(R.id.id_phone, bean.getPhone()); final CheckBox cb = viewHolder.getView(R.id.id_cbox); // ʹbeanеǷѡ // cb.setChecked(bean.isCkecked()); cb.setChecked(false); if (mPos.contains(viewHolder.getmOption())) { cb.setChecked(true); } cb.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // bean.setCkecked(cb.isChecked()); if (cb.isChecked()) { mPos.add(viewHolder.getmOption()); } else { mPos.remove((Integer) viewHolder.getmOption()); } } }); } }); // myAdapterWidthCommonViewHolder̳commonAdapter // listview.setAdapter(myAdapterWidthCommonViewHolder); } private void initDatas() { mDatas = new ArrayList<Bean>(); for (int i = 0; i < 20; i++) { Bean bean = new Bean("Android" + i, "ѧϰһAndroid", "2015-7-27", "10086"); mDatas.add(bean); } // mMyadapter=new MyAdapter(this, mDatas); // myAdapterWidthCommonViewHolder=new // MyAdapterWidthCommonViewHolder(this, mDatas,R.layout.item_listview); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
true
def00f1ef73b1e52f9be466b7e85988bdf96dc85
Java
Jorgegar96/DAV-Q2-ExamenParcial1
/JSONAdapter/JSONFormatRacingCar.java
UTF-8
555
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 JSONAdapter; /** * * @author jorge */ public class JSONFormatRacingCar { private String JSONCar; public JSONFormatRacingCar(final String JSONCar){ this.JSONCar = JSONCar; } public String getJSONCar() { return JSONCar; } public void setJSONCar(String JSONCar) { this.JSONCar = JSONCar; } }
true
bec7a8daeda5a0379f6f7c98377ec4d529d4d421
Java
jamesmedice/SPRING-CERTIFICATION
/ANNOTATION-BASED-DEPENDENCY-INJECTION/src/main/java/com/medici/app/spring/life/cycle/MailService.java
UTF-8
916
2.59375
3
[]
no_license
package com.medici.app.spring.life.cycle; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.springframework.stereotype.Component; @Component public class MailService { private Map<String, String> map = null; public MailService() { map = new HashMap<String, String>(); } public void send(String mailTo) { System.out.println("Inside send method - " + mailTo); } public Collection<String> getProperties() { if (map == null) map = new HashMap<String, String>(); return map.values(); } @PostConstruct public void init() { map.put("host", "mail.example.com"); map.put("port", "25"); map.put("from", "james@medici.com"); System.out.println("Inside init method - " + map); } @PreDestroy public void destroy() { map.clear(); System.out.println("Inside destroy method - " + map); } }
true
91d7d18a2a60aeb1336e15d49e14fae1dece8128
Java
thhart/BoofCV
/main/boofcv-geo/src/main/java/boofcv/factory/geo/ConfigSelfCalibEssentialGuess.java
UTF-8
1,924
2.328125
2
[ "Apache-2.0", "LicenseRef-scancode-takuya-ooura" ]
permissive
/* * Copyright (c) 2021, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * 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 boofcv.factory.geo; import boofcv.misc.BoofMiscOps; import boofcv.struct.Configuration; import static boofcv.misc.BoofMiscOps.checkTrue; /** * Configuration for {@link boofcv.alg.geo.selfcalib.SelfCalibrationEssentialGuessAndCheck}. * * @author Peter Abeles */ public class ConfigSelfCalibEssentialGuess implements Configuration { /** Specifies the lower and upper limit for focal lengths it will consider. Relative to image max(width,height) */ public double sampleMin = 0.3, sampleMax = 3; /** Number of focal length values it will sample for each camera. 200 is better but is slow */ public int numberOfSamples = 50; /** if true the focus is assumed to be the same for the first two images */ public boolean fixedFocus = true; @Override public void checkValidity() { checkTrue(sampleMin > 0, "Minimum focal length must be more than 0"); checkTrue(sampleMin < sampleMax, "Minimum focal length must less than the maximum"); BoofMiscOps.checkTrue(numberOfSamples >= 1); } public ConfigSelfCalibEssentialGuess setTo( ConfigSelfCalibEssentialGuess src ) { this.sampleMin = src.sampleMin; this.sampleMax = src.sampleMax; this.numberOfSamples = src.numberOfSamples; this.fixedFocus = src.fixedFocus; return this; } }
true
79d105b61ff91bfffb54d7753e1d7a2226024134
Java
soufianenajim/learningP
/src/main/java/com/learning/model/base/ConstantSecurity.java
UTF-8
978
1.890625
2
[]
no_license
package com.learning.model.base; public final class ConstantSecurity { public static final String TOKEN_PREFIX = "Bearer "; public static final String HEADER_STRING = "Authorization"; public static final String TOKEN_STRING = "token"; public static final String ROLES = "role"; // Constants for cookies public static final String COOKIE_NAME = "JWT-TOKEN"; public static final Boolean COOKIE_SECURE = false; public static final Boolean COOKIE_HTTP_ONLY = true; public static final String COOKIE_PATH = "/"; public static final Integer COOKIE_MAXAAGE = 2147483647; public static final String COOKIE_DOMAIN = "localhost"; // routes for login public static final String URL_LOGIN = "/auth"; // routes for forgtoPassword public static final String FORGOT_PASSWORD = "/user/forgotpwd"; // routes for timeOfBlock public static final String TIME_OF_BLOCK = "/user/timeOfBlock"; private ConstantSecurity() { throw new IllegalStateException("Utility class"); } }
true
26c815f88e536c9fdd01736d4bd159f13c1b3318
Java
denizoktay/tennis-club-android-app
/app/src/main/java/com/denizoktay/a00268434_denizoktay_androidproject1/Screen4.java
UTF-8
2,406
2.140625
2
[]
no_license
package com.denizoktay.a00268434_denizoktay_androidproject1; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class Screen4 extends ListActivity { String[] myEvents = { "Event1", "Event2", "Event3", "Event4", "Event5", "Event6", "Event7", "Event8", "Event9", "Event10", "Event11", "Event12", "Event13", "Event14", "Event15", "Event16", "Event17", "Event18" }; String[] myLabels = { "Senior Round Robins Ladders 2020", "Kilkenny Autumn Matchplay 2019", "Claremorris Autumn League 2019", "2019 David Lloyd Riverview Autumn Invitational Match-Plays", "Ladies Box League Round 4", "WINTER LEAGUE 2019 - sponsored by The Hoban Hotel, Kilkenny", "Mount Pleasant Turkey 2019", "Winter Mixed Doubles League 2019", "Carraig Rockies Nov 2019", "Junior Box League November 2019", "Leinster Autumn Tennis 10's 2019", "2019 Talbot Hotel Winter Doubles", "Winter League 2019", "Lower Aghada Senior Closed 2019", "Winter Doubles Round Robin 2019", "Cullen's Butchers Turkey Tournament 2019", "Naas Ltc - 2019 Winter Doubles REGISTRATION ONLY", "ULSTER SENIOR INDOOR CHAMPIONSHIPS 2019", }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_screen4); this.setListAdapter(new ArrayAdapter<String>(Screen4.this, android.R.layout.simple_list_item_1, myLabels)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { try { Class myClass = Class.forName("com.denizoktay.a00268434_denizoktay_androidproject1." + myEvents[position]); Intent i = new Intent(Screen4.this, myClass); startActivity(i); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
true
f8c4b57170aacb3dbb139afbc042035c98a5f7cc
Java
prashu18400/NCR_TR_PREP
/src/Methods/PvPr.java
UTF-8
1,152
4.34375
4
[]
no_license
package Methods; public class PvPr { public static void main(String[] args) { // TODO Auto-generated method stub //Here we are going to see the difference between Pass by value and Pass by reference int a = 32; int b = 12; swap(a,b);//as soon as the method is called System.out.println("a = "+a +",b = " + b); Dog c = new Dog(); Dog d = new Dog(); c.legs = 4; d.legs = 3; swap(c,d); System.out.println(c.legs + " " + d.legs); } private static void swap(int a, int b) { /*here two objects int a and int b are created and the values are stored in them and these are swapped * in the function but the original variables are unchanged */ // TODO Auto-generated method stub int temp = a; a = b; b = temp; System.out.print("Inside function "); System.out.println(a + " " + b); } private static void swap(Dog c,Dog d) { //Here when it comes to non-primitive data types i.e classes a reference to that class is created and //passed and those reference as swapped in this method but the reference of original c and d class //remain same Dog temp; temp = c; c = d; d = temp; } }
true
1d3ae522d2c9b54c6d8bbd680a12f7a14b84a317
Java
yudu4908/Lintcode
/NetEase/EnglishSoftware.java
UTF-8
2,893
3.953125
4
[]
no_license
package NetEase; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** 小林是班级的英语课代表,他想开发一款软件来处理班上同学的成绩 小林的软件有一个神奇的功能,能够通过一个百分数来反应你的成绩在班上的位置。“成绩超过班级 …% 的同学”。 设这个百分数为 p,考了 s 分,则可以通过以下式子计算得出 p: p = ( 分数不超过 s 的人数 - 1) / 班级总人数 * 100% 请你设计一下这个软件 */ /** 给出score数组代表第i个人考了score[i]分 给出ask数组代表询问第i个人的成绩百分数 每询问一次输出对应的成绩百分数,不需要输出百分号 答案向下取整 输入: score = [100,98,87], ask=[1,2,3] 输出: [66,33,0] 解释: 第一个人考了100分,超过了66%的学生 */ class Student { public int id; public double score; public Student(int _id, double _score) { this.id = _id; this.score = _score; } } public class EnglishSoftware { /** 这是一道简单题目,实际上我们可以用排序解决 我们先记录这个人当前的位置,对于成绩做一个排序 根据一个人拍完序后的位置/总人数得到成绩对应的百分比 最后根据ask位置所对应的成绩来得到百分比的值, 这里可以用map来记录其当前位置和之前位置,复杂度nlogn */ /** * @param score: Each student's grades * @param ask: A series of inquiries * @return: Find the percentage of each question asked */ //这题其实不简单。。 public List<Integer> englishSoftware(List<Integer> score, List<Integer> ask) { Map<Integer, Double> scoreMap = new HashMap<Integer, Double>(); List<Student> sortStudent = new ArrayList<Student>(); for (int i = 0; i < score.size(); i++) { scoreMap.put(i + 1, (double)score.get(i)); //存放第一个人和第一个人的score。。。 sortStudent.add(new Student(i, (double)score.get(i))); //sortStudent存放的是student对象 } sortStudent.sort((o1, o2) -> (int)o1.score - (int)o2.score); //分数从小到大排序, 为什么要转换为int型?因为不加的话lambda expression会报错bad return type Map<Double, Double> percentMap = new HashMap<Double, Double>(); for (int i = 0; i < sortStudent.size(); i++) { percentMap.put(sortStudent.get(i).score, (double)i * 100 / sortStudent.size()); //percentMap存放分数和百分比的对应关系 } List<Integer> ans = new ArrayList<Integer>(); for (int k : ask) { ans.add((int)(Math.floor(percentMap.get(scoreMap.get(k)))));//scoreMap.get(k)取出第k个人的分数,percentMap取出这个分数对应的班级百分比 } return ans; } }
true
5ba815b48618bf0ecb999b78153e80947375cd70
Java
jianyimiku/My-LeetCode-Solution
/Algorithms/0001-1000/0290. Word Pattern/Solution.java
UTF-8
804
3.1875
3
[]
no_license
class Solution { public boolean wordPattern(String pattern, String str) { str = str.trim(); String[] words = str.split(" "); if (pattern.length() != words.length) return false; int length = words.length; Map<Character, String> map1 = new HashMap<Character, String>(); Map<String, Character> map2 = new HashMap<String, Character>(); for (int i = 0; i < length; i++) { char c = pattern.charAt(i); String word = words[i]; if (map1.containsKey(c) && !map1.get(c).equals(word)) return false; if (map2.containsKey(word) && map2.get(word) != c) return false; map1.put(c, word); map2.put(word, c); } return true; } }
true
889ff48b53054d8fba23e12419548d06b845a254
Java
nbcc-java/cn.nbcc.resassistant
/src/cn/nbcc/resassistant/decrecated/FileEntity.java
UTF-8
529
2.265625
2
[]
no_license
package cn.nbcc.resassistant.decrecated; import java.nio.file.Path; import java.util.List; import cn.nbcc.resassistant.model.ITreeEntry; public class FileEntity implements ITreeEntry { private Path file; public FileEntity(Path file) { this.file = file; } @Override public String getName() { return file.getFileName().toString(); } @Override public void setName(String name) { } @Override public void setChildren(List<?> children) { } @Override public List<?> getChildren() { return null; } }
true
b1c82f00d1ef83850067dbdd5d1eb506ae7b25a9
Java
jamespharaoh/jpstack-console
/forms/types/FormFieldInterfaceMapping.java
UTF-8
1,092
1.929688
2
[]
no_license
package wbs.console.forms.types; import static wbs.utils.string.StringUtils.stringFormat; import java.util.Map; import com.google.common.base.Optional; import lombok.NonNull; import wbs.framework.database.Transaction; import fj.data.Either; public interface FormFieldInterfaceMapping <Container, Generic, Interface> { default Either <Optional <Generic>, String> interfaceToGeneric ( @NonNull Transaction parentTransaction, @NonNull Container container, @NonNull Map <String, Object> hints, @NonNull Optional <Interface> interfaceValue) { throw new UnsupportedOperationException ( stringFormat ( "%s.%s", getClass ().getSimpleName (), "interfaceToGeneric (...)")); } default Either <Optional <Interface>, String> genericToInterface ( @NonNull Transaction parentTransaction, @NonNull Container container, @NonNull Map <String, Object> hints, @NonNull Optional <Generic> genericValue) { throw new UnsupportedOperationException ( stringFormat ( "%s.%s", getClass ().getSimpleName (), "genericToInterface (...)")); } }
true
63f9e0a6f02b169bfbe7d40aee63a648ca357b57
Java
DreamBlueSun/dazeblueluka
/src/main/java/com/kirisame/gensokyo/daze/blue/luka/mapper/WordTypeParseMapper.java
UTF-8
874
1.867188
2
[]
no_license
package com.kirisame.gensokyo.daze.blue.luka.mapper; import com.kirisame.gensokyo.daze.blue.luka.entity.po.WordTypeParse; import com.kirisame.gensokyo.daze.blue.luka.entity.po.WordTypeParseExample; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; @Repository public interface WordTypeParseMapper { long countByExample(WordTypeParseExample example); int deleteByExample(WordTypeParseExample example); int insert(WordTypeParse record); int insertSelective(WordTypeParse record); List<WordTypeParse> selectByExample(WordTypeParseExample example); int updateByExampleSelective(@Param("record") WordTypeParse record, @Param("example") WordTypeParseExample example); int updateByExample(@Param("record") WordTypeParse record, @Param("example") WordTypeParseExample example); }
true
87a7a8420f5d3db1de224fccd901ec120ec0e05a
Java
davide-belli/smartchats-frontend
/MyChatbot_01/src/main/java/com/example/mychatbot/Utilities/IntentUtils.java
UTF-8
1,985
2.625
3
[ "MIT" ]
permissive
package com.example.mychatbot.Utilities; import android.app.Activity; import android.content.Intent; import android.net.Uri; /** * Created by david on 02/05/2017. * * Intents to launche preinstalled activity to access contextual information * for restaurant (send email, dial number, look website, open maps) */ public class IntentUtils { public static void invokeWebBrowser(Activity activity, String url) { if (!url.startsWith("http://") && !url.startsWith("https://")) url = "http://" + url; Intent intent = new Intent( android.content.Intent.ACTION_VIEW); intent.setAction(Intent.ACTION_VIEW); intent.setType("message/rfc822"); intent.setData(Uri.parse(url)); activity.startActivity(Intent.createChooser(intent, "Browse Using: ")); } public static void dial(Activity activity, String number) { Intent intent=new Intent(Intent.ACTION_DIAL); String uri = "tel:" + number.trim() ; intent.setData(Uri.parse(uri)); activity.startActivity(intent); } public static void showDirections(Activity activity, String lat, String lon){ Intent intent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://maps.google.com/?q="+lat +","+lon)); activity.startActivity(intent); } public static void sendEmail(Activity activity, String email){ Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); emailIntent.setAction(Intent.ACTION_SEND); //emailIntent.setClassName("com.google.android.gm","com.google.android.gm.ComposeActivityGmail"); emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{email}); emailIntent.setType("message/rfc822"); emailIntent.setData(Uri.parse("mailto:"+email)); emailIntent.setType("text/html"); activity.startActivity(Intent.createChooser(emailIntent, "Send Email Using: ")); } }
true
724f6a85955a435d2bc82c787e0620d4944b444e
Java
dayakulkarniasu/CSE545_Team7
/server/src/main/java/com/sbs/sbsgroup7/api/OtpController.java
UTF-8
5,362
2.171875
2
[]
no_license
package com.sbs.sbsgroup7.api; import java.util.Date; import com.sbs.sbsgroup7.DataSource.AcctRepository; import com.sbs.sbsgroup7.DataSource.SystemLogRepository; import com.sbs.sbsgroup7.DataSource.TransRepository; import com.sbs.sbsgroup7.model.Account; import com.sbs.sbsgroup7.model.SystemLog; import com.sbs.sbsgroup7.model.Transaction; import com.sbs.sbsgroup7.model.User; import com.sbs.sbsgroup7.service.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import com.sbs.sbsgroup7.service.MailService; /** * @author shrisowdhaman * Dec 15, 2017 */ @Controller @RequestMapping("/otp") public class OtpController { @Autowired private TransRepository transRepository; @Autowired private AccountService accountService; @Autowired private AcctRepository acctRepository; @Autowired private SystemLogRepository systemLogRepository; private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired public OtpService otpService; @Autowired public MailService emailService; @Autowired private UserService userService; @GetMapping("/generateOtp") public String generateOtp(){ Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String username = auth.getName(); int otp = otpService.generateOTP(username); logger.info("OTP : "+otp); //Generate The Template to send OTP // EmailTemplate template = new EmailTemplate("SendOtp.html"); // Map<String,String> replacements = new HashMap<String,String>(); // replacements.put("user", username); // replacements.put("otpnum", String.valueOf(otp)); // String message = template.getTemplate(replacements); emailService.sendOTPMail(username, Integer.toString(otp)); return "otp/otppage"; } @RequestMapping(value ="/validateOtp", method = RequestMethod.GET) public String validateOtp(){ Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String username = auth.getName(); int otp = otpService.generateOTP(username); logger.info("OTP : "+otp); emailService.sendOTPMail(username, Integer.toString(otp)); return "otp/otppage"; } @RequestMapping(value ="/validateOtp", method = RequestMethod.POST) public String validateOtp(@ModelAttribute("otp") String otpnum){ User user=userService.getLoggedUser(); final String SUCCESS = "Entered Otp is valid"; final String FAIL = "Entered Otp is NOT valid. Please Retry!"; Authentication auth = SecurityContextHolder.getContext().getAuthentication(); String username = auth.getName(); logger.info(" Otp Number : "+otpnum); //Validate the Otp if(Integer.parseInt(otpnum )>= 0){ int serverOtp = otpService.getOtp(username); if(serverOtp > 0){ if(Integer.parseInt(otpnum ) == serverOtp) { otpService.clearOTP(username); Transaction transaction = transRepository.findByTransactionOwnerAndTransactionStatus(user,"temp"); Account source= transaction.getFromAccount(); Account destination = transaction.getToAccount(); if(transaction.getAmount()<1000){ transaction.setTransactionStatus("approved"); transRepository.save(transaction); source.setBalance(source.getBalance()-transaction.getAmount()); destination.setBalance(destination.getBalance()+transaction.getAmount()); acctRepository.save(source); acctRepository.save(destination); SystemLog systemLog=new SystemLog(); systemLog.setMessage(user.getEmail() + " successfully transferred $" + transaction.getAmount()); systemLog.setTimestamp(new Date()); systemLogRepository.save(systemLog); } else{ transaction.setTransactionStatus("pending"); transRepository.save(transaction); SystemLog systemLog=new SystemLog(); systemLog.setMessage(user.getEmail() + " requested transfer of $" + transaction.getAmount()); systemLog.setTimestamp(new Date()); systemLogRepository.save(systemLog); } if(user.getRole().equals("USER")) { return "redirect:/user/accounts"; } else if(user.getRole().equals("MERCHANT")){ return "redirect:/merchant/accounts"; } else{ return "403error"; } } } } return "otp/invalid"; } }
true
17e114cf3c89d780a0fedbf16b0f3d0396f57c27
Java
shasank453/Backend-Samples
/src/test/java/edu/med/umich/michr/dao/QuestionDaoImplTest.java
UTF-8
2,398
2.28125
2
[]
no_license
package edu.med.umich.michr.dao; import edu.med.umich.michr.domain.Question; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit.jupiter.SpringExtension; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; import static org.junit.jupiter.api.Assertions.*; @ExtendWith(SpringExtension.class) @DataJpaTest class QuestionDaoImplTest { @Autowired private TestEntityManager testEntityManager; private QuestionDao dao; @BeforeEach void setUp() { dao = new QuestionDaoImpl(testEntityManager.getEntityManager()); } @AfterEach void tearDown() { dao = null; } @Test void testSave() { Question question = new Question("text"); Long savedId = dao.save(question); Question savedQuestion = dao.getById(savedId); assertEquals(question.getText(), savedQuestion.getText()); } @Test void testUpdate() { Question question = new Question("text"); Long savedId = dao.save(question); Question questionToUpdate = new Question(savedId, "new text"); dao.update(questionToUpdate); Question questionFetched = dao.getById(savedId); assertEquals(savedId.longValue(), questionFetched.getId()); assertEquals("new text", questionFetched.getText()); } @Test void testGetAll() { Question question1 = new Question("text1"); Question question2 = new Question("text2"); long id1 = dao.save(question1); long id2 = dao.save(question2); List<Question> expected = Arrays.asList(new Question(id1, question1.getText())); new Question(id2, question2.getText()); List<Question> questions = dao.getAll(); assertEquals(expected, questions); } @Test void testDelete() { Question question = new Question("text"); long id = dao.save(question); assertNotNull(dao.getById(id)); dao.delete(dao.getById(id)); assertNull(dao.getById(id)); } }
true
7454cc37f8adc3b159e0c61c72208743f1b83fb8
Java
Organization-Work/HPE
/HCAS/hcas_java/find-dev/src/main/java/com/autonomy/find/services/TaxonomyService.java
UTF-8
6,259
1.835938
2
[]
no_license
package com.autonomy.find.services; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import com.autonomy.aci.client.annotations.IdolAnnotationsProcessorFactory; import com.autonomy.aci.client.services.AciService; import com.autonomy.aci.client.util.AciParameters; import com.autonomy.find.config.TaxonomyConfig; import com.autonomy.find.dto.SearchRequestData; import com.autonomy.find.dto.taxonomy.CategoryData; import com.autonomy.find.dto.taxonomy.CategoryName; import com.autonomy.find.dto.taxonomy.CategoryPath; import com.autonomy.find.util.CollUtils; import com.autonomy.find.util.MTree; import com.googlecode.ehcache.annotations.Cacheable; import com.googlecode.ehcache.annotations.DecoratedCacheType; public class TaxonomyService { public AciService getCategoryAci() { return categoryAci; } public void setCategoryAci(AciService categoryAci) { this.categoryAci = categoryAci; } public TaxonomyConfig getTaxonomyConfig() { return taxonomyConfig; } public void setTaxonomyConfig(TaxonomyConfig taxonomyConfig) { this.taxonomyConfig = taxonomyConfig; } public IdolAnnotationsProcessorFactory getProcessorFactory() { return processorFactory; } public void setProcessorFactory(IdolAnnotationsProcessorFactory processorFactory) { this.processorFactory = processorFactory; } public TaxonomyDocCountService getDocCountService() { return docCountService; } public void setDocCountService(TaxonomyDocCountService docCountService) { this.docCountService = docCountService; } public static Logger getLogger() { return LOGGER; } public static String getActionGetHierDetails() { return ACTION_GET_HIER_DETAILS; } public static String getParamCategory() { return PARAM_CATEGORY; } public void setCategoryHier(MTree<String> categoryHier) { this.categoryHier = categoryHier; } private static final Logger LOGGER = LoggerFactory.getLogger(TaxonomyService.class); private static final String ACTION_GET_HIER_DETAILS = "CategoryGetHierDetails", PARAM_CATEGORY = "Category"; @Autowired @Qualifier("taxonomyAciService") private AciService categoryAci; @Autowired private TaxonomyConfig taxonomyConfig; @Autowired private IdolAnnotationsProcessorFactory processorFactory; @Autowired private TaxonomyDocCountService docCountService; private final Map<String, String> categoryNames = new HashMap<>(); private MTree<String> categoryHier; /** * */ private void loadCategoryHierAndNames() { if (categoryHier != null) { return; } final Map<String, Integer> docCounts = docCountService.getCategoryDocCounts(new SearchRequestData()); final Map<String, Set<String>> links = new HashMap<>(); for (final String categoryId : docCounts.keySet()) { if (!this.categoryNames.containsKey(categoryId)) { try { extractNamesAndLinks(getCategoryPath(categoryId).getActualPath(), this.categoryNames, links); } catch (final RuntimeException e) { LOGGER.error(String.format("Error loading category with id: `%s`", categoryId)); } } } this.categoryHier = CollUtils.compileLinksToTree(links, taxonomyConfig.getRootCategory()); } /** * Extracts category id + name pairs and parent to children links. * * @param path - Path to the category * @param categoryNames - Category naming map accumulator * @param links - Category linking accumulator */ private static void extractNamesAndLinks( final List<CategoryName> path, final Map<String, String> categoryNames, final Map<String, Set<String>> links ) { Set<String> children; String parent = null; for (final CategoryName category : path) { if (parent != null) { children = links.get(parent); if (children == null) { children = new LinkedHashSet<>(); } children.add(category.getId()); links.put(parent, children); } parent = category.getId(); categoryNames.put(category.getId(), category.getName()); } } /** * @param categoryId * @return */ private CategoryPath getCategoryPath( final String categoryId ) { final AciParameters params = paramsForHierAndNames(null, categoryId); return categoryAci.executeAction(params, processorFactory.listProcessorForClass(CategoryPath.class)).get(0); } /** * GetCategoryNames * * @return Map Id Name */ public Map<String, String> getCategoryNames() { loadCategoryHierAndNames(); return this.categoryNames; } /** * GetCategoryHier * * @return MTree Id */ public MTree<String> getCategoryHier() { loadCategoryHierAndNames(); return this.categoryHier; } /** * GetCategoryData * * @return CategoryData */ @Cacheable(cacheName = "getCategoryData", decoratedCacheType = DecoratedCacheType.SELF_POPULATING_CACHE) public CategoryData getCategoryData() { if (!taxonomyConfig.isActive()) { return null; } return new CategoryData( getCategoryHier(), getCategoryNames(), docCountService.getCategoryDocCounts(new SearchRequestData())); } /** * @param params * @param categoryId * @return */ public AciParameters paramsForHierAndNames( AciParameters params, final String categoryId ) { if (params == null) { params = new AciParameters(ACTION_GET_HIER_DETAILS); } params.add(PARAM_CATEGORY, categoryId); return params; } }
true
bf018642166d74c5abf72b8e119d3963d4d9070b
Java
Reems59/projetOpenDev
/ProjetOpenDev/src/main/java/project/game/Player.java
UTF-8
470
2.625
3
[]
no_license
package project.game; import java.awt.Graphics; import gameframework.drawing.Drawable; import gameframework.drawing.DrawableImage; import gameframework.drawing.GameCanvas; import gameframework.game.GameEntity; public class Player implements Drawable,GameEntity { private DrawableImage image; public Player(GameCanvas canvas, String name) { this.image = new DrawableImage(name, canvas); } public void draw(Graphics g) { this.image.draw(g); } }
true
443b55ddaf58695107b9ff92c9dd027b44905cb4
Java
Ianbpn/PereyraIanParcial
/Parcial/src/main/java/com/example/Parcial/service/CurrencyService.java
UTF-8
1,057
2.203125
2
[]
no_license
package com.example.Parcial.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import com.example.Parcial.repository.*; import com.example.Parcial.model.Currency; import org.springframework.web.client.HttpClientErrorException; import java.util.List; @Service public class CurrencyService { public CurrencyRepository currencyRepository; @Autowired public CurrencyService(CurrencyRepository currencyRepository){ this.currencyRepository =currencyRepository; } public List<Currency> getAll(){return currencyRepository.findAll();} public void addCurrency (Currency currency){ currencyRepository.save(currency); } public Currency getCurrencyByID(Integer id){ return currencyRepository.findById(id) .orElseThrow(()->new HttpClientErrorException(HttpStatus.NOT_FOUND)); } public void delCurrencyByID(Integer id){ currencyRepository.deleteById(id); } }
true
9712dce25d24bac83a91226a3c5efb516468a56a
Java
2202Programming/2018-2019
/src/auto/stopConditions/LiftStopCondition.java
UTF-8
788
2.9375
3
[]
no_license
package auto.stopConditions; import auto.IStopCondition; import miyamoto.components.Lift; import miyamoto.components.LiftPosition; /** * A stop condition based on the Miyamoto Lift component * * Precondition: The Lift component is calibrated */ public class LiftStopCondition implements IStopCondition { private Lift lift; private int stopPosition; public LiftStopCondition(Lift liftComponent, int finalPosition) { lift = liftComponent; stopPosition = finalPosition; } public LiftStopCondition(Lift liftComponent, LiftPosition finalPosition) { lift = liftComponent; stopPosition = finalPosition.getNumber(); } @Override public void init() { return; } @Override public boolean stopNow() { return Math.abs(stopPosition - lift.getLiftCounts()) <= 100; } }
true
a0d066878ce0c4c612038bcd754efec8508b1599
Java
kamikaz-e/MyYSTU
/app/src/main/java/ru/ystu/myystu/Activitys/EventActivity.java
UTF-8
22,551
1.796875
2
[ "Apache-2.0" ]
permissive
package ru.ystu.myystu.Activitys; import android.content.Context; import android.database.sqlite.SQLiteException; import android.os.Parcelable; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.animation.AnimationUtils; import android.view.animation.LayoutAnimationController; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicReference; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.snackbar.Snackbar; import io.reactivex.Single; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.observers.DisposableSingleObserver; import io.reactivex.schedulers.Schedulers; import ru.ystu.myystu.AdaptersData.EventItemsData_Event; import ru.ystu.myystu.AdaptersData.EventItemsData_Header; import ru.ystu.myystu.AdaptersData.StringData; import ru.ystu.myystu.AdaptersData.UpdateItemsTitleData; import ru.ystu.myystu.Application; import ru.ystu.myystu.Database.AppDatabase; import ru.ystu.myystu.Database.Data.CountersData; import ru.ystu.myystu.Network.LoadLists.GetListEventFromURL; import ru.ystu.myystu.R; import ru.ystu.myystu.Adapters.EventItemsAdapter; import ru.ystu.myystu.Utils.BellHelper; import ru.ystu.myystu.Utils.BottomFloatingButton.BottomFloatingButton; import ru.ystu.myystu.Utils.Converter; import ru.ystu.myystu.Utils.ErrorMessage; import ru.ystu.myystu.Utils.IntentHelper; import ru.ystu.myystu.Utils.LightStatusBar; import ru.ystu.myystu.Utils.NetworkInformation; import ru.ystu.myystu.Utils.PaddingHelper; import ru.ystu.myystu.Utils.SettingsController; public class EventActivity extends AppCompatActivity { private Context mContext; private ConstraintLayout mainLayout; private String url = "https://www.ystu.ru/events/"; // Url страницы событий сайта ЯГТУ private RecyclerView mRecyclerView; private RecyclerView.Adapter mRecyclerViewAdapter; private RecyclerView.LayoutManager mLayoutManager; private SwipeRefreshLayout mSwipeRefreshLayout; private ArrayList<Parcelable> mList; private ArrayList<Parcelable> updateList; private Parcelable mRecyclerState; private CompositeDisposable mDisposables; private GetListEventFromURL getListEventFromURL; private AppDatabase db; private boolean isUpdate = false; private BottomFloatingButton bfb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event); if (SettingsController.isDarkTheme(this)) { LightStatusBar.setLight(false, false, this, true); } else { LightStatusBar.setLight(true, true, this, true); } mContext = this; mainLayout = findViewById(R.id.main_layout_event); final AppBarLayout appBarLayout = findViewById(R.id.appBar_event); final Toolbar mToolbar = findViewById(R.id.toolBar_event); setSupportActionBar(mToolbar); mToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_material); mToolbar.setNavigationOnClickListener(view -> onBackPressed()); mToolbar.setOnClickListener(e -> { if(mRecyclerView != null){ if(((LinearLayoutManager)mLayoutManager).findFirstVisibleItemPosition() < 3) mRecyclerView.smoothScrollToPosition(0); else mRecyclerView.scrollToPosition(0); } }); mLayoutManager = new LinearLayoutManager(this); mRecyclerView = findViewById(R.id.recycler_event_items); mRecyclerView.setHasFixedSize(true); mRecyclerView.setLayoutManager(mLayoutManager); mSwipeRefreshLayout = findViewById(R.id.refresh_event); mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(getResources().getColor(R.color.colorBackgroundTwo)); mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary); mSwipeRefreshLayout.setOnRefreshListener(() -> { if (!isUpdate) { getEvent(url); } else { mSwipeRefreshLayout.setRefreshing(false); } }); mSwipeRefreshLayout.setProgressViewOffset(true, 0, (int) Converter.convertDpToPixel(70, mContext)); PaddingHelper.setPaddingStatusBarAndToolBar(mContext, mRecyclerView, true); PaddingHelper.setOffsetRefreshLayout(mContext, mSwipeRefreshLayout); PaddingHelper.setMarginsAppBar(appBarLayout); mDisposables = new CompositeDisposable(); getListEventFromURL = new GetListEventFromURL(); if (db == null || !db.isOpen()) db = Application.getInstance().getDatabase(); if (savedInstanceState == null){ if (getIntent().getExtras() != null){ isUpdate = getIntent().getExtras().getBoolean("isUpdate", false); } getEvent(url); } else { isUpdate = savedInstanceState.getBoolean("isUpdate", false); mList = savedInstanceState.getParcelableArrayList("mList"); updateList = savedInstanceState.getParcelableArrayList("updateList"); if (isUpdate) { mRecyclerViewAdapter = new EventItemsAdapter(updateList, this); bfb = BottomFloatingButton.onSaveInstance.getBottomFloatingButton(); bfb.updateFragmentManager(getSupportFragmentManager()); bfb.setOnClickListener(() -> { isUpdate = false; mRecyclerViewAdapter = new EventItemsAdapter(mList, mContext); mRecyclerViewAdapter.setHasStableIds(true); mRecyclerView.setAdapter(mRecyclerViewAdapter); setRecyclerViewAnim(mRecyclerView); }); } else { mRecyclerViewAdapter = new EventItemsAdapter(mList, this); } mRecyclerView.setAdapter(mRecyclerViewAdapter); } } @Override protected void onPause() { super.onPause(); if (isFinishing() && !SettingsController.isEnabledAnim(this)) { overridePendingTransition(0, 0); } } @Override protected void onDestroy() { super.onDestroy(); if (mDisposables != null) mDisposables.dispose(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_event, menu); LightStatusBar.setToolBarIconColor(mContext, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId() == R.id.menu_event_openInBrowser) { IntentHelper.openInBrowser(this, url); } return true; } @Override protected void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); mRecyclerState = mLayoutManager.onSaveInstanceState(); outState.putParcelable("recyclerViewState", mRecyclerState); outState.putParcelableArrayList("mList", mList); outState.putParcelableArrayList("updateList", updateList); outState.putString("url", url); outState.putBoolean("isUpdate", isUpdate); if (bfb != null) { BottomFloatingButton.onSaveInstance.setBottomFloatingButton(bfb); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mRecyclerState = savedInstanceState.getParcelable("recyclerViewState"); url = savedInstanceState.getString("url"); } public void setUrl (String url) { this.url = url; } // Загрузка html страницы и ее парсинг public void getEvent(String link){ if(mList == null) { mList = new ArrayList<>(); updateList = new ArrayList<>(); } else if (!isUpdate) { mList.clear(); updateList.clear(); } mSwipeRefreshLayout.post(() -> mSwipeRefreshLayout.setRefreshing(true)); if(NetworkInformation.hasConnection()){ final Single<ArrayList<Parcelable>> mSingleEventList = getListEventFromURL.getSingleEventList(link, mList); mDisposables.add(mSingleEventList .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribeWith(new DisposableSingleObserver<ArrayList<Parcelable>>() { @Override public void onSuccess(ArrayList<Parcelable> eventItemsData) { mList = eventItemsData; if(mRecyclerViewAdapter == null) { if (isUpdate) { AtomicReference<ArrayList<Parcelable>> temp = new AtomicReference<>(); final Thread thread = new Thread(() -> temp.set(getUpdateList(eventItemsData))); thread.start(); try { thread.join(); updateList = temp.get(); if (updateList.size() > 1) { mRecyclerViewAdapter = new EventItemsAdapter(updateList, mContext); } else { mRecyclerViewAdapter = new EventItemsAdapter(mList, mContext); isUpdate = false; } mRecyclerViewAdapter.setHasStableIds(true); mRecyclerView.post(() -> { mRecyclerView.setAdapter(mRecyclerViewAdapter); setRecyclerViewAnim(mRecyclerView); if (updateList.size() > 1) { bfb = new BottomFloatingButton(mContext, mainLayout, mContext.getString(R.string.bfb_all_event)); bfb.setIcon(R.drawable.ic_level_back); bfb.setShowDelay(2000); bfb.setAnimation(SettingsController.isEnabledAnim(mContext)); bfb.setOnClickListener(() -> { isUpdate = false; mRecyclerViewAdapter = new EventItemsAdapter(mList, mContext); mRecyclerViewAdapter.setHasStableIds(true); mRecyclerView.setAdapter(mRecyclerViewAdapter); setRecyclerViewAnim(mRecyclerView); }); bfb.show(); } }); } catch (InterruptedException e) { e.printStackTrace(); } } else { setUpdateTag(mList); } } else { if (!isUpdate) { mRecyclerViewAdapter.notifyItemRangeChanged(2, mList.size()); } } new Thread(() -> { try { if (db.getOpenHelper().getWritableDatabase().isOpen()) { // Удаляем все записи, если они есть if (db.eventsItemsDao().getCountEventHeader() > 0) db.eventsItemsDao().deleteEventHeader(); if (db.eventsItemsDao().getCountDividers() > 0) db.eventsItemsDao().deleteAllDividers(); if (db.eventsItemsDao().getCountEventItems() > 0) db.eventsItemsDao().deleteAllEventItems(); // Добавляем новые записи for (Parcelable parcelable : eventItemsData) { if (parcelable instanceof StringData) { db.eventsItemsDao().insertDividers((StringData) parcelable); } else if (parcelable instanceof EventItemsData_Event) { db.eventsItemsDao().insertEventItems((EventItemsData_Event) parcelable); } else if (parcelable instanceof EventItemsData_Header) { db.eventsItemsDao().insertEventHeader((EventItemsData_Header) parcelable); } } // Обновляем счетчики // Если нет счетчика, создаем if ( ((EventItemsData_Header) eventItemsData.get(0)).getSelected_id() == 0) { if (!db.countersDao().isExistsCounter("EVENT")) { final CountersData countersData = new CountersData(); countersData.setType("EVENT"); countersData.setCount(0); db.countersDao().insertCounter(countersData); } else { db.countersDao().setCount("EVENT", 0); } } runOnUiThread(BellHelper.UpdateListController::updateItems); } } catch (SQLiteException e) { runOnUiThread(() -> Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show()); } }).start(); mSwipeRefreshLayout.setRefreshing(false); } @Override public void onError(Throwable e) { mSwipeRefreshLayout.setRefreshing(false); if(e.getMessage().equals("Not found")){ ErrorMessage.show(mainLayout, 1, mContext.getResources().getString(R.string.error_message_event_not_found), mContext); } else { ErrorMessage.show(mainLayout, -1, e.getMessage(), mContext); } } })); } else { new Thread(() -> { try { if (db.getOpenHelper().getReadableDatabase().isOpen() && db.eventsItemsDao().getCountEventItems() > 0) { if (mList.size() > 0) mList.clear(); final int countListItems = db.eventsItemsDao().getCountDividers() + db.eventsItemsDao().getCountEventItems() + 2; for (int i = 0; i < countListItems; i++) { if (db.eventsItemsDao().isExistsDivider(i)) { mList.add(db.eventsItemsDao().getDividers(i)); } else if (db.eventsItemsDao().isExistsEventItems(i)) { mList.add(db.eventsItemsDao().getEvents(i)); } else if (db.eventsItemsDao().isExistsEventHeader(i)) { mList.add(db.eventsItemsDao().getEventHeader(i)); } } mRecyclerViewAdapter = new EventItemsAdapter(mList, this); mRecyclerView.post(() -> { mRecyclerView.setAdapter(mRecyclerViewAdapter); setRecyclerViewAnim(mRecyclerView); // SnackBar с предупреждением об отсутствие интернета final Snackbar snackbar = Snackbar .make( mainLayout, getResources().getString(R.string.toast_no_connection_the_internet), Snackbar.LENGTH_INDEFINITE) .setAction( getResources().getString(R.string.error_message_refresh), view -> { // Обновление данных getEvent(url); }); ((TextView)snackbar .getView() .findViewById(com.google.android.material.R.id.snackbar_text)) .setTextColor(getResources().getColor(R.color.colorTextBlack)); snackbar.show(); mSwipeRefreshLayout.setRefreshing(false); }); } else { runOnUiThread(() -> { ErrorMessage.show(mainLayout, 0, null, mContext); mSwipeRefreshLayout.setRefreshing(false); }); } } catch (SQLiteException e) { runOnUiThread(() -> { ErrorMessage.show(mainLayout, -1, e.getMessage(), mContext); mSwipeRefreshLayout.setRefreshing(false); }); } }).start(); } } private void setRecyclerViewAnim (final RecyclerView recyclerView) { if (SettingsController.isEnabledAnim(this)) { final Context context = recyclerView.getContext(); final LayoutAnimationController controller = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_main_recyclerview_show); recyclerView.setLayoutAnimation(controller); } else { recyclerView.clearAnimation(); } } private ArrayList<Parcelable> getUpdateList (ArrayList<Parcelable> mList) { final ArrayList<Parcelable> tempList = new ArrayList<>(); tempList.add(new UpdateItemsTitleData(getResources().getString(R.string.other_updateFindTitle), R.drawable.ic_update)); try { if (db.getOpenHelper().getReadableDatabase().isOpen() && db.eventsItemsDao().getCountEventItems() > 0) { for (int i = 0; i < mList.size(); i++) { if (mList.get(i) instanceof EventItemsData_Event) { final String link = ((EventItemsData_Event) mList.get(i)).getLink(); if (link != null && !db.eventsItemsDao().isExistsEventByLink(link)) { final EventItemsData_Event eventItem = (EventItemsData_Event) mList.get(i); eventItem.setNew(true); tempList.add(eventItem); } } } } } catch (SQLiteException e) { runOnUiThread(() -> mSwipeRefreshLayout.setRefreshing(false)); } return tempList; } private void setUpdateTag (ArrayList<Parcelable> mList) { final Thread thread = new Thread(() -> { try { if (db.getOpenHelper().getReadableDatabase().isOpen() && db.eventsItemsDao().getCountEventItems() > 0) { for (int i = 0; i < mList.size(); i++) { if (mList.get(i) instanceof EventItemsData_Event) { final String link = ((EventItemsData_Event) mList.get(i)).getLink(); if (link != null && !db.eventsItemsDao().isExistsEventByLink(link)) { ((EventItemsData_Event) mList.get(i)).setNew(true); } } } } } catch (SQLiteException ignored) { } }); thread.start(); try { thread.join(); mRecyclerViewAdapter = new EventItemsAdapter(mList, mContext); mRecyclerViewAdapter.setHasStableIds(true); mRecyclerView.post(() -> { mRecyclerView.setAdapter(mRecyclerViewAdapter); setRecyclerViewAnim(mRecyclerView); }); } catch (InterruptedException e) { e.printStackTrace(); } } public boolean isRefresh() { return mSwipeRefreshLayout.isRefreshing(); } }
true
186a0d025ac7f64d22f99e778f22732a1e7ccb9d
Java
rbaral/Coding-Challenge
/new_practice/leetcode/BoxStacking.java
UTF-8
2,244
3.9375
4
[]
no_license
/** Box stacking You have a stack of n boxes, with widths w., heights l\ and depths dr The boxes cannot be rotated and can only be stacked on top of one another if each box in the stack is strictly larger than the box above it in width, height, and depth. Implement a method to build the tallest stack possible, where the heigh t of a stack is the sum of the heights of each box. */ import java.util.*; class Box{ int length, width, height; Box(){} Box(int l, int w, int h){ length = l; width = w; height = h; } //if this box can be above another box b boolean canBeAbove(Box b){ if(b==null) return true; if(length<b.length && width<b.width && height<b.height){ return true; } return false; } //if this box can be below another box b boolean canBeBelow(Box b){ if(b==null) return false; return b.canBeAbove(this); } public String toString() { return "Box(" + length + "," + width + "," + height + ")"; } } public class BoxStacking{ /** use dp to solve the problem */ public static List<Box> createStackDP(Box[] boxes, Box bottom, HashMap<Box, List<Box>> boxmap){ if(bottom!=null && boxmap.containsKey(bottom)){ return boxmap.get(bottom);//.clone(); } int maxheight = 0; List<Box> maxstack = null; for(int i=0;i<boxes.length; i++){ if(boxes[i].canBeAbove(bottom)){ List<Box> newstack = createStackDP(boxes, boxes[i], boxmap); int newheight = findStackHeight(newstack); if(newheight>maxheight){ maxheight = newheight; maxstack = newstack; } } } if(maxstack==null){ maxstack = new ArrayList<Box>(); } if(bottom!=null){ maxstack.add(0, bottom); } boxmap.put(bottom, maxstack); return maxstack; } public static int findStackHeight(List<Box> boxlist){ int height = 0; for(Box b:boxlist){ height+=b.height; } return height; } public static void main(String[] args) { Box[] boxes = { new Box(3, 4, 1), new Box(8, 6, 2), new Box(7, 8, 3), new Box(1,1,0)}; List<Box> stack = createStackDP(boxes, null, new HashMap<Box, List<Box>>()); //ArrayList<Box> stack = createStackR(boxes, null); for (int i = stack.size() - 1; i >= 0; i--) { Box b = stack.get(i); System.out.println(b.toString()); } } }
true
6db34308807b6bb9e7d310902655c9e0f2dc5770
Java
perecullera/ioc_geodroid-geodroid
/app/src/main/java/com/example/io/myapplication/Dispositiu.java
UTF-8
2,068
2.3125
2
[]
no_license
package com.example.io.myapplication; import com.google.android.gms.maps.model.LatLng; /** * Created by Victor LLucià, Ricard Moya on 31/3/15. */ public class Dispositiu { //TODO generate atributes, getters and setters private String id_dispositiu; private String id_flota; private Double longitud; private Double latitud; private String vehicle; private String carrega; private String id_empresa; private String id_usuari; private String nom; public Dispositiu(){ } public Dispositiu(String id, String nom,String flota, String vehicle){ this.id_dispositiu = id; this.id_flota = flota; this.vehicle = vehicle; this.nom = nom; } public void setId(String id){ this.id_dispositiu=id; } public void setFlota(String flota){ this.id_flota = flota; } public void setNom(String nom){ this.nom = nom; } public void setPosition(Double longitud, Double latitud){ this.longitud = longitud; this.latitud = latitud; } public void setVehicle(String vehicle){ this.vehicle=vehicle; } public void setCarrega(String Carrega){ this.carrega = carrega; } public void setEmpresa(String empresa){ this.id_empresa = empresa; } public void setUsuari(String usuari){ this.id_usuari = usuari; } public String getId(){ return id_dispositiu; } public String getFlota(){ return id_flota; } public Double getLong(){ return longitud; } public Double getLat(){ return latitud; } public String getVehicle(){ return vehicle; } public String getCarrega(){ return carrega; } public String getId_empresa(){ return id_empresa; } public String getId_usuari(){ return id_usuari; } public LatLng getPosition() { LatLng latlong = new LatLng(latitud, longitud); return latlong; } public String getNom() { return nom; } }
true
f3624b54600e75f19b5032f0b23c44898d08b17d
Java
Yahya222/CGRA-Versuch
/Amidar/src/apps/de/amidar/HelloWorld.java
UTF-8
105
1.523438
2
[]
no_license
package de.amidar; public class HelloWorld{ public static void main(String[] args) { int i=1; } }
true
50760da9182cb37ca26e072b7bc6bc9a95535025
Java
clilystudio/NetBook
/allsrc/com/koushikdutta/async/http/filter/e.java
UTF-8
842
1.742188
2
[ "Unlicense" ]
permissive
package com.koushikdutta.async.http.filter; import com.koushikdutta.async.I; import com.koushikdutta.async.S; import com.koushikdutta.async.y; final class e implements S<byte[]> { boolean a; private int e; e(d paramd, y paramy, I paramI) { } private void a() { I localI = new I(this.b); h localh = new h(this); if ((0x8 & this.e) != 0) { localI.a(0, localh); return; } if ((0x10 & this.e) != 0) { localI.a(0, localh); return; } b(); } private void b() { if (this.a) { this.c.a(2, new i(this)); return; } this.d.a = false; this.d.a(this.b); } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.koushikdutta.async.http.filter.e * JD-Core Version: 0.6.0 */
true
0106d7ed0f9e30a62462d8e8a0d3303a58083b68
Java
mowuwalixilo/car
/src/main/java/com/car/entity/vo/ChannelVo.java
UTF-8
388
1.6875
2
[]
no_license
package com.car.entity.vo; import com.car.entity.TbChannelEntity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; /** * @author mowuwalixilo * @date2020/12/18 16:59 */ @Data @ToString @NoArgsConstructor @AllArgsConstructor public class ChannelVo { private TbChannelEntity channelEntity; private String image; }
true
7462c63565ff2a6467e51b1958e3527d2c00edfe
Java
olealgoritme/smittestopp_src
/v1.1.2/decompiled/d/e/a/e.java
UTF-8
2,669
1.851563
2
[]
no_license
package d.e.a; import android.content.res.ColorStateList; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.Outline; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffColorFilter; import android.graphics.Rect; import android.graphics.drawable.Drawable; public class e extends Drawable { public float a; public float b; public boolean c; public boolean d; public ColorStateList e; public PorterDuffColorFilter f; public ColorStateList g; public PorterDuff.Mode h; public final PorterDuffColorFilter a(ColorStateList paramColorStateList, PorterDuff.Mode paramMode) { if ((paramColorStateList != null) && (paramMode != null)) { return new PorterDuffColorFilter(paramColorStateList.getColorForState(getState(), 0), paramMode); } return null; } public final void a(Rect paramRect) { Rect localRect = paramRect; if (paramRect == null) { localRect = getBounds(); } int i = left; throw null; } public void draw(Canvas paramCanvas) { if (f == null) { float f1 = a; paramCanvas.drawRoundRect(null, f1, f1, null); return; } throw null; } public int getOpacity() { return -3; } public void getOutline(Outline paramOutline) { paramOutline.setRoundRect(null, a); } public boolean isStateful() { ColorStateList localColorStateList = g; if ((localColorStateList == null) || (!localColorStateList.isStateful())) { localColorStateList = e; if (((localColorStateList == null) || (!localColorStateList.isStateful())) && (!super.isStateful())) {} } else { return true; } boolean bool = false; return bool; } public void onBoundsChange(Rect paramRect) { super.onBoundsChange(paramRect); a(paramRect); throw null; } public boolean onStateChange(int[] paramArrayOfInt) { ColorStateList localColorStateList = e; localColorStateList.getColorForState(paramArrayOfInt, localColorStateList.getDefaultColor()); throw null; } public void setAlpha(int paramInt) { throw null; } public void setColorFilter(ColorFilter paramColorFilter) { throw null; } public void setTintList(ColorStateList paramColorStateList) { g = paramColorStateList; f = a(paramColorStateList, h); invalidateSelf(); } public void setTintMode(PorterDuff.Mode paramMode) { h = paramMode; f = a(g, paramMode); invalidateSelf(); } } /* Location: * Qualified Name: d.e.a.e * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
true
b4e90750b6f314732d32951ebd6e3ff84c3044e3
Java
yaojf/springboot
/src/main/java/com/yaojiafeng/springboot/domain/Order.java
UTF-8
1,030
2.546875
3
[]
no_license
package com.yaojiafeng.springboot.domain; import com.yaojiafeng.springboot.statemachine.OrderStatus; /** * @author yaojiafeng * @create 2018-01-11 上午11:17 */ public class Order { private Integer id; private Integer orderId; private OrderStatus status; public Order() { } public Order(Integer orderId, OrderStatus status) { this.orderId = orderId; this.status = status; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; } public OrderStatus getStatus() { return status; } public void setStatus(OrderStatus status) { this.status = status; } @Override public String toString() { return "Order{" + "orderId=" + orderId + ", status=" + status + '}'; } }
true
2701c471a490ecf9d9c9300d1563f01ea2698af0
Java
kordamp/ikonli
/icon-packs/ikonli-medicons-pack/src/main/java/org/kordamp/ikonli/medicons/Medicons.java
UTF-8
10,065
2.140625
2
[ "Apache-2.0" ]
permissive
/* * SPDX-License-Identifier: Apache-2.0 * * Copyright 2015-2023 Andres Almiray * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kordamp.ikonli.medicons; import org.kordamp.ikonli.Ikon; /** * @author Andres Almiray */ public enum Medicons implements Ikon { ACCESSIBILITY("medicon-accessibility", '\ue643'), ACCESSIBILITY_SQUARE("medicon-accessibility-square", '\ue671'), ADMINISTRATION("medicon-administration", '\ue624'), ADMINISTRATION_SQUARE("medicon-administration-square", '\ue670'), ALTERNATIVE_COMPLEMENTARY("medicon-alternative-complementary", '\ue623'), ALTERNATIVE_COMPLEMENTARY_SQUARE("medicon-alternative-complementary-square", '\ue66f'), AMBULANCE("medicon-ambulance", '\ue622'), AMBULANCE_SQUARE("medicon-ambulance-square", '\ue66e'), ANESTHESIA("medicon-anesthesia", '\ue621'), ANESTHESIA_SQUARE("medicon-anesthesia-square", '\ue66d'), BILLING("medicon-billing", '\ue620'), BILLING_SQUARE("medicon-billing-square", '\ue66c'), CARDIOLOGY("medicon-cardiology", '\ue61f'), CARDIOLOGY_SQUARE("medicon-cardiology-square", '\ue66b'), CARE_STAFF_AREA("medicon-care-staff-area", '\ue642'), CARE_STAFF_AREA_SQUARE("medicon-care-staff-area-square", '\ue68d'), CATH_LAB("medicon-cath-lab", '\ue641'), CATH_LAB_SQUARE("medicon-cath-lab-square", '\ue68c'), CHAPEL("medicon-chapel", '\ue640'), CHAPEL_SQUARE("medicon-chapel-square", '\ue68b'), COFFEE_SHOP("medicon-coffee-shop", '\ue63f'), COFFEE_SHOP_SQUARE("medicon-coffee-shop-square", '\ue68a'), DENTAL("medicon-dental", '\ue63e'), DENTAL_SQUARE("medicon-dental-square", '\ue689'), DERMATOLOGY("medicon-dermatology", '\ue63d'), DERMATOLOGY_SQUARE("medicon-dermatology-square", '\ue68f'), DIABETES_EDUCATION("medicon-diabetes-education", '\ue644'), DIABETES_EDUCATION_SQUARE("medicon-diabetes-education-square", '\ue66a'), DRINKING_FOUNTAIN("medicon-drinking-fountain", '\ue61e'), DRINKING_FOUNTAIN_SQUARE("medicon-drinking-fountain-square", '\ue669'), EAR_NOSE_THROAT("medicon-ear-nose-throat", '\ue61d'), EAR_NOSE_THROAT_SQUARE("medicon-ear-nose-throat-square", '\ue668'), ELEVATORS("medicon-elevators", '\ue61c'), ELEVATORS_SQUARE("medicon-elevators-square", '\ue667'), EMERGENCY("medicon-emergency", '\ue61b'), EMERGENCY_SQUARE("medicon-emergency-square", '\ue666'), FAMILY_PRACTICE("medicon-family-practice", '\ue61a'), FAMILY_PRACTICE_SQUARE("medicon-family-practice-square", '\ue665'), FIRE_EXTINGUISHER("medicon-fire-extinguisher", '\ue619'), FIRE_EXTINGUISHER_SQUARE("medicon-fire-extinguisher-square", '\ue664'), FIRST_AID("medicon-first-aid", '\ue63c'), FIRST_AID_SQUARE("medicon-first-aid-square", '\ue688'), GENETICS("medicon-genetics", '\ue63b'), GENETICS_SQUARE("medicon-genetics-square", '\ue687'), GIFT_SHOP("medicon-gift-shop", '\ue63a'), GIFT_SHOP_SQUARE("medicon-gift-shop-square", '\ue686'), HEALTH_EDUCATION("medicon-health-education", '\ue639'), HEALTH_EDUCATION_SQUARE("medicon-health-education-square", '\ue685'), HEALTH_SERVICES("medicon-health-services", '\ue638'), HEALTH_SERVICES_SQUARE("medicon-health-services-square", '\ue684'), HEARING_ASSISTANCE("medicon-hearing-assistance", '\ue637'), HEARING_ASSISTANCE_SQUARE("medicon-hearing-assistance-square", '\ue683'), HOSPITAL("medicon-hospital", '\ue645'), HOSPITAL_SQUARE("medicon-hospital-square", '\ue663'), IMAGING_ALTERNATIVE_CT("medicon-imaging-alternative-ct", '\ue618'), IMAGING_ALTERNATIVE_CT_SQUARE("medicon-imaging-alternative-ct-square", '\ue662'), IMAGING_ALTERNATIVE_MRI("medicon-imaging-alternative-mri", '\ue616'), IMAGING_ALTERNATIVE_MRI_SQUARE("medicon-imaging-alternative-mri-square", '\ue660'), IMAGING_ALTERNATIVE_MRI_TWO("medicon-imaging-alternative-mri-two", '\ue617'), IMAGING_ALTERNATIVE_MRI_TWO_SQUARE("medicon-imaging-alternative-mri-two-square", '\ue661'), IMAGING_ALTERNATIVE_PET("medicon-imaging-alternative-pet", '\ue615'), IMAGING_ALTERNATIVE_PET_SQUARE("medicon-imaging-alternative-pet-square", '\ue65f'), IMAGING_ROOT_CATEGORY("medicon-imaging-root-category", '\ue614'), IMAGING_ROOT_CATEGORY_SQUARE("medicon-imaging-root-category-square", '\ue65e'), IMMUNIZATIONS("medicon-immunizations", '\ue613'), IMMUNIZATIONS_SQUARE("medicon-immunizations-square", '\ue65d'), INFECTIOUS_DISEASES("medicon-infectious-diseases", '\ue636'), INFECTIOUS_DISEASES_SQUARE("medicon-infectious-diseases-square", '\ue682'), INFORMATION_US("medicon-information-us", '\ue635'), INFORMATION_US_SQUARE("medicon-information-us-square", '\ue681'), INPATIENT("medicon-inpatient", '\ue634'), INPATIENT_SQUARE("medicon-inpatient-square", '\ue680'), INTENSIVE_CARE("medicon-intensive-care", '\ue633'), INTENSIVE_CARE_SQUARE("medicon-intensive-care-square", '\ue67f'), INTERNAL_MEDICINE("medicon-internal-medicine", '\ue632'), INTERNAL_MEDICINE_SQUARE("medicon-internal-medicine-square", '\ue67e'), INTERPRETER_SERVICES("medicon-interpreter-services", '\ue631'), INTERPRETER_SERVICES_SQUARE("medicon-interpreter-services-square", '\ue67d'), KIDNEY("medicon-kidney", '\ue646'), KIDNEY_SQUARE("medicon-kidney-square", '\ue65c'), LABORATORY("medicon-laboratory", '\ue611'), LABORATORY_SQUARE("medicon-laboratory-square", '\ue65a'), LABOR_DELIVERY("medicon-labor-delivery", '\ue612'), LABOR_DELIVERY_SQUARE("medicon-labor-delivery-square", '\ue65b'), MAMMOGRAPHY("medicon-mammography", '\ue610'), MAMMOGRAPHY_SQUARE("medicon-mammography-square", '\ue659'), MEDICAL_LIBRARY("medicon-medical-library", '\ue60f'), MEDICAL_LIBRARY_SQUARE("medicon-medical-library-square", '\ue658'), MEDICAL_RECORDS("medicon-medical-records", '\ue60e'), MEDICAL_RECORDS_SQUARE("medicon-medical-records-square", '\ue657'), MENTAL_HEALTH("medicon-mental-health", '\ue60d'), MENTAL_HEALTH_SQUARE("medicon-mental-health-square", '\ue656'), MRI_PET("medicon-mri-pet", '\ue630'), MRI_PET_SQUARE("medicon-mri-pet-square", '\ue67c'), NEUROLOGY("medicon-neurology", '\ue62f'), NEUROLOGY_SQUARE("medicon-neurology-square", '\ue67b'), NO_SMOKING("medicon-no-smoking", '\ue62e'), NO_SMOKING_SQUARE("medicon-no-smoking-square", '\ue67a'), NURSERY("medicon-nursery", '\ue62d'), NURSERY_SQUARE("medicon-nursery-square", '\ue679'), NUTRITION("medicon-nutrition", '\ue62c'), NUTRITION_SQUARE("medicon-nutrition-square", '\ue678'), ONCOLOGY("medicon-oncology", '\ue62b'), ONCOLOGY_SQUARE("medicon-oncology-square", '\ue677'), OPHTHALMOLOGY("medicon-ophthalmology", '\ue647'), OPHTHALMOLOGY_SQUARE("medicon-ophthalmology-square", '\ue655'), OUTPATIENT("medicon-outpatient", '\ue60c'), OUTPATIENT_SQUARE("medicon-outpatient-square", '\ue654'), PATHOLOGY("medicon-pathology", '\ue60b'), PATHOLOGY_SQUARE("medicon-pathology-square", '\ue653'), PEDIATRICS("medicon-pediatrics", '\ue60a'), PEDIATRICS_SQUARE("medicon-pediatrics-square", '\ue652'), PHARMACY("medicon-pharmacy", '\ue609'), PHARMACY_SQUARE("medicon-pharmacy-square", '\ue651'), PHYSICAL_THERAPY("medicon-physical-therapy", '\ue608'), PHYSICAL_THERAPY_SQUARE("medicon-physical-therapy-square", '\ue650'), RADIOLOGY("medicon-radiology", '\ue607'), RADIOLOGY_SQUARE("medicon-radiology-square", '\ue64f'), REGISTRATION("medicon-registration", '\ue62a'), REGISTRATION_SQUARE("medicon-registration-square", '\ue68e'), RESPIRATORY("medicon-respiratory", '\ue629'), RESPIRATORY_SQUARE("medicon-respiratory-square", '\ue676'), RESTAURANT("medicon-restaurant", '\ue628'), RESTAURANT_SQUARE("medicon-restaurant-square", '\ue675'), RESTROOMS("medicon-restrooms", '\ue627'), RESTROOMS_SQUARE("medicon-restrooms-square", '\ue674'), SMOKING("medicon-smoking", '\ue626'), SMOKING_SQUARE("medicon-smoking-square", '\ue673'), SOCIAL_SERVICES("medicon-social-services", '\ue625'), SOCIAL_SERVICES_SQUARE("medicon-social-services-square", '\ue672'), STAIRS("medicon-stairs", '\ue606'), STAIRS_SQUARE("medicon-stairs-square", '\ue64e'), SURGERY("medicon-surgery", '\ue605'), SURGERY_SQUARE("medicon-surgery-square", '\ue64d'), TEXT_TELEPHONE("medicon-text-telephone", '\ue604'), TEXT_TELEPHONE_SQUARE("medicon-text-telephone-square", '\ue64c'), ULTRASOUND("medicon-ultrasound", '\ue603'), ULTRASOUND_SQUARE("medicon-ultrasound-square", '\ue64b'), VOLUME_CONTROL("medicon-volume-control", '\ue602'), VOLUME_CONTROL_SQUARE("medicon-volume-control-square", '\ue64a'), WAITING_AREA("medicon-waiting-area", '\ue601'), WAITING_AREA_SQUARE("medicon-waiting-area-square", '\ue649'), WOMENS_HEALTH("medicon-womens-health", '\ue600'), WOMENS_HEALTH_SQUARE("medicon-womens-health-square", '\ue648'); public static Medicons findByDescription(String description) { for (Medicons font : values()) { if (font.getDescription().equals(description)) { return font; } } throw new IllegalArgumentException("Icon description '" + description + "' is invalid!"); } private String description; private int code; Medicons(String description, int code) { this.description = description; this.code = code; } @Override public String getDescription() { return description; } @Override public int getCode() { return code; } }
true
a69672f3458594e4e39073e2ae9ca3a65e14698c
Java
jackyu86/sourceLib
/link-to-world/.svn/pristine/a6/a69672f3458594e4e39073e2ae9ca3a65e14698c.svn-base
UTF-8
1,205
2.25
2
[]
no_license
package io.sited.customer.web.controller; import io.sited.customer.api.CustomerWebService; import io.sited.customer.api.customer.CustomerResponse; import io.sited.customer.api.customer.UpdateCustomerRequest; import io.sited.http.GET; import io.sited.http.PUT; import io.sited.http.Path; import io.sited.http.Request; import io.sited.user.web.User; import javax.inject.Inject; import java.io.IOException; /** * @author chi */ public class CustomerAJAXController { @Inject CustomerWebService customerWebService; @Path("/ajax/customer/:customerId") @GET public CustomerResponse get(Request request) { String id = request.pathParam("customerId"); return customerWebService.get(id); } @Path("/ajax/customer/self") @GET public CustomerResponse self(Request request) { return customerWebService.get(request.require(User.class).id); } @Path("/ajax/customer/self") @PUT public CustomerResponse update(Request request) throws IOException { UpdateCustomerRequest customerRequest = request.body(UpdateCustomerRequest.class); return customerWebService.update(request.require(User.class).id, customerRequest); } }
true
3e6657f7b2a5a55655eaa4a3324e222985d9c28a
Java
tomatoguo/Android-Training
/toolbar/src/main/java/com/guoyonghui/toolbar/DrawerMenuAdapter.java
UTF-8
2,164
2.625
3
[]
no_license
package com.guoyonghui.toolbar; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; public class DrawerMenuAdapter extends ArrayAdapter<DrawerMenuItemLab.DrawerMenuItem> { private int mSelectedPosition = 0; private int mMenuItemBgResource; private ArrayList<DrawerMenuItemLab.DrawerMenuItem> mMenuItems; public DrawerMenuAdapter(Context context, int resource, ArrayList<DrawerMenuItemLab.DrawerMenuItem> objects) { super(context, resource, objects); mMenuItemBgResource = resource; mMenuItems = objects; } @Override public int getCount() { return mMenuItems.size(); } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder VH; if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(mMenuItemBgResource, parent, false); VH = new ViewHolder(); VH.contentTextView = (TextView) convertView.findViewById(R.id.menu_item_content); convertView.setTag(VH); } else { VH = (ViewHolder) convertView.getTag(); } DrawerMenuItemLab.DrawerMenuItem menuItem = mMenuItems.get(position); VH.contentTextView.setText(menuItem.getContent()); VH.contentTextView.setTextColor(getContext().getResources().getColor(position == mSelectedPosition ? android.R.color.white : android.R.color.darker_gray)); VH.contentTextView.setBackgroundResource(position == mSelectedPosition ? android.R.color.darker_gray : android.R.color.white); return convertView; } public void setSelectedPosition(int selectedPosition) { mSelectedPosition = selectedPosition; notifyDataSetChanged(); } public int getSelectedPosition() { return mSelectedPosition; } /** * 使用ViewHolder模式优化ListView加载效率 */ private class ViewHolder { private TextView contentTextView; } }
true
771bb79a6a8544794eb575d136cb0aca44345f51
Java
lopesdasilva/aTrakt
/Trakt-fragments/src/main/java/com/lopesdasilva/trakt/alarms/MyAlarmReceiver.java
UTF-8
7,400
1.976563
2
[]
no_license
package com.lopesdasilva.trakt.alarms; import android.annotation.TargetApi; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.widget.Toast; import com.jakewharton.trakt.ServiceManager; import com.jakewharton.trakt.entities.CalendarDate; import com.lopesdasilva.trakt.R; import com.lopesdasilva.trakt.Tasks.DownloadDayCalendar; import com.lopesdasilva.trakt.activities.EpisodesTonightActivity; import com.lopesdasilva.trakt.extras.UserChecker; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by lopesdasilva on 18/05/13. */ public class MyAlarmReceiver extends BroadcastReceiver implements DownloadDayCalendar.OnDayCalendarTaskCompleted { public static final String PREFS_NAME = "TraktPrefsFile"; private final String REMINDER_BUNDLE = "MyReminderBundle"; private ServiceManager manager; private Context context; // this constructor is called by the alarm manager. public MyAlarmReceiver() { } // you can use this constructor to create the alarm. // Just pass in the main activity as the context, // any extras you'd like to get later when triggered // and the timeout public MyAlarmReceiver(Context context, Bundle extras, int timeoutInHours) { AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(context, MyAlarmReceiver.class); intent.putExtra(REMINDER_BUNDLE, extras); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Calendar time = Calendar.getInstance(); // time.setTimeInMillis(System.currentTimeMillis()); // time.add(Calendar.SECOND, 60); // alarmMgr.set(AlarmManager.ELAPSED_REALTIME, time.getTimeInMillis(), // pendingIntent); // Calendar calendar = Calendar.getInstance(); // calendar.set(Calendar.HOUR_OF_DAY, 19); // calendar.set(Calendar.MINUTE, 30); // calendar.set(Calendar.SECOND, 0); // // // alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); // Set the alarm to start at approximately 2:00 p.m. Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 19); // With setInexactRepeating(), you have to use one of the AlarmManager interval // constants--in this case, AlarmManager.INTERVAL_DAY. alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); } @Override public void onReceive(Context context, Intent intent) { SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0); String mUsername = settings.getString("username", null); if (mUsername != null) { if (intent != null && intent.getAction() != null && intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { Log.d("Trakt it", "Android reboot rescheduling alarm to get shows tonight"); Bundle bundle = new Bundle(); // add extras here.. MyAlarmReceiver alarm = new MyAlarmReceiver(context, bundle, 24); } else { this.context = context; // here you can get the extras you passed in when creating the alarm //intent.getBundleExtra(REMINDER_BUNDLE)); Log.d("Trakt Fragments", "The alarm has ended"); Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show(); manager = UserChecker.checkUserLogin(context); if (manager != null) new DownloadDayCalendar(this, manager, new Date()).execute(); } } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Override public void OnDayCalendarTaskCompleted(List<CalendarDate> response) { Bundle arguments = new Bundle(); if (response.size() != 0) { arguments.putSerializable("CalendarTonight", response.get(0)); Log.d("Trakt", "Alarm a arguments send:" + response.get(0).episodes.size()); Intent episodes_tonight = new Intent(context, EpisodesTonightActivity.class); episodes_tonight.putExtras(arguments); PendingIntent intent = PendingIntent.getActivity(context, 0, episodes_tonight, PendingIntent.FLAG_ONE_SHOT); if (response.size() != 0) if (response.get(0).episodes.size() != 0) { Notification.Builder build = new Notification.Builder(context); if (response.get(0).episodes.size() == 1) { SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm"); build.setContentTitle(response.get(0).episodes.get(0).show.title + " on tonight") .setContentInfo(dateFormat.format(response.get(0).episodes.get(0).episode.firstAired)) .setContentText("S" + response.get(0).episodes.get(0).episode.season + "E" + response.get(0).episodes.get(0).episode.number + " " + response.get(0).episodes.get(0).episode.title) .setTicker(response.get(0).episodes.get(0).show.title + " on tonight " + "S" + response.get(0).episodes.get(0).episode.season + "E" + response.get(0).episodes.get(0).episode.number + " " + response.get(0).episodes.get(0).episode.title); } else { build.setContentTitle("You have " + response.get(0).episodes.size() + " TV shows on tonight") .setContentText("Click to see more") .setTicker("You have " + response.get(0).episodes.size() + " TV shows on tonight"); } build // .setContentInfo("S" + episode_info.episode.season + "E" + episode_info.episode.number) // .setContentIntent(intent) .setSmallIcon(R.drawable.ic_notifications); NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); // if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { // // AQuery aq= // Notification notification = new Notification // .BigPictureStyle(build) // .bigPicture(episodeScreen) // .setBigContentTitle("Your are watching") // .setSummaryText(episode_info.movie.title) // .build(); // mNotificationManager.notify(0, notification); // } else { mNotificationManager.notify(0, build.build()); // } } } } }
true
5e07430b6742562003af2182668707d785b46eaa
Java
nuswufei/LCrecorder
/Convert Sorted List to Binary Search Tree.java
UTF-8
822
3.078125
3
[]
no_license
public class Solution { public TreeNode sortedListToBST(ListNode head) { if(head == null) return null; ListNode dummyNode = new ListNode(0); dummyNode.next = head; ListNode cur = head; int count = 0; while(cur != null) { ++count; cur = cur.next; } int rootIndex = (count - 1) >> 1; ListNode rootNode = moveN(head, rootIndex); TreeNode root = new TreeNode(rootNode.val); ListNode leftEnd = moveN(dummyNode, rootIndex); leftEnd.next = null; root.left = sortedListToBST(dummyNode.next); root.right = sortedListToBST(rootNode.next); return root; } ListNode moveN(ListNode head, int n) { for(int i = 0; i < n; ++i) head = head.next; return head; } }
true
d98b2613ecf456053c8a93c413dfbf9ccda3a062
Java
TheCosmere64/Portfolio
/2017/Pizza-Palace/src/asgn2Tests/RestaurantPizzaTests.java
UTF-8
2,684
3.09375
3
[]
no_license
package asgn2Tests; import static org.junit.Assert.*; import java.time.LocalTime; import org.junit.Before; import org.junit.Test; import asgn2Exceptions.CustomerException; import asgn2Exceptions.LogHandlerException; import asgn2Exceptions.PizzaException; import asgn2Pizzas.*; import asgn2Restaurant.PizzaRestaurant; /** * A class that tests the methods relating to the handling of Pizza objects in the asgn2Restaurant.PizzaRestaurant class as well as * processLog and resetDetails. * * * * @author Person B * */ public class RestaurantPizzaTests { PizzaRestaurant pizzaRes; PizzaRestaurant largerRes; //JUST PIZZA OBJECTS @Before public void instantiatePizzaObjects() throws PizzaException, LogHandlerException, CustomerException { pizzaRes = new PizzaRestaurant(); largerRes = new PizzaRestaurant(); pizzaRes.processLog("logs\\20170101.txt"); largerRes.processLog("logs\\20170103.txt"); } //Testing getting a pizza by index @Test public void getPizzaNormal() throws PizzaException { pizzaRes.getPizzaByIndex(0); } //Testing a normal case @Test public void getPizzaLargerNormal() throws PizzaException { largerRes.getPizzaByIndex(50); } //Testing getting a pizza by index (there is only 3 pizza objects contained in this logfile @Test public void getPizzaBoundary() throws PizzaException { pizzaRes.getPizzaByIndex(2); } //There is one hundred pizza objects in this file, testing the bounds @Test public void getPizzaLargerBoundary() throws PizzaException { largerRes.getPizzaByIndex(99); } //Testing the amount of pizza objects @Test public void getCustomers() throws PizzaException { assertEquals(3, pizzaRes.getNumPizzaOrders()); } @Test public void getCustomersLargerRestaurant() throws PizzaException { assertEquals(100, largerRes.getNumPizzaOrders()); } //Testing the total order profit using a forloop to iterate through the pizza objects to get the total delivery distance and comparing it to what the method found @Test public void totalDeliveryDistance() throws PizzaException { double totalDistance = 0; for (int i = 0; i < largerRes.getNumPizzaOrders(); i++) { totalDistance += largerRes.getPizzaByIndex(i).getOrderProfit(); } assertEquals(totalDistance, largerRes.getTotalProfit(), 1); } //Testing to see if it resets the details properly @Test public void resetTest() throws PizzaException { largerRes.resetDetails(); } //Testing if it will return a pizza object even after the details have been reset @Test(expected = PizzaException.class) public void resetTestProper() throws PizzaException { largerRes.resetDetails(); largerRes.getPizzaByIndex(0); } }
true
55fd49c4d1e380fc1595ed1ae22e6065c0330717
Java
wani095/AgroMwinda
/app/src/main/java/com/icon/agromwinda/UI/Adapter/ListSecteurAdapter.java
UTF-8
2,458
2.203125
2
[]
no_license
package com.icon.agromwinda.UI.Adapter; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.google.gson.Gson; import com.icon.agromwinda.Data.model.Province; import com.icon.agromwinda.Data.model.Secteur; import com.icon.agromwinda.R; import org.json.JSONObject; import java.util.List; public class ListSecteurAdapter extends RecyclerView.Adapter<ListSecteurAdapter.SecteurViewHolder> { private Context context; private LayoutInflater inflater; private List<Secteur> secteurs; private Activity activity; public ListSecteurAdapter(Context context,List<Secteur> secteurs,Activity activity){ this.context = context; this.inflater = LayoutInflater.from(context); this.secteurs = secteurs; this.activity=activity; } @NonNull @Override public SecteurViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view = inflater.inflate(R.layout.row_secteur, viewGroup, false); return new SecteurViewHolder(view); } @Override public void onBindViewHolder(@NonNull final SecteurViewHolder secteurViewHolder,final int i) { secteurViewHolder.txNom_secteur.setText(secteurs.get(i).getNom()); secteurViewHolder.row_secteur.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(); Log.d("SECTEURDATA",new Gson().toJson(secteurs.get(i))); intent.putExtra("data",new Gson().toJson(secteurs.get(i))); activity.setResult(81,intent); activity.finish(); } }); } @Override public int getItemCount() { return secteurs.size(); } public class SecteurViewHolder extends RecyclerView.ViewHolder{ LinearLayout row_secteur; TextView txNom_secteur; public SecteurViewHolder(@NonNull View itemView) { super(itemView); txNom_secteur=itemView.findViewById(R.id.txNom_secteur); row_secteur=itemView.findViewById(R.id.row_secteur); } } }
true
2609dd1fa12987e1724d3a4a7a06b9f8f4ae0fbe
Java
mrkanet/PrinterTablet
/app/src/main/java/net/mrkaan/printer/services/PrintCompleteService.java
UTF-8
148
1.695313
2
[]
no_license
package net.mrkaan.printer.services; public interface PrintCompleteService { void onMessage(int status); void respondAfterWifiSwitch(); }
true
90a05ea289807e9c790841d9801f54483db410ad
Java
UncleTian/JavaDemo
/redisdemo/src/main/java/com/art2cat/dev/redisdemo/controller/UserController.java
UTF-8
1,608
2.265625
2
[]
no_license
package com.art2cat.dev.redisdemo.controller; import com.art2cat.dev.redisdemo.model.User; import com.art2cat.dev.redisdemo.repository.UserRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * com.art2cat.dev.redisdemo.controller * * @author art2c * @date 7/12/2018 */ @Controller @Slf4j public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/user/") public String index(Model model) { model.addAttribute("users", userRepository.findAll()); return "user_list"; } @RequestMapping(value = "/user/{id}", method = RequestMethod.GET) @Cacheable("user-key") public String getUserDetail(@PathVariable("id") Integer id, Model model) { User user = userRepository.getOne(id); log.info("get user: " + user); model.addAttribute("user", user); return "user"; } @RequestMapping(value = "/user/add", method = {RequestMethod.GET, RequestMethod.POST}) public String addToReadingList(User user) { user = userRepository.save(user); log.info("saved user: " + user); return "add_user"; } }
true
e05c0b5019f0d4dcba0d031cba45d7e358f54442
Java
dannyguarino/HiddenLeaf
/app/src/main/java/com/leaf/hiddenleadapp/Activites/ViewProfileActivity.java
UTF-8
2,222
1.953125
2
[]
no_license
package com.leaf.hiddenleadapp.Activites; import android.os.Bundle; import android.view.View; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.bumptech.glide.Glide; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.leaf.hiddenleadapp.R; import com.leaf.hiddenleadapp.UserModels.Users; import com.leaf.hiddenleadapp.databinding.ActivityViewProfileBinding; public class ViewProfileActivity extends AppCompatActivity { ActivityViewProfileBinding binding; FirebaseDatabase database; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityViewProfileBinding.inflate(getLayoutInflater()); database = FirebaseDatabase.getInstance(); setContentView(binding.getRoot()); String Userid = getIntent().getStringExtra("userID"); getSupportActionBar().setTitle("User profile"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); database.getReference("Users").child(Userid).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot snapshot) { Users user = snapshot.getValue(Users.class); binding.viewUserName.setText(user.getUserName()); binding.viewUserBio.setText(user.getUserBio()); binding.viewUserMail.setText(user.getMail()); Glide.with(ViewProfileActivity.this).load(user.getProfilePic()) .placeholder(R.drawable.avatar) .into(binding.profileView); } @Override public void onCancelled(@NonNull DatabaseError error) { } }); } @Override public boolean onSupportNavigateUp() { finish(); return super.onSupportNavigateUp(); } }
true
c69e0a2eb903e40f33098f23501df7753d9415df
Java
telf0rd/uChest
/src/main/java/com/ullarah/uchest/command/Reset.java
UTF-8
603
2.265625
2
[]
no_license
package com.ullarah.uchest.command; import com.ullarah.uchest.Init; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class Reset { public static void resetDonationChest(CommandSender sender) { if (sender.hasPermission("chest.reset") || !(sender instanceof Player)) { Init.getChestDonationInventory().clear(); Bukkit.broadcastMessage(Init.getMsgPrefix() + ChatColor.RED + "Donation Chest has been reset!"); } else sender.sendMessage(Init.getMsgPermDeny()); } }
true
0fa0a0246cdcb36f2d4468f4d0d9ad4eb1f6d670
Java
air-project/project-parent
/project-test/src/main/java/com/yh/hibernate/many2many/User.java
UTF-8
1,138
2.390625
2
[]
no_license
package com.yh.hibernate.many2many; /** * @author yh * @date 2014年9月7日 下午9:34:33 */ import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; private String name; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private List<Role> roles=new ArrayList<Role>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } }
true
a99d528697dfd4a5d58ca12127c85ed3dabee48c
Java
MyOralVillage/FinancialNumeracyGames
/app/src/main/java/com/myoralvillage/financialnumeracygames/Level1ActivityDemoQA.java
UTF-8
2,922
2.21875
2
[]
no_license
/* * Copyright 2016, 2019 MyOralVillage * All Rights Reserved */ package com.myoralvillage.financialnumeracygames; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; public class Level1ActivityDemoQA extends AppCompatActivity { private ImageButton mTrueButton; private ImageButton mFalseButton; private ImageView hImageViewPic; private ImageButton mFinish; private int currentImage = 0; int[] images = {R.drawable.owl0, R.drawable.owl1, R.drawable.owl2, R.drawable.owl3, R.drawable.owl4, R.drawable.owl5, R.drawable.owl6, R.drawable.owl7, R.drawable.owl8, R.drawable.owl9}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_level1_demoqa); startDemo(); } public void startDemo() { hImageViewPic = findViewById(R.id.imageView); mFalseButton = findViewById(R.id.false_button); mTrueButton = findViewById(R.id.true_button); mFinish = findViewById(R.id.finish_button); if (currentImage == 0) { mTrueButton.setVisibility(View.GONE); } mTrueButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currentImage--; mFalseButton.setVisibility(View.VISIBLE); mTrueButton.setVisibility(View.VISIBLE); mFinish.setVisibility(View.VISIBLE); currentImage = currentImage % images.length; if (currentImage == 0) { mTrueButton.setVisibility(View.GONE); } if (currentImage == 9) { mFalseButton.setVisibility(View.GONE); } hImageViewPic.setImageResource(images[currentImage]); } }); mFalseButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { currentImage++; mTrueButton.setVisibility(View.VISIBLE); mFalseButton.setVisibility(View.VISIBLE); currentImage = currentImage % images.length; if (currentImage == 0) { mTrueButton.setVisibility(View.GONE); } if (currentImage == 9) { mFalseButton.setVisibility(View.GONE); } hImageViewPic.setImageResource(images[currentImage]); } }); mFinish.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } public void exitDemo(View v) { finish(); } }
true
0df6a7836d16dcd89a1e5aec5a1c273916aa27ab
Java
perlovdinger/gloria1
/Gloria/ProcureMaterialDomain/src/main/java/com/volvo/gloria/procurematerial/util/migration/b/beans/WarehouseMigrationServiceBean.java
UTF-8
10,915
1.773438
2
[]
no_license
package com.volvo.gloria.procurematerial.util.migration.b.beans; import static com.volvo.gloria.procurematerial.util.migration.c.WarehouseMigrationHelper.filterMissingBinLocation; import static com.volvo.gloria.procurematerial.util.migration.c.WarehouseMigrationHelper.getAllBinLocationCodes; import static com.volvo.gloria.procurematerial.util.migration.c.WarehouseMigrationHelper.getValidList; import static com.volvo.gloria.procurematerial.util.migration.c.WarehouseMigrationHelper.populateAdditionalAttibutes; import static com.volvo.gloria.procurematerial.util.migration.c.WarehouseMigrationHelper.setAllCompanyCodes; import static com.volvo.gloria.procurematerial.util.migration.c.WarehouseMigrationHelper.setAllMaterialControllerTeams; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.volvo.gloria.authorization.b.UserServices; import com.volvo.gloria.authorization.c.TeamType; import com.volvo.gloria.authorization.d.entities.Team; import com.volvo.gloria.common.b.CommonServices; import com.volvo.gloria.common.c.PaginatedArrayList; import com.volvo.gloria.common.d.entities.CompanyCode; import com.volvo.gloria.common.d.entities.Site; import com.volvo.gloria.config.b.beans.ApplicationProperties; import com.volvo.gloria.procurematerial.util.migration.b.WarehouseMigrationService; import com.volvo.gloria.procurematerial.util.migration.c.WarehouseMigrationHelper; import com.volvo.gloria.procurematerial.util.migration.c.WarehouseNewTemplateExcelHandler; import com.volvo.gloria.procurematerial.util.migration.c.dto.MigrationStatusDTO; import com.volvo.gloria.procurematerial.util.migration.c.dto.WarehouseMigrationDTO; import com.volvo.gloria.util.GloriaApplicationException; import com.volvo.gloria.util.GloriaExceptionLogger; import com.volvo.gloria.util.IOUtil; import com.volvo.gloria.util.c.GloriaExceptionConstants; import com.volvo.gloria.warehouse.d.entities.BinLocation; import com.volvo.gloria.warehouse.repositories.b.WarehouseRepository; import com.volvo.jvs.runtime.servicesupport.ServiceLocator; public class WarehouseMigrationServiceBean implements WarehouseMigrationService { private static final Logger LOGGER = LoggerFactory.getLogger(WarehouseMigrationServiceBean.class); private static final int TEN = 10; private static final int HUNDRED = 100; private static final int MILLI = 1000; private boolean isDone = true; private StringBuilder statusText = new StringBuilder(); private int percentDone = 0; private String siteInProgress = ""; private String siteDone = ""; private static final int PAGE_SIZE = 20; private static final String NONOPERATIVE_WAREHOUSE = "/MigrationData/"; private static final String WAREHOUSE_DATA_PROPERTY_KEY = "MigrationData"; private static final String RESULT_FILE = "warehouse_<site>.csv"; private static final String RESULT_PATH = "C:\\Gloria\\migration\\wh\\result\\"; private static WarehouseRepository warehouseRepository; static { warehouseRepository = ServiceLocator.getService(WarehouseRepository.class); } @Override public MigrationStatusDTO getstatus() { MigrationStatusDTO migrationStatusDTO = new MigrationStatusDTO(); migrationStatusDTO.setDone(isDone); migrationStatusDTO.setSiteCompleted(siteDone); migrationStatusDTO.setCompleted(percentDone); migrationStatusDTO.setSiteInProgress(siteInProgress); migrationStatusDTO.setStatus(statusText.toString()); return migrationStatusDTO; } @Override public void initiateWarehouseMigration(Properties testDataProperties, String[] whToBeMigrated) throws GloriaApplicationException { isDone = false; statusText = new StringBuilder(); try { CommonServices commonServices = ServiceLocator.getService(CommonServices.class); UserServices userServices = ServiceLocator.getService(UserServices.class); String location = (String) testDataProperties.get(WAREHOUSE_DATA_PROPERTY_KEY); setAllMaterialControllerTeams(new HashSet<Team>(userServices.getTeams(TeamType.MATERIAL_CONTROL.toString()))); setAllCompanyCodes(new HashSet<CompanyCode>(commonServices.findAllCompanyCodes())); WarehouseMigrationHelper.setAllSitesInfo(new HashSet<Site>(commonServices.getAllSites())); // Read input excel for (String whSiteId : whToBeMigrated) { siteInProgress = "Warehouse - " + whSiteId; long start = System.currentTimeMillis(); Properties updatedDataProperties = new Properties(); updatedDataProperties.setProperty(WAREHOUSE_DATA_PROPERTY_KEY, location + whSiteId + File.separator); List<WarehouseMigrationDTO> warehouseMigrationDTOs = new ArrayList<WarehouseMigrationDTO>(); InputStream[] ins = getInputStreams(whSiteId); if (ins != null) { for (int i = 0; i < ins.length; i++) { log(whSiteId); WarehouseNewTemplateExcelHandler warehouseMigrationExcelHandler = new WarehouseNewTemplateExcelHandler(ins[i]); warehouseMigrationDTOs.addAll(warehouseMigrationExcelHandler.manageExcel()); List<WarehouseMigrationDTO> validDTOs = getValidList(warehouseMigrationDTOs); Set<String> binLocationCodes = getAllBinLocationCodes(warehouseMigrationDTOs); List<BinLocation> binLocations = warehouseRepository.findBinLocations(whSiteId, binLocationCodes); validDTOs = filterMissingBinLocation(validDTOs, binLocations); populateAdditionalAttibutes(validDTOs); PaginatedArrayList<WarehouseMigrationDTO> migrationDto = new PaginatedArrayList<WarehouseMigrationDTO>(validDTOs); migrationDto.setPageSize(PAGE_SIZE); int totalDone = 0, divisor = TEN, total = validDTOs.size(); for (List<WarehouseMigrationDTO> subList = null; (subList = migrationDto.nextPage()) != null;) { PerformWarehouseMigrationServiceBean serviceBean = ServiceLocator.getService(PerformWarehouseMigrationServiceBean.class); serviceBean.performWarehouseMigration(subList); totalDone += subList.size(); percentDone = (int) (totalDone * HUNDRED / total); if (percentDone >= divisor) { divisor += TEN; log(percentDone + "% - " + totalDone); } } generateReport(whSiteId, warehouseMigrationDTOs, getOutFilename(testDataProperties, whSiteId)); log(whSiteId + " took " + (System.currentTimeMillis() - start) / MILLI + " sec"); } } siteDone += (", " + whSiteId); siteInProgress = ""; } isDone = true; statusText = new StringBuilder(); siteInProgress = ""; } catch (Exception e) { GloriaExceptionLogger.log(e, WarehouseMigrationServiceBean.class); throw new GloriaApplicationException(GloriaExceptionConstants.DEFAULT_ERROR_CODE, "Failed to run Warehouse Migration!", e); } finally { statusText.append("\nDone"); } } private void generateReport(String whSiteId, List<WarehouseMigrationDTO> warehouseMigrationDTOs, String fileName) { if (warehouseMigrationDTOs != null && !warehouseMigrationDTOs.isEmpty()) { try { final File parentDir = new File(fileName).getParentFile(); if (null != parentDir) { parentDir.mkdirs(); } FileWriter writer = new FileWriter(fileName); int notMigrated = 0; int migrated = 0; // Add Header writer.append(WarehouseNewTemplateExcelHandler.HEADER); writer.append('\n'); for (WarehouseMigrationDTO warehouseMigrationDTO : warehouseMigrationDTOs) { if (!warehouseMigrationDTO.isMigrated()) { notMigrated++; } else { migrated++; } writer.append(warehouseMigrationDTO.toString()); writer.append('\n'); } writer.flush(); writer.close(); log("WH_" + whSiteId + " - " + migrated + " materials " + fileName); log("WH_" + whSiteId + " - " + notMigrated + " materials could not be migrated! " + fileName); } catch (IOException e) { GloriaExceptionLogger.log(e, WarehouseMigrationServiceBean.class); } } } private InputStream[] getInputStreams(String whSiteId) throws IOException { InputStream[] streams = null; String path = null; String warehouseMigrPath = "/data/MigrationData/" + whSiteId + "/"; String env = ServiceLocator.getService(ApplicationProperties.class).getEnvironment(); try { path = "initDB/" + env + warehouseMigrPath + "warehouse_*" + IOUtil.FILE_TYPE_EXCEL_NEW; streams = IOUtil.loadInputStreamFromClasspath(path); } catch (IOException e) { path = "initDB/" + "_global" + warehouseMigrPath + "warehouse_*" + IOUtil.FILE_TYPE_EXCEL_NEW; try { streams = IOUtil.loadInputStreamFromClasspath(path); } catch (Exception e1) { GloriaExceptionLogger.log(e1, WarehouseMigrationServiceBean.class); } } return streams; } private String getOutFilename(Properties testDataProperties, String whSiteId) { String outFilename; if (((String) testDataProperties.get(WAREHOUSE_DATA_PROPERTY_KEY)).startsWith(NONOPERATIVE_WAREHOUSE)) { outFilename = RESULT_PATH + (RESULT_FILE).replace("<site>", whSiteId); } else { String location = (String) testDataProperties.get(WAREHOUSE_DATA_PROPERTY_KEY); outFilename = location.replace("input", "result") + (RESULT_FILE).replace("<site>", whSiteId); } log("outFilename=" + outFilename); return outFilename; } private void log(String text) { statusText.append(text + "\n"); LOGGER.info(text); } }
true
f5453f706a299b9285a78b130aadb42c7e6677bc
Java
sumit-sardar/GitMigrationRepo01
/dep-base-ctrl/src/com/ctb/bean/testAdmin/ActiveSession.java
UTF-8
3,615
2.3125
2
[]
no_license
package com.ctb.bean.testAdmin; import com.ctb.bean.CTBBean; import java.util.Date; /** * ActiveSession.java * @author Nate_Cohen * * Data bean representing currently active sessions for a test. * orgNodeId and orgNodeName fields describe the node at which * the session was scheduled. */ public class ActiveSession extends CTBBean { static final long serialVersionUID = 1L; private Integer testAdminId; private String testAdminName; private String location; private Date loginStartDate; private Date loginEndDate; private Integer orgNodeId; private String orgNodeName; private String timeZone; private Date dailyLoginStartTime; private Date dailyLoginEndTime; /** * @return Returns the dailyLoginEndTime. */ public Date getDailyLoginEndTime() { return dailyLoginEndTime; } /** * @param dailyLoginEndTime The dailyLoginEndTime to set. */ public void setDailyLoginEndTime(Date dailyLoginEndTime) { this.dailyLoginEndTime = dailyLoginEndTime; } /** * @return Returns the dailyLoginStartTime. */ public Date getDailyLoginStartTime() { return dailyLoginStartTime; } /** * @param dailyLoginStartTime The dailyLoginStartTime to set. */ public void setDailyLoginStartTime(Date dailyLoginStartTime) { this.dailyLoginStartTime = dailyLoginStartTime; } /** * @return Returns the timeZone. */ public String getTimeZone() { return timeZone; } /** * @param timeZone The timeZone to set. */ public void setTimeZone(String timeZone) { this.timeZone = timeZone; } /** * @return Returns the orgNodeId. */ public Integer getOrgNodeId() { return orgNodeId; } /** * @param orgNodeId The orgNodeId to set. */ public void setOrgNodeId(Integer orgNodeId) { this.orgNodeId = orgNodeId; } /** * @return Returns the orgNodeName. */ public String getOrgNodeName() { return orgNodeName; } /** * @param orgNodeName The orgNodeName to set. */ public void setOrgNodeName(String orgNodeName) { this.orgNodeName = orgNodeName; } /** * @return Returns the location. */ public String getLocation() { return location; } /** * @param location The location to set. */ public void setLocation(String location) { this.location = location; } /** * @return Returns the testAdminId. */ public Integer getTestAdminId() { return testAdminId; } /** * @param testAdminId The testAdminId to set. */ public void setTestAdminId(Integer testAdminId) { this.testAdminId = testAdminId; } /** * @return Returns the testAdminName. */ public String getTestAdminName() { return testAdminName; } /** * @param testAdminName The testAdminName to set. */ public void setTestAdminName(String testAdminName) { this.testAdminName = testAdminName; } /** * @return Returns the loginEndDate. */ public Date getLoginEndDate() { return loginEndDate; } /** * @param loginEndDate The loginEndDate to set. */ public void setLoginEndDate(Date loginEndDate) { this.loginEndDate = loginEndDate; } /** * @return Returns the loginStartDate. */ public Date getLoginStartDate() { return loginStartDate; } /** * @param loginStartDate The loginStartDate to set. */ public void setLoginStartDate(Date loginStartDate) { this.loginStartDate = loginStartDate; } }
true
1ef0d80f9dff89cde2d19b26d055af3551927ba6
Java
Allos111/JavaSpecialist
/JavaSpecialist/src/samplecode/will/HashMapExamples.java
UTF-8
1,883
3.375
3
[]
no_license
package samplecode.will; import java.util.*; import java.util.concurrent.*; public class HashMapExamples { private static class Person { private final String name; private final int day; private final int month; private final int year; public Person(String name, int day, int month, int year) { this.name = name; this.day = day; this.month = month; this.year = year; } public int hashCode() { return (name.hashCode() << 16) ^ (day << 12) ^ (month << 8) ^ year; } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; if (day != person.day) return false; if (month != person.month) return false; if (year != person.year) return false; if (name != null ? !name.equals(person.name) : person.name != null) return false; return true; } } public static void main(String... args) { // 1.2 born - % remainder slow, but good distribution // 1.4 & bitmask fast, but can be bad distribution // 1.8 tree if too many clashes //HashMap 3816 // ArrayList 5408 MapClashInspector Issue 235 HashMap<String, Integer> numbers = new HashMap<>( Map.of("one", 1, "two", 2, "sixteen", 16, "unlucky", 13)); HashMap<String, List<Integer>> superstition = new HashMap<>(); add(superstition, "unlucky", 13); add(superstition, "unlucky", 7); add(superstition, "unlucky", 3); add(superstition, "lucky", 65); add(superstition, "lucky", 60); add(superstition, "lucky", 5); superstition.forEach((k, v) -> System.out.println(k + "->" + v)); } private static void add(HashMap<String, List<Integer>> superstition, String key, int number) { superstition.computeIfAbsent(key, k -> new ArrayList<>()).add(number); } }
true
e44888f76eda0e278771db816a9df8ad70531d8a
Java
valentinmanea/travel
/src/main/java/com/travel/assistant/repo/RoleRepo.java
UTF-8
224
1.953125
2
[]
no_license
package com.travel.assistant.repo; import java.util.Optional; import com.travel.assistant.entities.Role; public interface RoleRepo extends BaseRepository<Role>{ public Optional<Role> findFirstByName(String string); }
true
8a124dd1d1a0045287b76aae5c4e09259c741134
Java
guaguaguaxia/selfBeiJingNews
/app/src/main/java/com/slefbeijingnews/com/pager/GovaffairPager.java
UTF-8
1,503
1.921875
2
[]
no_license
package com.slefbeijingnews.com.pager; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; import android.widget.Toast; import com.slefbeijingnews.com.base.BasePager; import com.slefbeijingnews.com.utils.LogUtil; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Random; /** * 作者:尚硅谷-杨光福 on 2016/8/15 09:53 * 微信:yangguangfu520 * QQ号:541433511 * 作用:政要指南 */ public class GovaffairPager extends BasePager { public GovaffairPager(Context context) { super(context); } @Override public void initData() { super.initData(); LogUtil.e("政要指南数据被初始化了.."); tv_title.setText("政要指南"); TextView textView = new TextView(context); textView.setGravity(Gravity.CENTER); textView.setTextColor(Color.RED); textView.setTextSize(25); fl_content.addView(textView); textView.setText("政要指南内容"); } }
true
ca50292e17f04fb32e1d2e2803974a08c3387e94
Java
matiasrojo/orm.sistemas3
/Sistema de persistencia/src/programa/Perro.java
UTF-8
536
2.65625
3
[]
no_license
package programa; import persistencia.Motor; import persistencia.Table; @Table(name = "perro") public class Perro extends Motor { String nombre; Persona duenio; public Perro() {} public Perro(String nombre, Persona duenio) { this.nombre = nombre; this.duenio = duenio; } public String getName() { return this.nombre; } public void setName(String nombre) { this.nombre = nombre; } public Persona getDuenio() { return this.duenio; } public void setDuenio(Persona duenio) { this.duenio = duenio; } }
true
eeae3a095512f49d4600298200db58fa752012ff
Java
Videso/blackjack
/src/main/java/org/bitbucket/videso/model/BlackjackDeck.java
UTF-8
691
3.015625
3
[]
no_license
package org.bitbucket.videso.model; import lombok.Getter; import org.bitbucket.videso.model.enums.CardSuit; import java.util.ArrayList; import java.util.List; public class BlackjackDeck { private static final Integer MAX_AMOUNT_OF_CARDS = 52; @Getter private List<BlackjackCard> cards = new ArrayList<>(); public void addCard(BlackjackCard card) { if (cards.size() >= MAX_AMOUNT_OF_CARDS) { throw new IllegalStateException("Deck is full!"); } cards.add(card); } public void removeCard(CardSuit suit, String rank) { cards.removeIf(card -> card.getRank().equalsIgnoreCase(rank) && card.getSuit().equals(suit)); } }
true
1102548263ac5666abe2adf2410dfc8c6995f0bb
Java
realsnake1975/my-springcloud-services
/service-common/src/main/java/my/springcloud/common/constants/RoleType.java
UTF-8
702
2.640625
3
[ "Apache-2.0" ]
permissive
package my.springcloud.common.constants; import java.util.Arrays; public enum RoleType { SUPERADMIN("superadmin", "슈퍼어드민"), OPERATOR("operator", "운영자"); private final String code; private final String desc; RoleType(String code, String desc) { this.code = code; this.desc = desc; } public static RoleType findByName(String name) { return Arrays.stream(RoleType.values()) .filter(eventType -> eventType.getName().equals(name)) .findAny() .orElse(null); } public String code() { return code; } public String getName() { return this.desc; } @Override public String toString() { return String.format("code:%s, desc:%s", code(), getName()); } }
true
68ae52144044b9ea45ca14a3dc7bf5161d6f21d0
Java
suraj200981/SortingAlgorithms---Java
/src/heapSort.java
UTF-8
1,594
3.5
4
[]
no_license
import java.util.Arrays; public class heapSort { public static void main(String[] args) { int[] InputArr = new int[6]; InputArr[0] = 2; InputArr[1] = 8; InputArr[2] = 5; InputArr[3] = 3; InputArr[4] = 9; InputArr[5] = 1; heapSortAlg(InputArr); } public static void heapSortAlg(int[] arr) { int[] sortedArr = new int[arr.length]; int[] maxHeapArr = new int[arr.length]; int temp; System.out.println("build max heap:"); System.out.println(Arrays.toString(buildMaxHeap(arr)));// now we have max heap we need to swap largest with smallest maxHeapArr = buildMaxHeap(arr); temp = maxHeapArr[0];//9 maxHeapArr[0] = maxHeapArr[maxHeapArr.length - 1];//1 maxHeapArr[maxHeapArr.length-1]= temp; System.out.println(Arrays.toString(maxHeapArr));// now we have max heap we need to swap largest with smallest } public static int[] buildMaxHeap(int[] arrMaxHeap) { int temp1 = 0;//store biggest element int temp2 = arrMaxHeap[0]; // store first element in the array int temp3 = 0; //First find largest in the heap for (int x = 0; x < arrMaxHeap.length - 1; x++) { if (arrMaxHeap[x] < arrMaxHeap[x + 1]) { temp1 = arrMaxHeap[x + 1];//9 arrMaxHeap[0] = temp1; temp3 = x + 1; } }//once 9 is found replace initial 9 pos with index 0 element arrMaxHeap[temp3] = temp2; return arrMaxHeap; } }
true
bb8a1cf47975c5a6a2a943e658804777d9d621f8
Java
lancethomps/CommentRemover
/src/main/java/com/commentremover/processors/PropertyFileProcessor.java
UTF-8
2,815
2.453125
2
[ "Apache-2.0" ]
permissive
package com.commentremover.processors; import com.commentremover.app.CommentRemover; import com.commentremover.exception.CommentRemoverException; import com.commentremover.handling.RegexSelector; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PropertyFileProcessor extends AbstractFileProcessor { private static final String regex; private static final String singleLineCommentSymbol; private static final String singleLineCommentEscapeToken; static { regex = RegexSelector.getRegexByFileType("properties"); singleLineCommentSymbol = "#"; singleLineCommentEscapeToken = "#" + UUID.randomUUID().toString(); } public PropertyFileProcessor(CommentRemover commentRemover) { super(commentRemover); } @Override public void replaceCommentsWithBlanks() throws IOException, CommentRemoverException { super.replaceCommentsWithBlanks(regex); } @Override protected StringBuilder getFileContent(File file) throws IOException, CommentRemoverException { StringBuilder content = new StringBuilder((int) file.length()); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); for (String temp = br.readLine(); temp != null; temp = br.readLine()) { String trimmedTemp = temp.trim(); if (trimmedTemp.startsWith(singleLineCommentSymbol) && !isContainTodo(trimmedTemp)) { content.append(singleLineCommentEscapeToken).append("\n"); } else { content.append(temp).append("\n"); } } br.close(); return content; } @Override protected StringBuilder doRemoveOperation(StringBuilder fileContent, Matcher matcher) throws StackOverflowError { String sFileContent = fileContent.toString(); boolean isTodosRemoving = commentRemover.isRemoveTodos(); while (matcher.find()) { String foundToken = matcher.group(); if (isEqualsToken(foundToken)) { continue; } if (isTodosRemoving) { sFileContent = sFileContent.replaceFirst(Pattern.quote(foundToken), ""); } else { if (!isContainTodo(foundToken)) { sFileContent = sFileContent.replaceFirst(Pattern.quote(foundToken), ""); } } } fileContent = new StringBuilder(sFileContent); return fileContent; } private boolean isEqualsToken(String foundToken) { return foundToken.startsWith("="); } }
true
b8687306e6ab82e9e167fec974050a65b446097e
Java
DanielDonato/spring-webflux-demo
/src/main/java/com/danieldonato/webflux/controller/PlaylistController.java
UTF-8
1,784
2.171875
2
[]
no_license
package com.danieldonato.webflux.controller; import java.time.Duration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.danieldonato.webflux.documents.Playlist; import com.danieldonato.webflux.services.PlaylistService; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.util.function.Tuple2; @RestController @RequestMapping(value = "/playlist") public class PlaylistController { @Autowired private PlaylistService service; @RequestMapping(method = RequestMethod.GET) public Flux<Playlist> findAll(){ Flux<Playlist> obj = service.findAll(); return obj; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public Mono<Playlist> findById(@PathVariable String id){ Mono<Playlist> obj = service.findById(id); return obj; } @RequestMapping(method = RequestMethod.POST) public Mono<Playlist> save(@RequestBody Playlist obj){ Mono<Playlist> mono = service.save(obj); return mono; } @GetMapping(value = "/events", produces = MediaType.TEXT_EVENT_STREAM_VALUE) public Flux<Tuple2<Long, Playlist>> getPlaylistByEvents() { Flux<Long> interval = Flux.interval(Duration.ofSeconds(10)); Flux<Playlist> events = service.findAll(); return Flux.zip(interval, events); } }
true
b3b1b8c9b12a44409adc5e9fe1c18ff502d805cf
Java
AjlaElTabari/BITCampExercises
/dixit/src/common/Constants.java
UTF-8
85
1.609375
2
[]
no_license
package common; public class Constants { public static final int DECK_SIZE = 84; }
true
0c296e6c63b20a10938ab31f391ec5a48efac954
Java
winall898/gd-nst
/nst-api/src/main/java/cn/gdeng/nst/enums/selfdefine/RecommendEnum.java
UTF-8
939
2.53125
3
[]
no_license
package cn.gdeng.nst.enums.selfdefine; import cn.gdeng.nst.enums.TransStatusEnum; /** * @author DJB * @version 创建时间:2017年2月21日 下午5:15:41 * 找货源 recommend 自定义枚举 */ public enum RecommendEnum { /**系统推荐 */ SYS_RECOMMEND("1", "系统推荐"), /**空车配货 */ ALLOCATE_CARGO("2", "空车配货"); private String code; private String name; private RecommendEnum(String code, String name) { this.code = code; this.name = name; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static String getNameByCode(String code){ TransStatusEnum[] values = TransStatusEnum.values(); for(TransStatusEnum val : values){ if(val.getCode().equals(code)){ return val.getName(); } } return ""; } }
true
548b56114bb0b6758114a20165d8de5b68013b48
Java
whywuzeng/jingmgouproject
/lib/java/com/ab/http/AbBinaryHttpResponseListener.java
UTF-8
624
1.929688
2
[]
no_license
package com.ab.http; public class AbBinaryHttpResponseListener extends AbHttpResponseListener { private static final String TAG = "AbBinaryHttpResponseListener"; public void onSuccess(int paramInt, byte[] paramArrayOfByte) { } public void sendSuccessMessage(int paramInt, byte[] paramArrayOfByte) { sendMessage(obtainMessage(0, new Object[] { Integer.valueOf(paramInt), paramArrayOfByte })); } } /* Location: F:\一周备份\面试apk\希望代码没混淆\jingmgou\jingmgou2\classes-dex2jar.jar * Qualified Name: com.ab.http.AbBinaryHttpResponseListener * JD-Core Version: 0.6.2 */
true
f99c254dbe2834196a39f479fde8adb778dbcdec
Java
pedrofsn/espweb-mob-poo
/lista_3/src/br/ufg/espmob/lista3/exercicio3/Cidade.java
UTF-8
4,138
3.0625
3
[]
no_license
package br.ufg.espmob.lista3.exercicio3; import br.ufg.espmob.Utils; import java.util.List; import java.util.Random; /** * Created by pedrofsn on 03/05/2017. */ public class Cidade { private int codigo; private String nome; private String estado; private int veiculosPasseio; private int acidentesTransito; public Cidade() { this.codigo = new Random().nextInt(25); this.nome = new Random().nextInt() + "_cidade"; this.estado = "X" + new Random().nextInt(10); this.veiculosPasseio = new Random().nextInt(50); this.acidentesTransito = new Random().nextInt(100); } public void printCidadeComMaisAcidentesDeTransito(List<Cidade> cidades) { Cidade cidadeEscolhida = null; int acidentesRegistrados = 0; if (!Utils.isNullOrEmpty(cidades)) { for (int i = 0; i < cidades.size(); i++) { Cidade cidade = cidades.get(i); if (acidentesRegistrados == 0 | cidade.getAcidentesTransito() >= acidentesRegistrados) { acidentesRegistrados = cidade.getAcidentesTransito(); cidadeEscolhida = cidade; } } Utils.print(cidadeEscolhida.getCodigo() + " " + cidadeEscolhida.getNome() + " é a cidade com o maior número de acidentes registrados (" + cidadeEscolhida.getAcidentesTransito() + ")."); } } public void printCidadeComMenosAcidentesDeTransito(List<Cidade> cidades) { Cidade cidadeEscolhida = null; int acidentesRegistrados = 0; if (!Utils.isNullOrEmpty(cidades)) { for (int i = 0; i < cidades.size(); i++) { Cidade cidade = cidades.get(i); if (acidentesRegistrados == 0 || cidade.getAcidentesTransito() <= acidentesRegistrados) { acidentesRegistrados = cidade.getAcidentesTransito(); cidadeEscolhida = cidade; } } Utils.print(cidadeEscolhida.getCodigo() + " " + cidadeEscolhida.getNome() + " é a cidade com o menor número de acidentes registrados (" + cidadeEscolhida.getAcidentesTransito() + ")."); } } public void printMediaVeiculosPasseio(List<Cidade> cidades) { float media = 0; if (!Utils.isNullOrEmpty(cidades)) { for (int i = 0; i < cidades.size(); i++) { Cidade cidade = cidades.get(i); media += cidade.getVeiculosPasseio(); } media = media / cidades.size(); Utils.print("Média de veículos de passeio nas cidades brasileiras: " + media); } } public void printMediaAcidentes(List<Cidade> cidades, String estado) { float media = 0; int contador = 0; if (!Utils.isNullOrEmpty(cidades) && !Utils.isNullOrEmpty(estado)) { for (int i = 0; i < cidades.size(); i++) { Cidade cidade = cidades.get(i); if (estado.equalsIgnoreCase(cidade.getEstado())) { contador++; media += cidade.getAcidentesTransito(); } } media = media / contador; Utils.print("Média de acidentes entre as cidades do estado de " + estado.toUpperCase() + ": " + media); } } public int getCodigo() { return codigo; } public void setCodigo(int codigo) { this.codigo = codigo; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public String getEstado() { return estado; } public void setEstado(String estado) { this.estado = estado; } public int getVeiculosPasseio() { return veiculosPasseio; } public void setVeiculosPasseio(int veiculosPasseio) { this.veiculosPasseio = veiculosPasseio; } public int getAcidentesTransito() { return acidentesTransito; } public void setAcidentesTransito(int acidentesTransito) { this.acidentesTransito = acidentesTransito; } }
true
354994c0e5e664b5ab8cad357eaff0ffd7c8ea0e
Java
phenoscape/OBDAPI
/src/org/obd/test/OBDXMLWriteTest.java
UTF-8
1,661
2.15625
2
[]
no_license
package org.obd.test; import java.sql.SQLException; import java.util.Collection; import org.obd.model.Graph; import org.obd.model.Node; import org.obd.query.QueryTerm; import org.obd.query.Shard.EntailmentUse; import org.obd.query.Shard.GraphTranslation; import org.obd.query.impl.OBDSQLShard; public class OBDXMLWriteTest extends AbstractOBDTest{ public OBDXMLWriteTest(String n){ super(n); } public void testQuery() throws SQLException, ClassNotFoundException { /* if (true) { LabelQueryTerm lqt = new LabelQueryTerm(AliasType.PRIMARY_NAME, new ComparisonQueryTerm(Operator.CONTAINS,"eye")); //SourceQueryTerm sq = new SourceQueryTerm("cell"); //BooleanQueryTerm bq = new BooleanQueryTerm(BooleanOperator.AND,lqt,sq); Collection<Node> ns = this.runNodeQuery(bq, null); for (Node n : ns){ oxw.node(n); System.out.println(oxw.toString()); } Graph g = this.shard.getAnnotationGraphAroundNode("CL:0000149" , null, null); for (Statement s : g.getAllStatements()){ oxw.statement(s); System.out.println(oxw.toString()); } } */ } public Collection<Node> runNodeQuery(QueryTerm qt, String nid) throws SQLException, ClassNotFoundException { Collection<Node> nodes = ((OBDSQLShard)this.shard).getNodesByQuery(qt); return nodes; } public Graph runGraphQuery(QueryTerm qt, String nid){ //RelationalQuery rq = ((OBDSQLShard)this.shard).translateQueryForNode(qt); GraphTranslation gt = new GraphTranslation(); gt.setIncludeSubgraph(true); Graph g = ((OBDSQLShard)this.shard).getGraphByQuery(qt, EntailmentUse.USE_IMPLIED, gt); return g; } }
true
adc2ee61fa74b851c6e56c47ef9fef7cbb3e9986
Java
JohanFre/LifeCycle
/app/src/main/java/com/example/lifecircle20/ui/home/HomeFragment.java
UTF-8
2,634
2.328125
2
[]
no_license
package com.example.lifecircle20.ui.home; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import com.example.lifecircle20.MainActivity; import com.example.lifecircle20.R; import com.example.lifecircle20.databinding.FragmentHomeBinding; public class HomeFragment extends Fragment { EditText usernameInput; EditText passwordInput; Button loginButton; private HomeViewModel homeViewModel; private FragmentHomeBinding binding; public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class); binding = FragmentHomeBinding.inflate(inflater, container, false); View root = binding.getRoot(); final TextView textView = binding.textHome; homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() { @Override public void onChanged(@Nullable String s) { textView.setText(""); } }); usernameInput = (EditText) root.findViewById(R.id.etUsername); passwordInput = (EditText) root.findViewById(R.id.etPassword); loginButton = (Button) root.findViewById(R.id.loginBtn); loginButton.setOnClickListener(this::onClick); if(MainActivity.getUserStatus()) { loginButton.setText("Logout"); } else { loginButton.setText("Login"); } return root; } private void onClick(View view) { String username = usernameInput.getText().toString(); String password = passwordInput.getText().toString(); if(username.equals("admin") && password.equals("admin") && !MainActivity.getUserStatus()){ MainActivity.setUserStatus(true); Toast.makeText(getContext(), "Logged In", Toast.LENGTH_SHORT).show(); } else if (MainActivity.getUserStatus()){ MainActivity.setUserStatus(false); Toast.makeText(getContext(), "Logged Out", Toast.LENGTH_SHORT).show(); } } @Override public void onDestroyView() { super.onDestroyView(); binding = null; } }
true
0f462ef8584cc49f8365ed320e73fcc85667ea64
Java
Fpoittevin/Entrevoisins
/app/src/main/java/com/openclassrooms/entrevoisins/service/DummyNeighbourGenerator.java
UTF-8
2,708
2.6875
3
[]
no_license
package com.openclassrooms.entrevoisins.service; import com.openclassrooms.entrevoisins.model.Neighbour; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public abstract class DummyNeighbourGenerator { static String LOREM = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."; public static List<Neighbour> DUMMY_NEIGHBOURS = Arrays.asList( new Neighbour(1, "Caroline", "http://i.pravatar.cc/150?u=a042581f4e29026704d", "Saint Pierre du Mont", 5, "+33 6 86 57 90 14", "www.facebook.fr/caroline", LOREM), new Neighbour(2, "Jack", "http://i.pravatar.cc/150?u=a042581f4e29026704e", "Saint Pierre du Mont", 1, "+33 6 86 57 90 13", "www.facebook.fr/jack", LOREM), new Neighbour(3, "Chloé", "http://i.pravatar.cc/150?u=a042581f4e29026704f", "Saint Pierre du Mont", 2, "+33 6 86 57 90 12", "www.facebook.fr/chloe", LOREM), new Neighbour(4, "Vincent", "http://i.pravatar.cc/150?u=a042581f4e29026704a", "Saint Pierre du Mont", 3, "+33 6 86 57 90 11", "www.facebook.fr/vincent", LOREM), new Neighbour(5, "Elodie", "http://i.pravatar.cc/150?u=a042581f4e29026704b", "Saint Pierre du Mont", 4, "+33 6 86 57 90 10", "www.facebook.fr/elodie", LOREM), new Neighbour(6, "Sylvain", "http://i.pravatar.cc/150?u=a042581f4e29026704c", "Saint Pierre du Mont", 5, "+33 6 86 57 90 11", "www.facebook.fr/sylvain", LOREM), new Neighbour(7, "Laetitia", "http://i.pravatar.cc/150?u=a042581f4e29026703d", "Saint Pierre du Mont", 1, "+33 6 86 57 90 12", "www.facebook.fr/laeticia", LOREM), new Neighbour(8, "Dan", "http://i.pravatar.cc/150?u=a042581f4e29026703b", "Saint Pierre du Mont", 2, "+33 6 86 57 90 13", "www.facebook.fr/dan", LOREM), new Neighbour(9, "Joseph", "http://i.pravatar.cc/150?u=a042581f4e29026704d", "Saint Pierre du Mont", 3, "+33 6 86 57 90 14", "www.facebook.fr/joseph", LOREM), new Neighbour(10, "Emma", "http://i.pravatar.cc/150?u=a042581f4e29026706d", "Saint Pierre du Mont", 4, "+33 6 86 57 90 15", "www.facebook.fr/emma", LOREM), new Neighbour(11, "Patrick", "http://i.pravatar.cc/150?u=a042581f4e29026702d", "Saint Pierre du Mont", 5, "+33 6 86 57 90 14", "www.facebook.fr/patrick", LOREM), new Neighbour(12, "Ludovic", "http://i.pravatar.cc/150?u=a042581f3e39026702d", "Saint Pierre du Mont", 5, "+33 6 86 57 90 13a", "www.facebook.fr/ludovic", LOREM) ); static List<Neighbour> generateNeighbours() { return new ArrayList<>(DUMMY_NEIGHBOURS); } }
true
f005b3971f691c4ebb222cc38b1eb89b9c319167
Java
zendawg/org.w3c.atom
/src/main/java/org/hl7/fhir/impl/DocumentReferenceRelatesToImpl.java
UTF-8
3,226
1.75
2
[]
no_license
/* * XML Type: DocumentReference.RelatesTo * Namespace: http://hl7.org/fhir * Java type: org.hl7.fhir.DocumentReferenceRelatesTo * * Automatically generated - do not modify. */ package org.hl7.fhir.impl; /** * An XML DocumentReference.RelatesTo(@http://hl7.org/fhir). * * This is a complex type. */ public class DocumentReferenceRelatesToImpl extends org.hl7.fhir.impl.BackboneElementImpl implements org.hl7.fhir.DocumentReferenceRelatesTo { private static final long serialVersionUID = 1L; public DocumentReferenceRelatesToImpl(org.apache.xmlbeans.SchemaType sType) { super(sType); } private static final javax.xml.namespace.QName CODE$0 = new javax.xml.namespace.QName("http://hl7.org/fhir", "code"); private static final javax.xml.namespace.QName TARGET$2 = new javax.xml.namespace.QName("http://hl7.org/fhir", "target"); /** * Gets the "code" element */ public org.hl7.fhir.DocumentRelationshipType getCode() { synchronized (monitor()) { check_orphaned(); org.hl7.fhir.DocumentRelationshipType target = null; target = (org.hl7.fhir.DocumentRelationshipType)get_store().find_element_user(CODE$0, 0); if (target == null) { return null; } return target; } } /** * Sets the "code" element */ public void setCode(org.hl7.fhir.DocumentRelationshipType code) { generatedSetterHelperImpl(code, CODE$0, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON); } /** * Appends and returns a new empty "code" element */ public org.hl7.fhir.DocumentRelationshipType addNewCode() { synchronized (monitor()) { check_orphaned(); org.hl7.fhir.DocumentRelationshipType target = null; target = (org.hl7.fhir.DocumentRelationshipType)get_store().add_element_user(CODE$0); return target; } } /** * Gets the "target" element */ public org.hl7.fhir.ResourceReference getTarget() { synchronized (monitor()) { check_orphaned(); org.hl7.fhir.ResourceReference target = null; target = (org.hl7.fhir.ResourceReference)get_store().find_element_user(TARGET$2, 0); if (target == null) { return null; } return target; } } /** * Sets the "target" element */ public void setTarget(org.hl7.fhir.ResourceReference targetValue) { generatedSetterHelperImpl(targetValue, TARGET$2, 0, org.apache.xmlbeans.impl.values.XmlObjectBase.KIND_SETTERHELPER_SINGLETON); } /** * Appends and returns a new empty "target" element */ public org.hl7.fhir.ResourceReference addNewTarget() { synchronized (monitor()) { check_orphaned(); org.hl7.fhir.ResourceReference target = null; target = (org.hl7.fhir.ResourceReference)get_store().add_element_user(TARGET$2); return target; } } }
true
793baba91438d118fbb0d70179e9688765cc2c8b
Java
1511983241/classchecks
/src/main/java/com/framework/content/code/TeacherClockInBusinessCode.java
UTF-8
939
1.992188
2
[ "Apache-2.0" ]
permissive
package com.framework.content.code; public class TeacherClockInBusinessCode { /** * 教师考勤返回码 */ public final static String [] BUSINESS_SUCCESS = {"4000", "考勤操作成功"}; public final static String [] BUSSINESS_SQL_EXCEPTION = {"4001", "数据库异常"}; public final static String [] BUSSINESS_NO_DETECT_FACE = {"4002", "没有检测到人脸,请重试"}; public final static String [] BUSSINESS_IMAGE_SAVE_FAILED = {"4003", "上传的图片保存失败"}; public final static String [] BUSSINESS_IMAGE_EMPTY = {"4004", "上传的图片为空"}; public final static String [] BUSSINESS_NO_STU_LIST = {"4005", "没有查询到对应的学生名单"}; public final static String [] JW_ACCOUNT_EMPTY = {"4006", "教务账号空"}; public final static String [] LOGIN_ACCOUNT_EMPTY = {"4007", "登录账号空"}; public final static String [] LNG_LAT_EMPTY = {"4008", "经纬度空"}; }
true
1159854694a6d91e8241c36abeaef1a4eaacb571
Java
moh-patel/Vehicle-Reservation-System
/Van.java
UTF-8
1,211
3.40625
3
[]
no_license
import java.util.*; /** * Write a description of class Van here. * * @author (your name) * @version (a version number or a date) */ public class Van extends Commercial { // load compartment volume (m3) private double loadVolume; // Sliding Side Door private boolean slidingSideDoor; /** * Constructor for objects of class Van */ public Van() { super(); loadVolume = 0; slidingSideDoor = false; } private String getSlidingSideDoor() { if (slidingSideDoor = true) { return "Yes"; } else { return "No"; } } public void printDetails() { super.printDetails(); System.out.println("Load Compartment Volume (m3): " + loadVolume); System.out.println("Sliding Side Door: " + getSlidingSideDoor()); } public void readData(Scanner scanner) { super.readData(scanner); loadVolume = scanner.nextDouble(); if(scanner.next().toLowerCase().equals("yes")) { slidingSideDoor = true; } else { slidingSideDoor = false; } } }
true
032cdf9ef86285c344eb01f6189c0871de0d02dc
Java
sanopa/Blackjack-Game
/GUIFrame.java
UTF-8
814
3.0625
3
[]
no_license
/** * Sophia Anopa/Alex Yang * APCSSec01Yl12 * Blackjack: Main/GUI * Java 1.7, MacOSX10.8 * May 14-21, 2013 */ import java.awt.*; import java.awt.event.*; import javax.swing.*; public class GUIFrame extends JFrame{ private static final long serialVersionUID = 1L; JPanel pane = new JPanel(); JButton play = new JButton("Play"); GUIFrame() { super("Black Jack"); setBounds(100, 100, 300, 100); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container con = this.getContentPane(); play.setMnemonic('P'); pane.add(play); play.requestFocus(); con.add(pane); setVisible(true); } public void action(ActionEvent event) { Object source = event.getSource(); if (source == play) { Game newGame = new Game(); newGame.play(); } } public static void main(String[] args) { new GUIFrame(); } }
true
64035ac53e323043ea92e8bbb50dc1e36aae74f9
Java
BlackJet/Pract
/src/file/FileUtils.java
UTF-8
1,646
2.890625
3
[]
no_license
package file; import java.io.FileReader; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * User: Tony * Date: 05.12.13 * Time: 22:05 */ public class FileUtils { public static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return encoding.decode(ByteBuffer.wrap(encoded)).toString(); } public static void writeFile(String text, String path) throws IOException{ Files.write(Paths.get(path), text.getBytes(), StandardOpenOption.WRITE); Scanner scanner = new Scanner(new FileReader("filename.txt")); } public static void xorFile(String fileName) throws IOException{ RandomAccessFile file = new RandomAccessFile(fileName, "rw"); FileChannel channel = file.getChannel(); MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size()); buffer.mark(); while (buffer.hasRemaining()) { byte b = (byte)~buffer.get(); buffer.reset(); buffer.put(b); buffer.mark(); } buffer.flip(); channel.write(buffer); file.close(); } public static void main(String[] args) throws IOException{ xorFile("C:\\var\\w.txt"); } }
true
4fbf0bccc4310b7ddc0a547e036645e355e878ba
Java
rotinom/CSE-5324
/MyTutor/src/com/mytutor/search/SearchData.java
UTF-8
698
2.3125
2
[ "Apache-2.0" ]
permissive
package com.mytutor.search; import java.util.ArrayList; import java.util.List; import java.util.Map; import android.content.Context; public class SearchData { // Location information public List<Map> data = new ArrayList<Map>(); static SearchData singleton_; protected SearchData() { } public static SearchData getInstance() throws Exception{ if(null == singleton_){ throw new Exception("singleton_ not set. Call create first!"); } return singleton_; } public static SearchData create(){ if(null == singleton_){ singleton_ = new SearchData(); } return singleton_; } }
true
d9da66eb673d088c5f22aa01bf42600a72e9b9b9
Java
Naramsim/vulnerability-assessment-tool
/rest-backend/src/main/java/com/sap/psr/vulas/backend/repo/TracesRepositoryImpl.java
UTF-8
5,458
2.140625
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-3-Clause" ]
permissive
package com.sap.psr.vulas.backend.repo; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.EntityNotFoundException; import javax.persistence.PersistenceException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.sap.psr.vulas.backend.model.Application; import com.sap.psr.vulas.backend.model.ConstructId; import com.sap.psr.vulas.backend.model.Library; import com.sap.psr.vulas.backend.model.Dependency; import com.sap.psr.vulas.backend.model.Trace; import com.sap.psr.vulas.backend.util.ReferenceUpdater; import com.sap.psr.vulas.shared.util.StopWatch; /** * <p>TracesRepositoryImpl class.</p> * */ public class TracesRepositoryImpl implements TracesRepositoryCustom { private static Logger log = LoggerFactory.getLogger(TracesRepositoryImpl.class); @Autowired ApplicationRepository appRepository; @Autowired LibraryRepository libRepository; @Autowired ConstructIdRepository cidRepository; @Autowired TracesRepository traceRepository; @Autowired ReferenceUpdater refUpdater; @Autowired DependencyRepository depRepository; /** * <p>customSave.</p> * * @return the saved bug * @param _app a {@link com.sap.psr.vulas.backend.model.Application} object. * @param _traces an array of {@link com.sap.psr.vulas.backend.model.Trace} objects. * @throws javax.persistence.PersistenceException if any. */ public List<Trace> customSave(Application _app, Trace[] _traces) throws PersistenceException { final StopWatch sw = new StopWatch("Save [" + _traces.length + "] traces for app " + _app).start(); // To be returned List<Trace> traces = new ArrayList<Trace>(); // Helpers needed for updating the properties of the provided traces Trace managed_trace = null; ConstructId managed_cid = null; Dependency managed_dep = null; // Avoid lib queries for every trace Map<String, Dependency> deps_cache = new HashMap<String,Dependency>(); for(Trace provided_trace: _traces) { // Does it already exist? try { // Set managed objects provided_trace.setApp(_app); if(provided_trace.getLib()!=null) // Lib can be null if trace belongs to app construct provided_trace.setLib(LibraryRepository.FILTER.findOne(this.libRepository.findByDigest(provided_trace.getLib().getDigest()))); provided_trace.setConstructId(ConstructIdRepository.FILTER.findOne(this.cidRepository.findConstructId(provided_trace.getConstructId().getLang(), provided_trace.getConstructId().getType(), provided_trace.getConstructId().getQname()))); // Find existing trace (if any) if(provided_trace.getLib()!=null) managed_trace = TracesRepository.FILTER.findOne(this.traceRepository.findTracesOfLibraryConstruct(provided_trace.getApp(), provided_trace.getLib(), provided_trace.getConstructId())); else // Find existing application trace (if any) managed_trace = TracesRepository.FILTER.findOne(this.traceRepository.findTracesOfAppConstruct(provided_trace.getApp(), provided_trace.getConstructId())); // Found existing trace, now merge count and trace times provided_trace.setId(managed_trace.getId()); provided_trace.setCount(managed_trace.getCount() + provided_trace.getCount()); } catch (EntityNotFoundException e1) {} // Care for traces who's constructs have not been uploaded yet try { managed_cid = ConstructIdRepository.FILTER.findOne(this.cidRepository.findConstructId(provided_trace.getConstructId().getLang(), provided_trace.getConstructId().getType(), provided_trace.getConstructId().getQname())); } catch (EntityNotFoundException e1) { managed_cid = this.cidRepository.save(provided_trace.getConstructId()); } provided_trace.setConstructId(managed_cid); // Check whether a corresponding dependency has been created already and set traced property if(provided_trace.getLib()!=null) { try { // Get the dependency if(deps_cache.containsKey(provided_trace.getLib().getDigest())) { managed_dep = deps_cache.get(provided_trace.getLib().getDigest()); } else { managed_dep = DependencyRepository.FILTER.findOne(this.depRepository.findByAppAndLib(_app, provided_trace.getLib().getDigest())); deps_cache.put(provided_trace.getLib().getDigest(), managed_dep); } // Update traced property if(managed_dep.getTraced()==null || !managed_dep.getTraced()) { managed_dep.setTraced(true); this.depRepository.save(managed_dep); } } catch (EntityNotFoundException e1) { managed_dep = new Dependency(_app, provided_trace.getLib(), null, null, provided_trace.getFilename()); managed_dep.setTraced(true); managed_dep = this.depRepository.save(managed_dep); deps_cache.put(managed_dep.getLib().getDigest(), managed_dep); } } //TODO: Check traces whose libraries are not yet existing // Save try { managed_trace = this.traceRepository.save(provided_trace); traces.add(managed_trace); } catch (Exception e) { throw new PersistenceException("Error while saving trace " + provided_trace + ": " + e.getMessage()); } } //After all traces have been saved, //update the lastScan timestamp of the application (we already have a managed application here) appRepository.refreshLastScanbyApp(_app); sw.stop(); return traces; } }
true
1e93df9f3d46b9984a782366d38a589d79151ee2
Java
TheDarkRob/Sgeorsge
/build/tmp/expandedArchives/forge-1.15.2-31.2.0_mapped_snapshot_20200514-1.15.1-sources.jar_c582e790131b6dd3325b282fce9d2d3d/net/minecraft/world/storage/loot/functions/ILootFunction.java
UTF-8
1,655
2.0625
2
[ "Apache-2.0" ]
permissive
package net.minecraft.world.storage.loot.functions; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonObject; import com.google.gson.JsonSerializationContext; import java.util.function.BiFunction; import java.util.function.Consumer; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.world.storage.loot.IParameterized; import net.minecraft.world.storage.loot.LootContext; public interface ILootFunction extends IParameterized, BiFunction<ItemStack, LootContext, ItemStack> { static Consumer<ItemStack> func_215858_a(BiFunction<ItemStack, LootContext, ItemStack> p_215858_0_, Consumer<ItemStack> p_215858_1_, LootContext p_215858_2_) { return (p_215857_3_) -> { p_215858_1_.accept(p_215858_0_.apply(p_215857_3_, p_215858_2_)); }; } public interface IBuilder { ILootFunction build(); } public abstract static class Serializer<T extends ILootFunction> { private final ResourceLocation lootTableLocation; private final Class<T> functionClass; protected Serializer(ResourceLocation location, Class<T> clazz) { this.lootTableLocation = location; this.functionClass = clazz; } public ResourceLocation getFunctionName() { return this.lootTableLocation; } public Class<T> getFunctionClass() { return this.functionClass; } public abstract void serialize(JsonObject object, T functionClazz, JsonSerializationContext serializationContext); public abstract T deserialize(JsonObject p_212870_1_, JsonDeserializationContext p_212870_2_); } }
true
f3a6df64382df4d64c6a3735eb71ddb9bed00288
Java
celiaromerodiaz/Actividades-Maven
/Actividad_Multimodulo/Resta/src/main/java/Resta.java
UTF-8
91
2.359375
2
[]
no_license
public class Resta { public float resta(float a, float b){ return a-b; } }
true
851e9be3783709a9771fe37a8fa5bd3ea7cc4dc6
Java
ngheo1128/cs362f15
/projects/kitchenr/URLValidator/src/AuthorityTester.java
UTF-8
975
2.265625
2
[]
no_license
import static org.junit.Assert.*; import org.junit.Test; public class AuthorityTester { @Test public void testValid() { UrlValidator urlVd = new UrlValidator(null, null, UrlValidator.ALLOW_ALL_SCHEMES); assert(urlVd.isValid("http://abcdefghijklmnopqrstuvwxyz-1234567890.com")); assert(urlVd.isValid("http://test.test.test.com")); } @Test public void testPorts(){ UrlValidator urlVd = new UrlValidator(null, null, UrlValidator.ALLOW_ALL_SCHEMES); assert(urlVd.isValid("http://google.com:1234")); } @Test public void testUser(){ UrlValidator urlVd = new UrlValidator(null,null,UrlValidator.ALLOW_ALL_SCHEMES); assert(urlVd.isValid("http://user@google.com")); } @Test public void testInvalid() { UrlValidator urlVd = new UrlValidator(null, null, UrlValidator.ALLOW_ALL_SCHEMES); assert(!urlVd.isValid("http://goog2+3.com")); assert(!urlVd.isValid("http://adsf:adf.com")); assert(!urlVd.isValid("http://-dferdf.com")); } }
true
d03b03fd78e70febd27c5121231676aae977b25f
Java
PykeChen/LearnOpenGL
/app/src/main/java/com/astana/learnopengl/drawCube/GLDrawSquare.java
UTF-8
5,735
2.28125
2
[]
no_license
package com.astana.learnopengl.drawCube; import android.opengl.GLES20; import android.opengl.GLSurfaceView; import android.opengl.Matrix; import android.os.Bundle; import android.support.annotation.Nullable; import com.astana.learnopengl.BaseActivity; import com.astana.learnopengl.R; import com.astana.learnopengl.utils.CommonUtils; import com.astana.learnopengl.utils.GLCommonUtils; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import java.nio.FloatBuffer; import java.nio.ShortBuffer; /** * 绘制正方形, 编写过程: * 1.绘制普通的正方形 * 2.绘制立方体 * * @author cpy * @Description: * @version: * @date: 2018/11/20 */ public class GLDrawSquare extends BaseActivity implements GLSurfaceView.Renderer{ private static final int SIZEOF_FLOAT = 4; float mTriangleCoords[] = { -1.0f, 1.0f, 0f, // top left -1.0f, -1.0f, 0f,// bottom left 1.0f, -1.0f, 0f, // bottom right 1.0f, 1.0f, 0f // bottom top }; //各个顶点的颜色值 float mColorCoords[] = { 1.0f, 0.0f, 0.0f, 1.0f, // top left 0.0f, 1.0f, 0f, 1.0f,// bottom left 0.0f, 0.0f, 1.0f, 1.0f, // bottom right 0.0f, 1.0f, 1.0f, 1.0f // bottom top }; //绘制顶点的索引-逆时针索引 short mIndices[] = { 0, 2, 1, // 左下角三角形 0, 2, 3 //右上角三角形 }; private FloatBuffer mVertexBuffer; private FloatBuffer mColorBuffer; private ShortBuffer mIndicesBuffer; private int mShaderProgram = -1; float[] mProjectMatrix = new float[16]; float[] mViewMatrix = new float[16]; float[] mMVPMatrix = new float[16]; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); GLSurfaceView glSurfaceView = new GLSurfaceView(this); //设置2.0的环境 glSurfaceView.setEGLContextClientVersion(2); setContentView(glSurfaceView); glSurfaceView.setRenderer(this); glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY); } @Override public void onSurfaceCreated(GL10 gl, EGLConfig config) { //设置背景色(r,g,b,a) GLES20.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); //-------------演示顺时针还是逆时针以及正面背面剔除--- // GLES20.glFrontFace(GLES20.GL_CCW); // GLES20.glEnable(GLES20.GL_CULL_FACE); // GLES20.glCullFace(GLES20.GL_FRONT); //-------------演示顺时针还是逆时针以及正面背面剔除--- //做一些初始化的事情 //createBuffer,创建FBO mVertexBuffer = GLCommonUtils.createBuffer(mTriangleCoords); mColorBuffer = GLCommonUtils.createBuffer(mColorCoords); mIndicesBuffer = GLCommonUtils.createBuffer(mIndices); //加载编译程序 String fragmentStrRes = CommonUtils.readShaderFromResource(this, R.raw.triangle_fragment_shader); String vertexStrRes = CommonUtils.readShaderFromResource(this, R.raw.triangle_vertex_shader); int vertexShader = GLCommonUtils.loadShader(GLES20.GL_VERTEX_SHADER, vertexStrRes); int fragmentShader = GLCommonUtils.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentStrRes); mShaderProgram = GLCommonUtils.linkProgram(vertexShader, fragmentShader); } @Override public void onSurfaceChanged(GL10 gl, int width, int height) { //设置窗口 GLES20.glViewport(0, 0, width, height); //设置宽高比 float radio = (float) width / height; //设置透视投影 Matrix.frustumM(mProjectMatrix, 0, -radio, radio, -1, 1, 3, 5); //设置相机置 Matrix.setLookAtM(mViewMatrix, 0, 0, 0, 5.0f, 0, 0, 0, 0, 1, 0); //计算得到变换矩阵 Matrix.multiplyMM(mMVPMatrix, 0, mProjectMatrix, 0, mViewMatrix, 0); } @Override public void onDrawFrame(GL10 gl) { //重绘背景色,如果不设置这个BUFFER_BIT的话,上面onSurfaceCreate#glClearColor下次不生效 GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); // GLES20.glClearColor(1.0f, 1.0f, 0.0f, 1.0f); //获取顶点着色器的vMatrix成员句柄 int matrixHandler = GLES20.glGetUniformLocation(mShaderProgram, "vMatrix"); //指定vMatrix的值 GLES20.glUniformMatrix4fv(matrixHandler, 1, false, mMVPMatrix, 0); //获取顶点着色器的aColor句柄 int aColorHandler = GLES20.glGetAttribLocation(mShaderProgram, "aColor"); //启动三角形顶点的颜色句柄-不启动则没有效果 GLES20.glEnableVertexAttribArray(aColorHandler); //指定aColor的值 GLES20.glVertexAttribPointer(aColorHandler, 4, GLES20.GL_FLOAT, false, 4 * SIZEOF_FLOAT, mColorBuffer); //获取顶点着色器的vPosition成员句柄 int positionHandler = GLES20.glGetAttribLocation(mShaderProgram, "vPosition"); //启用三角形顶点的句柄 GLES20.glEnableVertexAttribArray(positionHandler); //准备三角形的坐标数据 GLES20.glVertexAttribPointer(positionHandler, 3, GLES20.GL_FLOAT, false, 3 * SIZEOF_FLOAT, mVertexBuffer); //绘制三角形 GLES20.glDrawArrays(GLES20.GL_TRIANGLE_FAN, 0, 4); // GLES20.glDrawElements(GLES20.GL_TRIANGLES, mIndices.length, GLES20.GL_UNSIGNED_SHORT, mIndicesBuffer); // //禁止顶点数组的句柄 GLES20.glDisableVertexAttribArray(positionHandler); //禁止顶点数组的句柄--用来测试 GLES20.glDisableVertexAttribArray(aColorHandler); } }
true
285d450b96d6a906e0ec76b8ec99aeb6b0a0e438
Java
lpiaszczyk/2watch2night
/app/src/main/java/dev/paj/towatchtonight/ui/discoverMovies/SelectVoteAverageDialog.java
UTF-8
3,076
2.09375
2
[]
no_license
package dev.paj.towatchtonight.ui.discoverMovies; import android.app.DialogFragment; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.appyvet.rangebar.RangeBar; import butterknife.BindView; import butterknife.ButterKnife; import dev.paj.towatchtonight.R; public class SelectVoteAverageDialog extends DialogFragment { @BindView(R.id.dialog_select_vote_range_bar) RangeBar rangeBar; @BindView(R.id.dialog_select_vote_range_values) TextView rangeValues; @BindView(R.id.dialog_select_vote_average_select_button) Button selectButton; private int voteFrom = 1; private int voteTo = 10; private OnVoteSelectedListener mListener; private String parentFragmentTag; public static SelectVoteAverageDialog newInstance(String parentFragmentTag, int startingFrom, int startingTo) { SelectVoteAverageDialog f = new SelectVoteAverageDialog(); Bundle args = new Bundle(); args.putString("parentFragmentTag", parentFragmentTag); f.setArguments(args); f.voteFrom = startingFrom; f.voteTo = startingTo; return f; } public int getVoteFrom() { return voteFrom; } public int getVoteTo() { return voteTo; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_dialog_select_vote_avg_range, container, false); ButterKnife.bind(this, view); rangeValues.setText(getResources().getString(R.string.dialog_select_vote_range_values, voteFrom, voteTo)); rangeBar.setOnRangeBarChangeListener((rangeBar, leftPinIndex, rightPinIndex, leftPinValue, rightPinValue) -> { voteFrom = leftPinIndex + 1; voteTo = rightPinIndex + 1; rangeValues.setText(getResources().getString(R.string.dialog_select_vote_range_values, voteFrom, voteTo)); }); selectButton.setOnClickListener((button) -> this.dismiss()); return view; } @Override public void onAttach(Context context) { super.onAttach(context); parentFragmentTag = getArguments().getString("parentFragmentTag"); try { mListener = (OnVoteSelectedListener) ((AppCompatActivity)context).getSupportFragmentManager().findFragmentByTag(parentFragmentTag); } catch (ClassCastException e) { throw new ClassCastException(context.toString() + " must implement OnVoteSelectedListener"); } } @Override public void onDetach() { mListener.onVoteAverageSelected(this); super.onDetach(); } interface OnVoteSelectedListener { void onVoteAverageSelected(SelectVoteAverageDialog dialog); } }
true
6327c7b755ebfd92a442be24c22494cd03102d0f
Java
erikaZToth/selenium_pom
/src/main/java/com/codecool/vargabeles/selenium/pom/pageObjects/MainPage.java
UTF-8
1,138
2.21875
2
[]
no_license
package com.codecool.vargabeles.selenium.pom.pageObjects; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.ui.ExpectedConditions; public class MainPage extends BasePage { @FindBy(id="header-details-user-fullname") private WebElement header; @FindBy(id="create_link") private WebElement createIssueButton; @FindBy(id="log_out") WebElement logoutOption; public MainPage(WebDriver driver) { super(driver); } public WebElement getHeader() { return header; } public boolean isLoggedIn() { try { header.isDisplayed(); } catch (NoSuchElementException e) { return false; } return true; } public void clickCreateIssueButton() { createIssueButton.click(); } public void logout() { header.click(); wait.until(ExpectedConditions.visibilityOf(logoutOption)); logoutOption.click(); } }
true
4b031d8bf14e0728f669dc1df701eb03cf71821c
Java
zenglzh/Doraemon
/rpc-client/src/main/java/com/example/rpcclient/RpcClientApplication.java
UTF-8
1,195
1.914063
2
[ "MIT" ]
permissive
package com.example.rpcclient; import com.example.rpcclient.client.SendMessage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class }) @RestController public class RpcClientApplication { @Autowired private SendMessage sendMessage; public static void main(String[] args) { ConfigurableApplicationContext run = SpringApplication.run(RpcClientApplication.class, args); } @RequestMapping("/hello") public String getName() { return sendMessage.sendName("hh"); } }
true