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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
bdd05234423468fd3b2e1eb78afc87c68fff6743 | Java | tarpboy/sendemailtest | /app/src/main/java/com/woongjin/sendemailtest/Define.java | UTF-8 | 3,154 | 2.421875 | 2 | [] | no_license | package com.woongjin.sendemailtest;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created by Jonathan on 2017. 1. 8..
*/
public class Define {
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final int MESSAGE_CONNECTION_LOST = 6;
public static final int MESSAGE_UNABLE_CONNECT = 7;
//*****************************************************
public static final int REQUEST_CONNECT_DEVICE = 1;
public static final int REQUEST_ENABLE_BT = 2;
public static final int REQUEST_CHOSE_BMP = 3;
public static final int REQUEST_CAMER = 4;
//*****************************************************
public static final String CHINESE = "GBK";
public static final String THAI = "CP874";
public static final String KOREAN = "EUC-KR";
public static final String BIG5 = "BIG5";
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
public static final int REQUEST_CAMERA_PERMISSION = 1;
public static long mLastClickTime = 0;
public static int REQUEST_FROM_HOME = 111;
public static int PLANER_DETAIL_OK = 123;
public static String nullCheck(Object value) {
return value == null ? "" : value.toString().trim().equals("null") ? "" : value.toString().trim();
}
/**
* 숫자에 ,를 붙여서 반환한다.
*
* @param value
* @return
*/
public static String formatToMoney(String value) {
long numberTemp = 0;
try {
if (Define.nullCheck(value).length() > 0) {
if (value.indexOf(".") > -1) {
float chNumber = Float.valueOf(value);
numberTemp = (long) chNumber;
} else {
numberTemp = Long.valueOf(value);
}
StringBuffer sb = new StringBuffer();
sb.append(NumberFormat.getNumberInstance().format(numberTemp)).append("");
return sb.toString().length() == 0 ? "0" : sb.toString();
}
} catch (NumberFormatException e) {
// e.printStackTrace();
}
return "0";
}
/**
* 패턴에 맞는 데이트 format형식으로 반환한다.
*
* @param date
* @return
*/
private static Calendar getPatternToDate(String pattern, String date) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
Date dateTime = simpleDateFormat.parse(date);
if (dateTime != null) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateTime);
return calendar;
}
} catch (ParseException e) {
// e.printStackTrace();
}
return null;
}
}
| true |
a37383382e2ce1b2b06016f0c0bbd4e722593a1b | Java | xiaosigua1/SpringMVC | /12SSM/src/main/java/com/xdf/dao/UserMapper.java | UTF-8 | 154 | 1.773438 | 2 | [] | no_license | package com.xdf.dao;
import com.xdf.bean.User;
public interface UserMapper {
/**
* 登录
*/
User login(String name, String pwd);
}
| true |
64291bd8727bd198805d9e23fe10eac0c7643d1b | Java | slysonway/PrivateSale | /app/src/main/java/com/kfp/privatesale/view/ui/activity/ListActivity.java | UTF-8 | 2,493 | 2.125 | 2 | [] | no_license | package com.kfp.privatesale.view.ui.activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Toast;
import com.kfp.privatesale.utils.ConstantField;
import com.kfp.privatesale.R;
import com.kfp.privatesale.data.db.entity.Customer;
import com.kfp.privatesale.data.db.entity.Event;
import com.kfp.privatesale.utils.CustomerProcess;
import com.kfp.privatesale.view.ui.fragment.CustomerListFragment;
import com.kfp.privatesale.view.ui.fragment.EventListFragment;
public class ListActivity extends AppCompatActivity implements EventListFragment.OnListFragmentInteractionListerner, CustomerListFragment.OnFragmentInteractionListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
launchFragment(new EventListFragment(), false).commit();
}
@Override
public void onEventListFragmentInteraction(Event event) {
Toast.makeText(this, event.toString(), Toast.LENGTH_SHORT).show();
setTitle(getString(R.string.event_title));
launchFragment(new CustomerListFragment(event.getId()), true).commit();
}
@Override
public void onFragmentCustomerListInteraction(Customer customer) {
Toast.makeText(this, customer.toString(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(ListActivity.this, CustomerActivity.class);
intent.putExtra(ConstantField.SCANNED_CODE, customer.getId());
intent.putExtra(ConstantField.CUSTOMER_PROCESS, CustomerProcess.CONSULTATION);
startActivity(intent);
}
private FragmentTransaction launchFragment(Fragment fragment, Boolean isBackStack) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.list_frame, fragment);
if (isBackStack) {
ft.addToBackStack(null);
}
return ft;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return true;
}
}
| true |
399d90b7677f1eb75c811131db46069b17a77945 | Java | riomukhtarom/android-sql | /app/src/main/java/com/rio/sqliteexample/TeamHelper.java | UTF-8 | 2,323 | 2.671875 | 3 | [] | no_license | package com.rio.sqliteexample;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import static com.rio.sqliteexample.DatabaseContract.TABLE_NAME;
import static com.rio.sqliteexample.DatabaseContract.TeamColumn.ID;
import static com.rio.sqliteexample.DatabaseContract.TeamColumn.NAME;
public class TeamHelper {
private Context context;
private DatabaseHelper databaseHelper;
private SQLiteDatabase database;
public TeamHelper(Context context) {
this.context = context;
}
public TeamHelper open(){
databaseHelper= new DatabaseHelper(context);
database = databaseHelper.getWritableDatabase();
return this;
}
public void close(){
databaseHelper.close();
if (database.isOpen()){
database.close();
}
}
public ArrayList<Team> getAllData(){
Cursor cursor = database.query(TABLE_NAME, null, null, null, null, null, ID +" ASC", null);
cursor.moveToFirst();
ArrayList<Team> listTeam = new ArrayList<>();
Team teamModel;
if (cursor.getCount()>0){
do{
teamModel = new Team();
teamModel.setIdTeam(cursor.getInt(cursor.getColumnIndexOrThrow(ID)));
teamModel.setNameTeam(cursor.getString(cursor.getColumnIndexOrThrow(NAME)));
listTeam.add(teamModel);
cursor.moveToNext();
} while (!cursor.isAfterLast());
}
cursor.close();
return listTeam;
}
public long insert(Team team){
ContentValues contentValues = new ContentValues();
contentValues.put(ID, team.getIdTeam());
contentValues.put(NAME, team.getNameTeam());
return database.insert(TABLE_NAME, null, contentValues);
}
public int update(Team team){
ContentValues contentValues = new ContentValues();
contentValues.put(ID, team.getIdTeam());
contentValues.put(NAME, team.getNameTeam());
return database.update(TABLE_NAME, contentValues, ID +"= '"+team.getIdTeam()+"'", null);
}
public int delete(String id){
return database.delete(TABLE_NAME, ID+"= '"+id+"'", null);
}
}
| true |
f8fab3cbad1a297416a2ebd4cf7988e110c86b76 | Java | ferdj1/fer-ryzetello-webserver | /src/main/java/my/project/fer/ryzetello/ryzetellowebserver/service/WebSocketServiceImpl.java | UTF-8 | 2,069 | 2.21875 | 2 | [] | no_license | package my.project.fer.ryzetello.ryzetellowebserver.service;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import my.project.fer.ryzetello.ryzetellowebserver.model.WebSocketMessage;
import my.project.fer.ryzetello.ryzetellowebserver.model.WebSocketMessageType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.UUID;
@Service
public class WebSocketServiceImpl implements WebSocketService {
private SimpMessagingTemplate template;
private ObjectMapper objectMapper;
@Autowired
public WebSocketServiceImpl(final SimpMessagingTemplate template, final ObjectMapper objectMapper) {
this.template = template;
this.objectMapper = objectMapper;
}
@Override
public void notifyDronesAdded(List<UUID> addedDroneIds) {
try {
final WebSocketMessage<List<UUID>> webSocketMessage = new WebSocketMessage<>();
webSocketMessage.setType(WebSocketMessageType.DRONES_ADDED);
webSocketMessage.setData(addedDroneIds);
String webSocketMessageJson = objectMapper.writeValueAsString(webSocketMessage);
template.convertAndSend("/queue/drones", webSocketMessageJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
@Override
public void notifyDronesRemoved(List<UUID> removedDroneIds) {
try {
final WebSocketMessage<List<UUID>> webSocketMessage = new WebSocketMessage<>();
webSocketMessage.setType(WebSocketMessageType.DRONES_REMOVED);
webSocketMessage.setData(removedDroneIds);
String webSocketMessageJson = objectMapper.writeValueAsString(webSocketMessage);
template.convertAndSend("/queue/drones", webSocketMessageJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
| true |
da075f7b866a3f1e2f1579a850814eb21973eb90 | Java | Nookie25/CC11 | /My knight's tour.java | UTF-8 | 196 | 1.75 | 2 | [] | no_license | /*
Name: Sean Jeffrey B. Fung
Section: CCA
Date:
Description: This program will be used to determine a knight's tour solution (if there is any) of a given coordinate of an 8x8 chess board by the user.
*/ | true |
764c1ed1d73951434cfb349d8c8a3ebed185e351 | Java | a0samue/pace-cnd-java | /spring-cloud-contracts/spring-cloud-contract-client/src/main/java/io/pivotal/pace/model/Profile.java | UTF-8 | 608 | 2.453125 | 2 | [] | no_license | package io.pivotal.pace.model;
import java.math.BigDecimal;
public class Profile {
private BigDecimal income;
private BigDecimal loanAmount;
public Profile() {
}
public Profile(double income, double loanAmount) {
this.income = BigDecimal.valueOf(income);
this.loanAmount = BigDecimal.valueOf(loanAmount);
}
public BigDecimal getIncome() {
return income;
}
public void setIncome(BigDecimal income) {
this.income = income;
}
public BigDecimal getLoanAmount() {
return loanAmount;
}
public void setLoanAmount(BigDecimal loanAmount) {
this.loanAmount = loanAmount;
}
}
| true |
8cf07c7045047aac2af1ba5581524ea24b1e70d7 | Java | rajjaiswalsaumya/spring-boot-h2-demo | /src/main/java/org/cdac/SpringBootH2DemoApplication.java | UTF-8 | 1,020 | 2.015625 | 2 | [] | no_license | package org.cdac;
import org.cdac.models.User;
import org.cdac.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableTransactionManagement
public class SpringBootH2DemoApplication implements CommandLineRunner {
@Autowired
UserRepository userRepository;
public static void main(String[] args) {
SpringApplication.run(SpringBootH2DemoApplication.class, args);
}
@Override
public void run(String... strings) throws Exception {
User user = new User("raj", "raj", "rajjaiswalsaumya@gmail.com");
//if (userRepository.findUserByEmailid("rajjaiswalsaumya@gmail.com") != null)
userRepository.save(user);
}
}
| true |
8c88ec0b0c4d667faac1d3a9cc5f47049c173ab5 | Java | aesopcmc/springcloudlearn | /microservice-consumer-movie-feign/src/main/java/com/chao/cloud/ConsumerMovieFeignApplication.java | UTF-8 | 539 | 1.65625 | 2 | [] | no_license | package com.chao.cloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableFeignClients//feign
@EnableCircuitBreaker//hystrix
@SpringBootApplication
public class ConsumerMovieFeignApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerMovieFeignApplication.class, args);
}
}
| true |
3465bd8330a362b10dac426a8313b8d4dda57d01 | Java | github/codeql | /java/ql/test/stubs/java-ee-el/javax/el/MethodExpression.java | UTF-8 | 131 | 1.609375 | 2 | [
"MIT"
] | permissive | package javax.el;
public class MethodExpression {
public Object invoke(ELContext context, Object[] params) { return null; }
}
| true |
90bec6d790ea54d82def61b4263b095fdf2a43c9 | Java | JereChen11/Android_ContentProvider_Learning | /app/src/main/java/com/jere/android_contentprovider_learning/MyContentObserver.java | UTF-8 | 1,201 | 2.40625 | 2 | [] | no_license | package com.jere.android_contentprovider_learning;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
/**
* @author jere
*/
public class MyContentObserver extends ContentObserver {
public static final int USER_TABLE_WHAT_CODE = 1111;
public static final int SCORE_TABLE_WHAT_CODE = 2222;
private Handler mHandler;
public MyContentObserver(Handler handler) {
super(handler);
this.mHandler = handler;
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
}
@Override
public void onChange(boolean selfChange, Uri uri) {
super.onChange(selfChange, uri);
switch (MyContentProvider.uriMatch.match(uri)) {
case MyContentProvider.USER_TABLE_CODE:
mHandler.obtainMessage(USER_TABLE_WHAT_CODE).sendToTarget();
break;
case MyContentProvider.SCORE_TABLE_CODE:
mHandler.obtainMessage(SCORE_TABLE_WHAT_CODE).sendToTarget();
break;
default:
mHandler.obtainMessage(USER_TABLE_WHAT_CODE).sendToTarget();
break;
}
}
}
| true |
0d594ec8d77c0f1c01d1549f3ac710746c44d769 | Java | nova-27/ServerManager | /SMFB_Core/src/main/java/com/github/nova_27/mcplugin/servermanager/core/command/MinecraftCommandExecutor.java | UTF-8 | 6,357 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | package com.github.nova_27.mcplugin.servermanager.core.command;
import com.github.nova_27.mcplugin.servermanager.core.utils.Messages;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.TabExecutor;
import java.util.*;
import java.util.stream.Collectors;
/**
* Minecraftコマンドの呼び出し等を行うクラス
*/
public class MinecraftCommandExecutor extends Command implements TabExecutor {
private ArrayList<MinecraftSubCommandBuilder> subCommands;
private String permission;
/**
* コンストラクタ
* @param name コマンド名
* @param permission 権限
* @param aliases エイリアス
*/
public MinecraftCommandExecutor(String name, String permission, String... aliases) {
super(name, permission, aliases);
subCommands = new ArrayList<>();
this.permission = permission;
}
/**
* サブコマンドを追加する
* @param builder サブコマンド
*/
public void addSubCommand(MinecraftSubCommandBuilder builder) {
subCommands.add(builder);
}
/**
* コマンド実行時に呼び出される
* @param commandSender コマンド送信者
* @param args 引数
*/
@Override
public void execute(CommandSender commandSender, String[] args) {
//権限の確認
if(!commandSender.hasPermission(permission)) {
commandSender.sendMessage(new TextComponent(Messages.BungeeCommand_denied.toString()));
return;
}
//引数の確認
if(args.length == 0) {
for(MinecraftSubCommandBuilder subCommand : subCommands) {
if(subCommand.isDefault) subCommand.action.execute(commandSender, new String[1]);
}
return;
}
//サブコマンドを選択
MinecraftSubCommandBuilder execCmd = null;
for(MinecraftSubCommandBuilder subCommand : subCommands) {
if(subCommand.alias.equals(args[0])) {
execCmd = subCommand;
break;
}
}
if(execCmd == null) {
commandSender.sendMessage(new TextComponent(Messages.BungeeCommand_notfound.toString()));
return;
}
//権限の確認
if (execCmd.subPermission != null && !commandSender.hasPermission(execCmd.subPermission)) {
commandSender.sendMessage(new TextComponent(Messages.BungeeCommand_denied.toString()));
return;
}
String[] commandArgs = new String[args.length - 1];
for(int i = 1; i <= commandArgs.length; i++) {
commandArgs[i-1] = args[i];
}
//引数の確認
if(commandArgs.length < execCmd.requireArgs) {
commandSender.sendMessage(new TextComponent(Messages.BungeeCommand_syntaxerror.toString()));
return;
}
execCmd.action.execute(commandSender, commandArgs);
}
/**
* タブ補完機能
* @param commandSender 送信者
* @param args 引数
* @return 補完リスト
*/
@Override
public Iterable<String> onTabComplete(CommandSender commandSender, String[] args) {
//引数がなかったら(「smfb」だけだったら無視)
if (args.length == 0) {
return Collections.emptyList();
}
args[0] = args[0].toLowerCase();
if(args.length == 1) {
return subCommands.stream()
.map(b -> b.alias)
.filter(alias -> alias.startsWith(args[0]))
.collect(Collectors.toSet());
} else {
for (MinecraftSubCommandBuilder subCommand : subCommands) {
if (subCommand.alias.equalsIgnoreCase(args[0])) {
ArrayList<String> argsList = new ArrayList<>(Arrays.asList(args));
argsList.remove(0);
return (subCommand.tabExecutor != null) ?
subCommand.tabExecutor.onTabComplete(commandSender, argsList.toArray(new String[0])) : Collections.emptyList();
}
}
}
return Collections.emptyList();
}
/**
* サブコマンドの設定等を保持するクラス
*/
public class MinecraftSubCommandBuilder {
private String alias;
private String subPermission;
private MinecraftCommandBase action;
private boolean isDefault;
private int requireArgs;
private TabExecutor tabExecutor;
/**
* コンストラクタ
* @param alias エイリアス
* @param subPermission 権限
* @param action 実行する処理
* @param tabExecutor 引数の補完処理
*/
public MinecraftSubCommandBuilder(String alias, String subPermission, MinecraftCommandBase action, TabExecutor tabExecutor) {
this.alias = alias;
this.subPermission = permission + "." + subPermission;
this.action = action;
isDefault = false;
requireArgs = 0;
this.tabExecutor = tabExecutor;
}
public MinecraftSubCommandBuilder(String alias, String subPermission, MinecraftCommandBase action) {
this.alias = alias;
this.subPermission = permission + "." + subPermission;
this.action = action;
isDefault = false;
requireArgs = 0;
}
public MinecraftSubCommandBuilder(String alias, MinecraftCommandBase action) {
this.alias = alias;
this.subPermission = null;
this.action = action;
isDefault = false;
requireArgs = 0;
}
/**
* デフォルトコマンドを設定する
* @param isDefault デフォルトか
*/
public MinecraftSubCommandBuilder setDefault(boolean isDefault) {
this.isDefault = isDefault;
return this;
}
/**
* 必要な引数の数を設定する
* @param cnt 引数の数
*/
public MinecraftSubCommandBuilder requireArgs(int cnt) {
requireArgs = cnt;
return this;
}
}
}
| true |
24fd30c4fa7b5952a55d3b260df5c20c6fea6a11 | Java | a595834/dat102 | /Stabel/src/no/hvl/dat102/klient/KlientLabyrint.java | UTF-8 | 492 | 2.671875 | 3 | [] | no_license | package no.hvl.dat102.klient;
public class KlientLabyrint {
public static void main(String[] args) {
Labyrint labyrint = new Labyrint();
System.out.println("labyrinten");
System.out.println(labyrint);
LabyrintSpill spill = new LabyrintSpill(labyrint);
if (spill.gjennomgaa()) {
System.out.println("Det er en sti gjennom labyrinten");
} else {
System.out.println("Det er ingen mulig sti.");
}
System.out.println(labyrint);
}// main
}
| true |
c00d2054ea02115853a0f2461bf863e6ff0caec7 | Java | maple00/RainWoodOA | /app/src/main/java/com/rainwood/oa/presenter/IArticlePresenter.java | UTF-8 | 914 | 1.8125 | 2 | [] | no_license | package com.rainwood.oa.presenter;
import com.rainwood.oa.base.IBasePresenter;
import com.rainwood.oa.view.IArticleCallbacks;
/**
* @Author: a797s
* @Date: 2020/6/5 18:12
* @Desc: 文章管理 ---沟通技巧、管理制度、开发文档、帮助中心
*/
public interface IArticlePresenter extends IBasePresenter<IArticleCallbacks> {
/**
* 沟通技巧
* @param searchText
* @param pageCount
*/
void requestCommunicationData(String searchText, int pageCount);
/**
* 管理制度
* @param title
*/
void requestManagerSystemData(String title);
/**
* 开发文档
*/
void requestDevDocumentData();
/**
* 帮助中心
* @param searchText
* @param pageCount
*/
void requestHelperData(String searchText, int pageCount);
/**
* 查看文章详情
*/
void requestArticleDetailById(String id);
}
| true |
e8cdcde55a34619af918b97fbdc75fe56e3501fb | Java | liubin97/LogisticalManagement | /dzd/src/com/neuedu/controller/SubWarehouseServlet.java | UTF-8 | 8,728 | 2.28125 | 2 | [] | no_license | package com.neuedu.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.neuedu.model.po.RecvGoodsInfo;
import com.neuedu.model.po.ReturnRegisterInfo;
import com.neuedu.model.po.SubWarehouseInInfo;
import com.neuedu.model.service.SubWarehouseService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* Servlet implementation class SubWarehouseServlet
*/
public class SubWarehouseServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public SubWarehouseServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request,response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("进入SubWarehouseServlet");
//设定编码格式
request.setCharacterEncoding("utf-8");
String action = request.getParameter("action");
//查找任务单
if("searchTaskIn".equals(action)){
doGetTaskIn(request, response);
} else if("submitTaskIn".equals(action)) {//提交调拨入库单
try {
doTransferIn(request,response);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if("searchTaskOut".equals(action)) {//查询领货单
doGetTaskOut(request, response);
} else if("submitTaskOut".equals(action)) {//提交出库信息
try {
doRecvGoods(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if("searchReturnRegister".equals(action)) {//查询退货登记信息
doGetReturnRegisterInfo(request, response);
} else if("submitReturnRegister".equals(action)) {//插入退货登记信息
try {
doRetrunRegister(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if("searchSubReturnOut".equals(action)) {//查询退货出库信息
try {
doGetReturnOut(request, response);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if("submitReturnOut".equals(action)) {
try {
doReturnOut(request, response);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//查询入库任务单
private void doGetTaskIn(HttpServletRequest request, HttpServletResponse response) throws IOException {
String task_id = request.getParameter("taskid");
JSONObject json = null;
json = SubWarehouseService.getInstance().getTaskListIn(Integer.parseInt(task_id));
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
pw.print(json);
pw.close();
}
//插入调拨入库信息
private void doTransferIn(HttpServletRequest request, HttpServletResponse response) throws ParseException, SQLException, ServletException, IOException {
String task_id = request.getParameter("taskid");
String indate = request.getParameter("indate");
String note = request.getParameter("note");
SubWarehouseInInfo swin = new SubWarehouseInInfo();
swin.setTask_list_id(Integer.parseInt(task_id));
swin.setNote(note);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
swin.setOperate_date(sdf.parse(indate));
SubWarehouseService.getInstance().insertInInfo(swin);
request.getRequestDispatcher("Substation warehouse transfer in.jsp").forward(request, response);
}
//查询出库任务单
private void doGetTaskOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
String task_id = request.getParameter("taskid");
JSONObject json = null;
json = SubWarehouseService.getInstance().getTaskListOut(Integer.parseInt(task_id));
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
pw.print(json);
pw.close();
}
//插入领货信息
private void doRecvGoods(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException, ParseException {
String task_id = request.getParameter("taskid");
String outdate = request.getParameter("outdate");
String note = request.getParameter("note");
String recv_person = request.getParameter("recvname");
RecvGoodsInfo rin = new RecvGoodsInfo();
rin.setTask_list_id(Integer.parseInt(task_id));
rin.setNote(note);
rin.setRecv_person(recv_person);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
rin.setRecv_date(sdf.parse(outdate));
rin.setOperate_date(new Date());
SubWarehouseService.getInstance().insertRecvGoodsInfo(rin);
request.getRequestDispatcher("picking.jsp").forward(request, response);
}
//查询退货登记任务单
private void doGetReturnRegisterInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
String task_id = request.getParameter("taskid");
JSONObject json = SubWarehouseService.getInstance().getReturnInTaskList(Integer.parseInt(task_id));
response.setContentType("text/html;charset=utf-8");
PrintWriter pw = response.getWriter();
pw.print(json);
pw.close();
}
//插入退货登记信息
private void doRetrunRegister(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
String task_id = request.getParameter("taskid");
String actual_num = request.getParameter("acnum");
ReturnRegisterInfo rin = new ReturnRegisterInfo();
rin.setTask_id(Integer.parseInt(task_id));
rin.setActual_num(Integer.parseInt(actual_num));
rin.setOperate_date(new Date());
SubWarehouseService.getInstance().insertReturnRegisterInfo(rin);
request.getRequestDispatcher("Return register.jsp").forward(request, response);
}
//查询退货出库任务单
private void doGetReturnOut(HttpServletRequest request, HttpServletResponse response) throws ParseException, ServletException, IOException {
String start_date = null;
String end_date = null;
String pagenum = request.getParameter("pageNum");
int pageNum = 1;
if(pagenum!=null && !"".equals(pagenum)){
//点击页码查询
System.out.println(pagenum);
start_date = (String) request.getSession().getAttribute("starttime");
end_date = (String) request.getSession().getAttribute("endtime");
pageNum = Integer.parseInt(pagenum);
}else{
//点击页面按钮查询
start_date = request.getParameter("starttime");
end_date = request.getParameter("endtime");
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
java.sql.Date sdate = new java.sql.Date(sdf.parse(start_date).getTime());
java.sql.Date edate = new java.sql.Date(sdf.parse(end_date).getTime());
JSONArray json = SubWarehouseService.getInstance().getReturnOutTaskList(sdate,edate,pageNum);
int pageCount = SubWarehouseService.getInstance().getReturnOutPage(sdate,edate);
request.setAttribute("resultList", json);
request.getSession().setAttribute("starttime", start_date);
request.getSession().setAttribute("endtime", end_date);
request.getSession().setAttribute("pageNum", pageNum);
request.getSession().setAttribute("pagecount", pageCount);
request.getRequestDispatcher("Substation return out.jsp").forward(request, response);
}
//插入退货出库信息
private void doReturnOut(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
String[] ids = request.getParameterValues("chk");
int[] idss = new int[ids.length];
for(int i = 0;i<ids.length;i++){
idss[i] = Integer.parseInt(ids[i]);
}
SubWarehouseService.getInstance().insertReturnOutInfo(idss);
int pageNum = (Integer)request.getSession().getAttribute("pageNum");
response.sendRedirect(request.getContextPath()+"/subWarehouseServlet?action=searchSubReturnOut&pageNum="+pageNum);
}
}
| true |
a611077971cf6bb8737e2702b3e5edf201300b7b | Java | subbu-k/Hibernate_Practice | /Demo2/src/main/java/com/sm/demo2/Alien.java | UTF-8 | 1,089 | 2.640625 | 3 | [] | no_license | package com.sm.demo2;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Alien {
@Id
private int id;
//private String name;
private Name name;
private int points;
//One Alien Can Have Many Bike's(mappedBy="alien" is mapped is done by bike table with alien_id column [alien object mentioned in Bike Entity])
@OneToMany(mappedBy="alien")
private List<Bike> bike;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public List<Bike> getBike() {
return bike;
}
public void setBike(List<Bike> bike) {
this.bike = bike;
}
@Override
public String toString() {
return "Alien [id=" + id + ", name=" + name + ", points=" + points + ", bike=" + bike + "]";
}
}
| true |
0492c4d20b697fcf60af92f8588f5e4e87a202c0 | Java | buixuanthe2212/reduxThunk | /android/app/src/main/java/com/jinjerkeihi/nfcfelica/transit/nextfare/record/NextfareTransactionRecord.java | UTF-8 | 5,755 | 2.140625 | 2 | [] | no_license | /*
* NextfareTapRecord.java
*
* Copyright 2015-2016 Michael Farrell <micolous+git@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.jinjerkeihi.nfcfelica.transit.nextfare.record;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.util.Log;
import com.jinjerkeihi.nfcfelica.transit.nextfare.NextfareUtil;
import com.jinjerkeihi.nfcfelica.util.Utils;
import java.util.GregorianCalendar;
/**
* Tap record type
* https://github.com/micolous/metrodroid/wiki/Cubic-Nextfare-MFC
*/
public class NextfareTransactionRecord extends NextfareRecord implements Parcelable, Comparable<NextfareTransactionRecord> {
public static final Creator<NextfareTransactionRecord> CREATOR = new Creator<NextfareTransactionRecord>() {
@Override
public NextfareTransactionRecord createFromParcel(Parcel in) {
return new NextfareTransactionRecord(in);
}
@Override
public NextfareTransactionRecord[] newArray(int size) {
return new NextfareTransactionRecord[size];
}
};
private static final String TAG = "NextfareTxnRecord";
private GregorianCalendar mTimestamp;
private int mMode;
private int mJourney;
private int mStation;
private int mValue;
private int mChecksum;
private boolean mContinuation;
protected NextfareTransactionRecord() {
}
public NextfareTransactionRecord(Parcel parcel) {
mTimestamp = new GregorianCalendar();
mTimestamp.setTimeInMillis(parcel.readLong());
mMode = parcel.readInt();
mJourney = parcel.readInt();
mStation = parcel.readInt();
mChecksum = parcel.readInt();
mContinuation = parcel.readInt() == 1;
mValue = parcel.readInt();
}
public static NextfareTransactionRecord recordFromBytes(byte[] input) {
//if (input[0] != 0x31) throw new AssertionError("not a tap record");
// LAX: input[0] == 0x05 for "Travel Pass" trips.
// SEQ, LAX: input[0] == 0x31 for "Stored Value" trips / transfers
// LAX: input[0] == 0x41 for "Travel Pass" sale.
// LAX: input[0] == 0x71 for "Stored Value" sale -- effectively recorded twice
// SEQ, LAX: input[0] == 0x79 for "Stored Value" sale
if (input[0] > 0x70) {
return null;
}
// Check if all the other data is null
if (Utils.byteArrayToLong(input, 1, 8) == 0L) {
Log.d(TAG, "Null transaction record, skipping");
return null;
}
NextfareTransactionRecord record = new NextfareTransactionRecord();
record.mMode = Utils.byteArrayToInt(input, 1, 1);
byte[] ts = Utils.reverseBuffer(input, 2, 4);
record.mTimestamp = NextfareUtil.unpackDate(ts);
byte[] journey = Utils.reverseBuffer(input, 5, 2);
record.mJourney = Utils.byteArrayToInt(journey) >> 5;
record.mContinuation = (Utils.byteArrayToInt(journey) & 0x10) > 1;
byte[] value = Utils.reverseBuffer(input, 7, 2);
record.mValue = Utils.byteArrayToInt(value);
if (record.mValue > 0x8000) {
record.mValue = -(record.mValue & 0x7fff);
}
byte[] station = Utils.reverseBuffer(input, 12, 2);
record.mStation = Utils.byteArrayToInt(station);
byte[] checksum = Utils.reverseBuffer(input, 14, 2);
record.mChecksum = Utils.byteArrayToInt(checksum);
Log.d(TAG, String.format("@%s: mode %d, station %d, value %d, journey %d, %s",
Utils.isoDateTimeFormat(record.mTimestamp), record.mMode, record.mStation, record.mValue,
record.mJourney, (record.mContinuation ? "continuation" : "new trip")));
return record;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeLong(mTimestamp.getTimeInMillis());
parcel.writeInt(mMode);
parcel.writeInt(mJourney);
parcel.writeInt(mStation);
parcel.writeInt(mChecksum);
parcel.writeInt(mContinuation ? 1 : 0);
parcel.writeInt(mValue);
}
public int getMode() {
return mMode;
}
public GregorianCalendar getTimestamp() {
return mTimestamp;
}
public int getJourney() {
return mJourney;
}
public int getStation() {
return mStation;
}
public int getChecksum() {
return mChecksum;
}
public boolean isContinuation() {
return mContinuation;
}
public int getValue() {
return mValue;
}
@Override
public int compareTo(@NonNull NextfareTransactionRecord rhs) {
// Group by journey, then by timestamp.
// First trip in a journey goes first, and should (generally) be in pairs.
if (rhs.mJourney == this.mJourney) {
return Long.valueOf(this.mTimestamp.getTimeInMillis()).compareTo(rhs.mTimestamp.getTimeInMillis());
} else {
return (Integer.valueOf(this.mJourney)).compareTo(rhs.mJourney);
}
}
}
| true |
a7918c3cc70c543edc2adf58ee2b2755fd7c1f65 | Java | madanankurmalviya/GooglePageProject | /GoogleProject/src/test/java/com/google/test/NewsPageTest.java | UTF-8 | 1,243 | 2.046875 | 2 | [] | no_license | package com.google.test;
import java.io.IOException;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.google.base.BaseTest;
import com.google.pages.GoogleSecondPage;
import com.google.pages.LoginPage;
import com.google.pages.NewsPage;
public class NewsPageTest extends BaseTest
{
GoogleSecondPage secondPage;
LoginPage login;
NewsPage newsPage;
public NewsPageTest() throws IOException
{
super();
}
@BeforeMethod
public void setUp() throws IOException
{
Before();
login = new LoginPage();
secondPage = login.SearchItem(prop.getProperty("Prod1"));
newsPage=secondPage.clickOnNewsPage();
}
@Test
public void verifyBottomMessageTest()
{
System.out.println(newsPage.verifyBottomMessage());
Assert.assertEquals(newsPage.verifyBottomMessage(),"ankur malviya","This is not matching - ankur - malviya");
}
@Test(dependsOnMethods="verifyBottomMessageTest")
public void verifyBottomNameTest()
{
System.out.println(newsPage.verifyBottomName());
Assert.assertEquals(newsPage.verifyBottomName(), "India" ,"Its not matched Bro");
}
@AfterMethod
public void tearDown()
{
driver.close();
}
}
| true |
02756f459899cda8260b8bff97e582732214ebe5 | Java | meeras26/Demoautomationtesting | /src/main/java/Pageobjects/framePage.java | UTF-8 | 929 | 2.234375 | 2 | [] | no_license | package Pageobjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class framePage
{
public WebDriver driver;
public framePage(WebDriver driver2)
{
// TODO Auto-generated constructor stub
this.driver=driver2;
}
By switchlink=By.cssSelector("a[href='SwitchTo.html']");
By framelink=By.linkText("Frames");
By text=By.cssSelector("input[type='text']");
By withinframe=By.cssSelector("a[href='#Multiple']");
By ftext=By.cssSelector("input[type='text']");
public WebElement getswitchtolink()
{
return driver.findElement( switchlink);
}
public WebElement framelink()
{
return driver.findElement(framelink);
}
public WebElement getText()
{
return driver.findElement(text);
}
public WebElement getFrame()
{
return driver.findElement(withinframe);
}
public WebElement gerSframe()
{
return driver.findElement(ftext);
}
}
| true |
fdca1daa347db042c6761da3053467df616b74e7 | Java | AlexRod97/examen1 | /src/main/java/gt/edu/url/examen1/api/Monster.java | UTF-8 | 356 | 2.0625 | 2 | [] | no_license | package gt.edu.url.examen1.api;
public interface Monster {
public String getElemento();
public void setElemento(String element);
public int getEdad();
public void setEdad(int age);
public String getColor();
public void setColor(String colorN);
public void agigantarse ();
public void caminarLento();
public void golpear();
}
| true |
a502618e00194188e706e3fd2d88d3959370d015 | Java | MayurSTechnoCredit/JAVATechnoJuly2021 | /src/parthav/ParthavD_Assignment14/MaxNumberFromArray.java | UTF-8 | 344 | 3.109375 | 3 | [] | no_license | package parthav.ParthavD_Assignment14;
public class MaxNumberFromArray {
int maxNumber;
void printMaxNumberFromArray(int[] arr) {
for (int index = 0; index < arr.length; index++) {
if (maxNumber <= arr[index]) {
maxNumber = arr[index];
}
}
System.out.println("The max number from the given array is: " + maxNumber);
}
}
| true |
9b7af4712971a493fb4a99e47715487209f9ef06 | Java | yankuokuo/JD_demo | /app/src/main/java/bwei/com/jd_demo/activity/SearchActivity.java | UTF-8 | 4,379 | 1.90625 | 2 | [] | no_license | package bwei.com.jd_demo.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import bwei.com.jd_demo.R;
import bwei.com.jd_demo.mvp.car.model.bean.AddBean;
import bwei.com.jd_demo.mvp.home.adpter.SearAdapter;
import bwei.com.jd_demo.mvp.home.model.bean.DetailBean;
import bwei.com.jd_demo.mvp.home.model.bean.JiuBean;
import bwei.com.jd_demo.mvp.home.model.bean.LunBean;
import bwei.com.jd_demo.mvp.home.model.bean.SearBean;
import bwei.com.jd_demo.mvp.home.persenter.HomePersenter;
import bwei.com.jd_demo.mvp.home.view.ILoginView;
public class SearchActivity extends AppCompatActivity implements ILoginView {
@BindView(R.id.sousuo_recyclerView)
RecyclerView sousuoRecyclerView;
@BindView(R.id.exit_login)
ImageView exitLogin;
@BindView(R.id.search_zonghe)
TextView searchZonghe;
@BindView(R.id.search_xiaoliang)
TextView searchXiaoliang;
@BindView(R.id.search_jiage)
TextView searchJiage;
@BindView(R.id.exit_sou)
EditText exitSou;
private HomePersenter homePersenter;
private String info;
private SearAdapter searAdapter;
private String fenname;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
ButterKnife.bind(this);
Intent intent = getIntent();
info = intent.getStringExtra("info");
fenname = intent.getStringExtra("fenname");
Log.d("fenname", "111---" + fenname);
homePersenter = new HomePersenter(this);
homePersenter.SearLogin(info, "0");
homePersenter.SearLogin(fenname, "0");
}
@Override
public void onLoginSuccess(LunBean lunBean) {
}
@Override
public void onjiuLoginSuccess(JiuBean jiuBean) {
}
@Override
public void onsearLoginSucess(SearBean searBean) {
List<SearBean.DataBean> list = searBean.getData();
Log.d("搜索展示", "sssss" + list);
if (list.equals("")) {
Toast.makeText(SearchActivity.this, "没有搜索的结果", Toast.LENGTH_SHORT).show();
}
searAdapter = new SearAdapter(list, SearchActivity.this);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
sousuoRecyclerView.setLayoutManager(gridLayoutManager);
sousuoRecyclerView.setAdapter(searAdapter);
searAdapter.setOnItemClickListener(new SearAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int pid) {
Intent intent = new Intent(SearchActivity.this, Detail2Activity.class);
intent.putExtra("searpid", pid);
startActivity(intent);
}
});
}
@Override
public void onDetailLoginSucess(DetailBean detailBean) {
}
@Override
public void addUsseccd(AddBean addBean) {
}
@Override
public void onerror(String error) {
}
@OnClick({R.id.exit_login, R.id.search_zonghe, R.id.search_xiaoliang, R.id.search_jiage})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.exit_login:
startActivity(new Intent(SearchActivity.this,ExitActivity.class));
break;
case R.id.search_zonghe:
homePersenter.SearLogin(info, "0");
homePersenter.SearLogin(fenname, "0");
break;
case R.id.search_xiaoliang:
homePersenter.SearLogin(info, "1");
homePersenter.SearLogin(fenname, "1");
break;
case R.id.search_jiage:
homePersenter.SearLogin(info, "2");
homePersenter.SearLogin(fenname, "2");
break;
}
}
@OnClick(R.id.exit_sou)
public void onViewClicked() {
startActivity(new Intent(SearchActivity.this,ExitActivity.class));
}
}
| true |
be6058a8de5c728f80bdc4804acaaa8b0849612b | Java | bpeak/springbootMVCSample | /src/main/java/com/bpeak/Dao/StudentDao.java | UTF-8 | 3,445 | 2.78125 | 3 | [] | no_license | package com.bpeak.Dao;
import com.bpeak.Entity.Student;
import org.springframework.stereotype.Repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Collection;
import java.util.HashMap;
@Repository
public class StudentDao {
public Collection<Student> getAllStudents(){
HashMap<Integer, Student> students = new HashMap();
try{
Connection conn = DB.connect();
Statement stmt = conn.createStatement();
String sql = "select * from students";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String course = rs.getString(3);
Student student = new Student();
student.setId(id);
student.setName(name);
student.setCourse(course);
students.put(id, student);
}
} catch (Exception e){
}
return students.values();
}
public Student getStudentById(int id){
Student student = new Student();
try{
Connection conn = DB.connect();
String sql = "select * from students where id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
ResultSet rs = pstmt.executeQuery();
while(rs.next()){
student.setId(rs.getInt(1));
student.setName(rs.getString(2));
student.setCourse(rs.getString(3));
}
} catch (Exception e){
}
return student;
}
public void updateStudentById(Student student){
try{
Connection conn = DB.connect();
String sql = "update students set id = ?, name = ?, course = ? where id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, student.getId());
pstmt.setString(2, student.getName());
pstmt.setString(3, student.getCourse());
pstmt.setInt(4, student.getId());
int count = pstmt.executeUpdate();
} catch ( Exception e ){
}
}
// public void updateStudentById(Student student){
// Student updatedStudent = students.get(student.getId());
// updatedStudent.setName(student.getName());
// updatedStudent.setCourse(student.getCourse());
// students.put(student.getId(), updatedStudent);
// }
public void removeStudentById(int id){
try{
Connection conn = DB.connect();
String sql = "delete from students where id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, id);
int count = pstmt.executeUpdate();
} catch (Exception e){
}
}
public void insertStudent(Student student){
try{
Connection conn = DB.connect();
String sql = "insert into students(id, name, course) values(?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, student.getId());
pstmt.setString(2, student.getName());
pstmt.setString(3, student.getCourse());
int count = pstmt.executeUpdate();
} catch (Exception e){
}
}
}
| true |
e06281c099a87c74986ed6645531af883a5d9dfb | Java | AntonYastrebkov/MusicStreaming | /src/main/java/com/music/streaming/model/Song.java | UTF-8 | 409 | 2.109375 | 2 | [] | no_license | package com.music.streaming.model;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Entity
@Data
@NoArgsConstructor
public class Song {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Integer number;
private String name;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "album_id")
private Album album;
}
| true |
597b862b5bbcb6d0b0d6f25f0d6cd5c9e16e316d | Java | raulserranomena/NewsApp | /app/src/main/java/com/example/newsapp/NewsAdapter.java | UTF-8 | 4,710 | 2.453125 | 2 | [] | no_license | package com.example.newsapp;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.MyViewHolder> {
private static final String TAG = "NewsAdapter";
//String that can have some format to use later
private SpannableStringBuilder spannableTitleString = new SpannableStringBuilder("");
//new TypedValue "colorValue" to store color value from resource later
private TypedValue colorValue = new TypedValue();
private List<NewsData> mNewsList;
private Context mContext;
public NewsAdapter(Context context, List<NewsData> newsList) {
this.mNewsList = newsList;
this.mContext = context;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_data_list_item, parent, false);
final MyViewHolder myViewHolder = new MyViewHolder(view);
myViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Find the current News Data that was clicked on
NewsData currentNewsData = mNewsList.get(myViewHolder.getLayoutPosition());
// Convert the String URL into a URI object (to pass into the Intent constructor)
Uri newsUrl = Uri.parse(currentNewsData.getNewsWebUrl());
// Create a new intent to view the News URI
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, newsUrl);
// Send the intent to launch a new activity
mContext.startActivity(websiteIntent);
}
});
return myViewHolder;
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder: called");
//we use the Glide library to look and download the image from the URL save within our NewsList
// and set it within the holder News Image View
Glide.with(mContext)
.asBitmap()
.load(mNewsList.get(position).getNewsThumbnailLink())
.into(holder.mNewsImage);
//get the color value from the AppTheme;
mContext.getTheme().resolveAttribute(R.attr.colorAccent, colorValue, true);
spannableTitleString.clear();
//we add to the spannableTitleString the tag of the currentNews
spannableTitleString.append(mNewsList.get(position).getNewsTag());
//add a "/ " at the end of the string
spannableTitleString.append("/ ");
//here we are colouring the String to the accent color of the them
spannableTitleString.setSpan(new ForegroundColorSpan(colorValue.data), 0, spannableTitleString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//we are adding the title of the current News
spannableTitleString.append(mNewsList.get(position).getNewsTitle());
//here we set the title of the news to the corresponding holder object
holder.mNewsTitle.setText(spannableTitleString);
//here we set the Text of the news to the corresponding holder object
holder.mNewsText.setText(mNewsList.get(position).getNewsTrailText());
}
@Override
public int getItemCount() {
return mNewsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView mNewsTitle, mNewsText;
private ImageView mNewsImage;
public MyViewHolder(@NonNull View itemView) {
super(itemView);
mNewsTitle = itemView.findViewById(R.id.news_title_text_view);
mNewsText = itemView.findViewById(R.id.news_text_view);
mNewsImage = itemView.findViewById(R.id.news_image_view);
}
}
//method to clear the news Data within the adapter
void clear() {
mNewsList.clear();
this.notifyDataSetChanged();
}
//method to add the news Data to the adapter
void addAll(List<NewsData> newsList) {
mNewsList = newsList;
this.notifyDataSetChanged();
}
}
| true |
42a83f0522c03a00aebad2f3ef57687488e07a37 | Java | txrx-research/teku | /storage/src/main/java/tech/pegasys/teku/storage/server/rocksdb/core/RocksDbInstance.java | UTF-8 | 11,504 | 1.960938 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | /*
* Copyright 2020 ConsenSys AG.
*
* 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 tech.pegasys.teku.storage.server.rocksdb.core;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.annotations.MustBeClosed;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.rocksdb.AbstractRocksIterator;
import org.rocksdb.ColumnFamilyHandle;
import org.rocksdb.RocksDBException;
import org.rocksdb.RocksIterator;
import org.rocksdb.TransactionDB;
import org.rocksdb.WriteOptions;
import tech.pegasys.teku.storage.server.DatabaseStorageException;
import tech.pegasys.teku.storage.server.ShuttingDownException;
import tech.pegasys.teku.storage.server.rocksdb.schema.RocksDbColumn;
import tech.pegasys.teku.storage.server.rocksdb.schema.RocksDbVariable;
public class RocksDbInstance implements RocksDbAccessor {
private final TransactionDB db;
private final ColumnFamilyHandle defaultHandle;
private final ImmutableMap<RocksDbColumn<?, ?>, ColumnFamilyHandle> columnHandles;
private final List<AutoCloseable> resources;
private final Set<Transaction> openTransactions = new HashSet<>();
private final AtomicBoolean closed = new AtomicBoolean(false);
RocksDbInstance(
final TransactionDB db,
final ColumnFamilyHandle defaultHandle,
final ImmutableMap<RocksDbColumn<?, ?>, ColumnFamilyHandle> columnHandles,
final List<AutoCloseable> resources) {
this.db = db;
this.defaultHandle = defaultHandle;
this.columnHandles = columnHandles;
this.resources = resources;
}
@Override
public <T> Optional<T> get(RocksDbVariable<T> variable) {
assertOpen();
try {
return Optional.ofNullable(db.get(defaultHandle, variable.getId().toArrayUnsafe()))
.map(data -> variable.getSerializer().deserialize(data));
} catch (RocksDBException e) {
throw new DatabaseStorageException("Failed to get value", e);
}
}
@Override
public <K, V> Optional<V> get(RocksDbColumn<K, V> column, K key) {
assertOpen();
final ColumnFamilyHandle handle = columnHandles.get(column);
final byte[] keyBytes = column.getKeySerializer().serialize(key);
try {
return Optional.ofNullable(db.get(handle, keyBytes))
.map(data -> column.getValueSerializer().deserialize(data));
} catch (RocksDBException e) {
throw new DatabaseStorageException("Failed to get value", e);
}
}
@Override
public <K, V> Map<K, V> getAll(RocksDbColumn<K, V> column) {
assertOpen();
try (final Stream<ColumnEntry<K, V>> stream = stream(column)) {
return stream.collect(Collectors.toMap(ColumnEntry::getKey, ColumnEntry::getValue));
}
}
@Override
public <K, V> Optional<ColumnEntry<K, V>> getFloorEntry(RocksDbColumn<K, V> column, final K key) {
assertOpen();
final byte[] keyBytes = column.getKeySerializer().serialize(key);
final Consumer<RocksIterator> setupIterator = it -> it.seekForPrev(keyBytes);
try (final Stream<ColumnEntry<K, V>> stream = createStream(column, setupIterator)) {
return stream.findFirst();
}
}
@Override
public <K, V> Optional<ColumnEntry<K, V>> getFirstEntry(final RocksDbColumn<K, V> column) {
assertOpen();
try (final Stream<ColumnEntry<K, V>> stream =
createStream(column, AbstractRocksIterator::seekToFirst)) {
return stream.findFirst();
}
}
@Override
public <K, V> Optional<ColumnEntry<K, V>> getLastEntry(RocksDbColumn<K, V> column) {
assertOpen();
try (final Stream<ColumnEntry<K, V>> stream =
createStream(column, AbstractRocksIterator::seekToLast)) {
return stream.findFirst();
}
}
@Override
@MustBeClosed
public <K, V> Stream<ColumnEntry<K, V>> stream(RocksDbColumn<K, V> column) {
assertOpen();
return createStream(column, RocksIterator::seekToFirst);
}
@Override
@MustBeClosed
public <K extends Comparable<K>, V> Stream<ColumnEntry<K, V>> stream(
final RocksDbColumn<K, V> column, final K from, final K to) {
assertOpen();
return createStream(
column,
iter -> iter.seek(column.getKeySerializer().serialize(from)),
key -> key.compareTo(to) <= 0);
}
@Override
@MustBeClosed
public synchronized RocksDbTransaction startTransaction() {
assertOpen();
Transaction tx = new Transaction(db, defaultHandle, columnHandles, openTransactions::remove);
openTransactions.add(tx);
return tx;
}
@MustBeClosed
private <K, V> Stream<ColumnEntry<K, V>> createStream(
RocksDbColumn<K, V> column, Consumer<RocksIterator> setupIterator) {
return createStream(column, setupIterator, key -> true);
}
@SuppressWarnings("MustBeClosedChecker")
@MustBeClosed
private <K, V> Stream<ColumnEntry<K, V>> createStream(
RocksDbColumn<K, V> column,
Consumer<RocksIterator> setupIterator,
Predicate<K> continueTest) {
final ColumnFamilyHandle handle = columnHandles.get(column);
final RocksIterator rocksDbIterator = db.newIterator(handle);
setupIterator.accept(rocksDbIterator);
return RocksDbIterator.create(column, rocksDbIterator, continueTest, closed::get).toStream();
}
@Override
public synchronized void close() throws Exception {
if (closed.compareAndSet(false, true)) {
for (Transaction openTransaction : openTransactions) {
openTransaction.closeViaDatabase();
}
db.syncWal();
for (final AutoCloseable resource : resources) {
resource.close();
}
}
}
private void assertOpen() {
if (closed.get()) {
throw new ShuttingDownException();
}
}
public static class Transaction implements RocksDbTransaction {
private final ColumnFamilyHandle defaultHandle;
private final ImmutableMap<RocksDbColumn<?, ?>, ColumnFamilyHandle> columnHandles;
private final org.rocksdb.Transaction rocksDbTx;
private final WriteOptions writeOptions;
private final ReentrantLock lock = new ReentrantLock();
private final AtomicBoolean closedViaDatabase = new AtomicBoolean(false);
private final Consumer<Transaction> onClosed;
private boolean closed = false;
private Transaction(
final TransactionDB db,
final ColumnFamilyHandle defaultHandle,
final ImmutableMap<RocksDbColumn<?, ?>, ColumnFamilyHandle> columnHandles,
final Consumer<Transaction> onClosed) {
this.defaultHandle = defaultHandle;
this.columnHandles = columnHandles;
this.writeOptions = new WriteOptions();
this.rocksDbTx = db.beginTransaction(writeOptions);
this.onClosed = onClosed;
}
@Override
public <T> void put(RocksDbVariable<T> variable, T value) {
applyUpdate(
() -> {
final byte[] serialized = variable.getSerializer().serialize(value);
try {
rocksDbTx.put(defaultHandle, variable.getId().toArrayUnsafe(), serialized);
} catch (RocksDBException e) {
throw new DatabaseStorageException("Failed to put variable", e);
}
});
}
@Override
public <K, V> void put(RocksDbColumn<K, V> column, K key, V value) {
applyUpdate(
() -> {
final byte[] keyBytes = column.getKeySerializer().serialize(key);
final byte[] valueBytes = column.getValueSerializer().serialize(value);
final ColumnFamilyHandle handle = columnHandles.get(column);
try {
rocksDbTx.put(handle, keyBytes, valueBytes);
} catch (RocksDBException e) {
throw new DatabaseStorageException("Failed to put column data", e);
}
});
}
@Override
public <K, V> void put(RocksDbColumn<K, V> column, Map<K, V> data) {
applyUpdate(
() -> {
final ColumnFamilyHandle handle = columnHandles.get(column);
for (Map.Entry<K, V> kvEntry : data.entrySet()) {
final byte[] key = column.getKeySerializer().serialize(kvEntry.getKey());
final byte[] value = column.getValueSerializer().serialize(kvEntry.getValue());
try {
rocksDbTx.put(handle, key, value);
} catch (RocksDBException e) {
throw new DatabaseStorageException("Failed to put column data", e);
}
}
});
}
@Override
public <K, V> void delete(RocksDbColumn<K, V> column, K key) {
applyUpdate(
() -> {
final ColumnFamilyHandle handle = columnHandles.get(column);
try {
rocksDbTx.delete(handle, column.getKeySerializer().serialize(key));
} catch (RocksDBException e) {
throw new DatabaseStorageException("Failed to delete key", e);
}
});
}
@Override
public <T> void delete(RocksDbVariable<T> variable) {
applyUpdate(
() -> {
try {
rocksDbTx.delete(defaultHandle, variable.getId().toArrayUnsafe());
} catch (RocksDBException e) {
throw new DatabaseStorageException("Failed to delete variable", e);
}
});
}
@Override
public void commit() {
applyUpdate(
() -> {
try {
this.rocksDbTx.commit();
} catch (RocksDBException e) {
throw new DatabaseStorageException("Failed to commit transaction", e);
} finally {
close();
}
});
}
@Override
public void rollback() {
applyUpdate(
() -> {
try {
this.rocksDbTx.commit();
} catch (RocksDBException e) {
throw new DatabaseStorageException("Failed to commit transaction", e);
} finally {
close();
}
});
}
private void applyUpdate(final Runnable operation) {
lock.lock();
try {
assertOpen();
operation.run();
} finally {
lock.unlock();
}
}
private void assertOpen() {
if (closed) {
if (closedViaDatabase.get()) {
throw new ShuttingDownException();
} else {
throw new IllegalStateException("Attempt to update a closed transaction");
}
}
}
private void closeViaDatabase() {
closedViaDatabase.set(true);
close();
}
@Override
public void close() {
lock.lock();
try {
if (!closed) {
closed = true;
onClosed.accept(this);
writeOptions.close();
rocksDbTx.close();
}
} finally {
lock.unlock();
}
}
}
}
| true |
6ff27a7d50ff1df8aa47a87d43973f323944a393 | Java | dennisekstrom/EW | /EW/src/chart/ChartGrid.java | UTF-8 | 1,348 | 3.5625 | 4 | [] | no_license | package chart;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
/**
* This class describes the underlying grid of the chart. It's a transparent
* panel with a light gray grid displayed. The lines of the grid are specified
* by integer arrays, in which each integer represents the position (x or y) of
* a line in the grid.
*
* @author Dennis Ekstrom
*
*/
@SuppressWarnings("serial")
public class ChartGrid extends JPanel {
private int[] horLines;
private int[] verLines;
ChartGrid() {
setGrid(new int[0], new int[0]); // initially no lines
// make transparent
setOpaque(false);
}
public void setGrid(int[] horLines, int[] verLines) {
this.horLines = horLines;
this.verLines = verLines;
}
/**
* @param horLines The horizontal lines to set
*/
public void setHorLines(int[] horLines) {
if (horLines != null)
this.horLines = horLines;
}
/**
* @param verLines The vertical lines to set
*/
public void setVerLines(int[] verLines) {
if (verLines != null)
this.verLines = verLines;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(new Color(230, 230, 230)); // Very light gray
for (int y : horLines) {
g.drawLine(0, y, this.getWidth(), y);
}
for (int x : verLines) {
g.drawLine(x, 0, x, this.getHeight());
}
}
} | true |
0f9d92471e7d116a173c533e1f0821c5169e599c | Java | johngova/newaem2018 | /core/src/main/java/com/azure/aemcode/core/servlets/AzureReadOnlySlingServlet.java | UTF-8 | 1,136 | 2.046875 | 2 | [] | no_license | package com.azure.aemcode.core.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* This is a Read-only servlet. For implementing the read-only servlet, the
* class must extend SlingSafeMethodServlet which only has doGet defined in it.
*
*
*
*
*/
@SlingServlet(resourceTypes = "aem-code/myresourcetype", generateComponent = true, generateService = true, extensions = { "json" }, methods = {
"GET" })
public class AzureReadOnlySlingServlet extends SlingSafeMethodsServlet {
/**
*
*/
private static final long serialVersionUID = 5055063923292910011L;
private Logger log = LoggerFactory.getLogger(getClass());
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)
throws ServletException, IOException {
log.debug("Servlet Called.");
}
}
| true |
4d892f8858a78953a1fbf75969eed0a976b7ada8 | Java | agustinpitaro/Compilador | /Compi/src/Utilidades/Test.java | UTF-8 | 484 | 2.375 | 2 | [] | no_license | package Utilidades;
import AnalizadorLexico.AnalizadorLexico;
import AnalizadorLexico.Simbolo;
import Parser.Parser;
public class Test {
public static void main (String [] args) {
AnalizadorLexico al = new AnalizadorLexico("linteger _a,");
// while (!al.isEOF()) {
// Simbolo s = al.getSimbolo();
// System.out.println(s.getNumero());
// System.out.println();
// }
Parser p = new Parser("entro al parser");
p.setAL(al);
p.run();
}
}
| true |
e58ba4c5b807f76c02407057a265c6aab30cc484 | Java | byempy/LolasoApp | /app/src/main/java/com/example/miguel/lolstats/Adapters/RateAdapter.java | UTF-8 | 2,434 | 2.390625 | 2 | [] | no_license | package com.example.miguel.lolstats.Adapters;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.miguel.lolstats.ApisHelper.ChampionggApiHelper;
import com.example.miguel.lolstats.Models.Campeon;
import com.example.miguel.lolstats.R;
import java.util.ArrayList;
public class RateAdapter extends BaseAdapter {
Context context;
ArrayList<Campeon> campeon;
public RateAdapter(Context context, ArrayList<Campeon> campeon){
this.context = context;
this.campeon = campeon;
}
@Override
public int getCount() {
return campeon.size();
}
@Override
public Object getItem(int position) {
return campeon.get(position);
}
@Override
public long getItemId(int position) {
return campeon.get(position).getChampionId();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inf.inflate(R.layout.rate_list, null);
}
Campeon c = campeon.get(position);
TextView txtWinRate = v.findViewById(R.id.txtWinRate);
txtWinRate.setText(String.format("%.2f", c.getWinRate()*100) + "%");
if(c.getWinRate()>=0.50) {
txtWinRate.setTextColor(Color.GREEN);
}else{
txtWinRate.setTextColor(Color.RED);
}
TextView txtPickRate = v.findViewById(R.id.txtPickRate);
txtPickRate.setText(String.format("%.2f", c.getPlayRate()*100) + "%");
TextView txtBanRate = v.findViewById(R.id.txtBanRate);
txtBanRate.setText(String.format("%.2f", c.getBanRate()*100) + "%");
double kda = (c.getKills()+c.getAssists())/c.getDeaths();
TextView txtKda = v.findViewById(R.id.txtKda);
txtKda.setText(String.format("%.2f", kda));
TextView txtPartidas = v.findViewById(R.id.txtPartidas);
txtPartidas.setText("" + c.getGamesPlayed());
TextView txtRol = v.findViewById(R.id.txtBuildRol);
txtRol.setText(ChampionggApiHelper.convertRole(c.getRole()));
return v;
}
}
| true |
4b43956864a90a21d7722d48199f4c366e99c3e2 | Java | dlrbgh9303/websource | /board/src/main/java/board/action/BoardActionFoward.java | UTF-8 | 322 | 1.710938 | 2 | [] | no_license | package board.action;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
// 이동경로, 이동방식 저장 클래스
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class BoardActionFoward {
private String path;
private boolean redirect;
}
| true |
976952693bb3468273bfb393088c0365b2405089 | Java | adachij2002/mhp3-miner-ranking | /src/mh/miner/conf/RankingConf.java | UTF-8 | 437 | 2.1875 | 2 | [] | no_license | package mh.miner.conf;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
/**
* RankingConf provides configuration of ranking page.
*/
@Root
public class RankingConf {
@Element(required=false)
private int maxPagesize = 10;
@Element(required=false)
private int navsize = 5;
public int getMaxPagesize() {
return maxPagesize;
}
public int getNavsize() {
return navsize;
}
}
| true |
e4844d6639656651566625fdd12b7710195d4f69 | Java | dmitrybilyk/interviews | /src/main/java/com/learn/spring/springinjection/autowire/mkyongtutorial/common/ChildPerson1.java | UTF-8 | 329 | 1.507813 | 2 | [] | no_license | package com.learn.spring.springinjection.autowire.mkyongtutorial.common;
import org.springframework.stereotype.Component;
/**
* Created with IntelliJ IDEA.
* User: Buh
* Date: 30.08.13
* Time: 9:26
* To change this template use File | Settings | File Templates.
*/
@Component
public class ChildPerson1 extends Person {
}
| true |
907d39389487040aa7d6d4704da9fddea50dc085 | Java | XingYu9902/Algorithms4th | /src/chapter1_1/Example_15.java | UTF-8 | 762 | 3.53125 | 4 | [] | no_license | package chapter1_1;
public class Example_15 {
public static void main(String[] args) {
int[] a = {1, 2, 1, 2, 3, 4, 5, 6, 7, 7};
int[] result = histogram(a, 8);
for (int i = 0; i < result.length; i++) {
System.out.println(i + ":" + result[i]);
}
}
private static int[] histogram(int[] a, int m) {
int[] result = new int[m];
for (int i = 0; i < a.length; i++) {
if (a[i] >= 0 && a[i] < m) {
result[a[i]]++;
}
}
return result;
}
/*
输出结果:
0:0
1:2
2:2
3:1
4:1
5:1
6:1
7:2
*/
}
| true |
6bae0e61c574375cb2b08f22fd94e76a29d97459 | Java | est7/DemoProject | /app/src/main/java/com/est7/demoproject/swipeback/SwipBackActivity.java | UTF-8 | 387 | 1.609375 | 2 | [] | no_license | package com.est7.demoproject.swipeback;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.est7.demoproject.R;
public class SwipBackActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_swip_back);
}
}
| true |
23d7112c070ba02fa55f7572050370da3acf7c28 | Java | zhaosy-git/UNI_HAWKEYE | /uni_crawler/src/main/java/com/uni/hawkeye/crawler/womai_phone/bean/ProductInfo.java | UTF-8 | 2,808 | 2.296875 | 2 | [] | no_license | package com.uni.hawkeye.crawler.womai_phone.bean;
import java.math.BigDecimal;
import java.util.Date;
public class ProductInfo {
private String product_id;
private String product_title;
private String brand_name;
private int status;
private int product_list_id;
private String url;
private String json;
private Date ctime;
private Date mtime;
public ProductInfo(){}
public ProductInfo(String product_id, String product_title, String brand_name, int status, int product_list_id, String url, String json) {
super();
this.product_id = product_id;
this.product_title = product_title;
this.brand_name = brand_name;
this.status = status;
this.product_list_id = product_list_id;
this.url = url;
this.json = json;
}
/**
* @return the product_id
*/
public String getProduct_id() {
return product_id;
}
/**
* @param product_id the product_id to set
*/
public void setProduct_id(String product_id) {
this.product_id = product_id;
}
/**
* @return the product_title
*/
public String getProduct_title() {
return product_title;
}
/**
* @param product_title the product_title to set
*/
public void setProduct_title(String product_title) {
this.product_title = product_title;
}
/**
* @return the brand_name
*/
public String getBrand_name() {
return brand_name;
}
/**
* @param brand_name the brand_name to set
*/
public void setBrand_name(String brand_name) {
this.brand_name = brand_name;
}
/**
* @return the status
*/
public int getStatus() {
return status;
}
/**
* @param status the status to set
*/
public void setStatus(int status) {
this.status = status;
}
/**
* @return the product_list_id
*/
public int getProduct_list_id() {
return product_list_id;
}
/**
* @param product_list_id the product_list_id to set
*/
public void setProduct_list_id(int product_list_id) {
this.product_list_id = product_list_id;
}
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* @param url the url to set
*/
public void setUrl(String url) {
this.url = url;
}
/**
* @return the json
*/
public String getJson() {
return json;
}
/**
* @param json the json to set
*/
public void setJson(String json) {
this.json = json;
}
/**
* @return the ctime
*/
public Date getCtime() {
return ctime;
}
/**
* @param ctime the ctime to set
*/
public void setCtime(Date ctime) {
this.ctime = ctime;
}
/**
* @return the mtime
*/
public Date getMtime() {
return mtime;
}
/**
* @param mtime the mtime to set
*/
public void setMtime(Date mtime) {
this.mtime = mtime;
}
}
| true |
1cdef6ca254cb9eb61f3e0d991d196877d542188 | Java | dashagaranina/Hometasks | /term4/task9/src/main/java/core/App.java | UTF-8 | 542 | 1.90625 | 2 | [] | no_license | package core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import service.OrderService;
public class App {
public static void main(String[] args) throws Exception {
ApplicationContext appContext = new ClassPathXmlApplicationContext("Spring-Customer.xml");
OrderService orderService = (OrderService) appContext.getBean(OrderService.class);
orderService.addOrder("qwe", Long.parseLong("0"));
orderService.getOrder("qwe");
}
} | true |
24c0681eedd124a2b8be52d2c81b28637cc2c728 | Java | stonegyu/mywork | /ActBeat/src/com/bsent/actbeat1/UserInfomation.java | UHC | 3,932 | 2.4375 | 2 | [] | no_license | package com.bsent.actbeat1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class UserInfomation {
private final String filename = "userid.txt";
private static String inputId ="";
void Userinfo() {
}
public String getInputId() {
return inputId;
}
// external б/Ⱑ Ѱ?
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
// external ּ ϱ⸮ Ѱ?
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)
|| Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
Message msg = new Message();
void Save_RhythmData(String Note_Name, String Note_Data, Context context, Handler handler, int msg) {
this.msg.what = msg;
String root = context.getExternalFilesDir(null).toString();
root = root.substring(0, root.length()-5);
File myDir = new File(root+"/Note_Data");
myDir.mkdir();
File file = new File(myDir, Note_Name);
if(file.exists())file.delete();
try{
FileOutputStream fos = new FileOutputStream(file);
fos.write(Note_Data.getBytes());
fos.close();
}catch(Exception e){
e.printStackTrace();
}
handler.sendMessage(this.msg);
}
class TxtFilter implements FilenameFilter{
@Override
public boolean accept(File arg0, String arg1) {
// TODO Auto-generated method stub
return (filename.endsWith(".txt"));
}
}
List<Rhythm_Data> Read_RhythmData(Context context){
List<Rhythm_Data> data = new ArrayList<Rhythm_Data>();
String ext = Environment.getExternalStorageState();
String root = null;
if(ext.equals(Environment.MEDIA_MOUNTED)){
root = context.getExternalFilesDir(null).toString();
root = root.substring(0, root.length()-5);
root+="Note_Data";
}else{
root = Environment.MEDIA_UNMOUNTED;
return null;
}
File files = new File(root);
files.mkdir();
if(files.listFiles(new TxtFilter()).length>0){
for(File file : files.listFiles(new TxtFilter())){
String str, str1="";
try {
FileInputStream fis = new FileInputStream(root+"/"+file.getName());
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(fis));
while((str = bufferReader.readLine())!=null){
str1+=str;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
data.add(new Rhythm_Data(file.getName(), str1));
}
}
return data;
}
void onSaveId(String id, Context context) {
try {
Log.d("log", "save id "+id);
FileOutputStream fos = context.openFileOutput(filename,
Context.MODE_WORLD_READABLE);
fos.write(id.getBytes());
fos.close();
Log.d("log", "end");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
String onGetId(Context context) {
String id = null;
Log.d("log",""+context.getExternalFilesDir(null));
try {
FileInputStream fis = context.openFileInput(filename);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
id = new String(buffer);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("log", "end " + id);
inputId = id;
return id;
}
}
| true |
4fa4fd79524b4f11afe3091e7e5aba886eb5933a | Java | ONagaty/SEA-ModellAR | /eu.cessar.ct.core.mms/src/eu/cessar/ct/core/mms/internal/IMMNamespaceMapping.java | UTF-8 | 336 | 1.914063 | 2 | [] | no_license | package eu.cessar.ct.core.mms.internal;
import java.util.Map;
/**
*
*/
public interface IMMNamespaceMapping
{
/**
* @param namespace
* @return
*/
public String getPackageName(String namespace);
/**
* @return
*/
public String getRootNamespace();
/**
* @return
*/
public Map<String, String> getAllPackages();
}
| true |
789abbeb4ad9d95e91899c89a82a378052fa7ae0 | Java | xym-mm/yeb | /yeb-server/src/main/java/com/yeb/server/service/IAdminService.java | UTF-8 | 733 | 1.796875 | 2 | [] | no_license | package com.yeb.server.service;
import com.yeb.server.pojo.Admin;
import com.baomidou.mybatisplus.extension.service.IService;
import com.yeb.server.pojo.Menu;
import com.yeb.server.pojo.RespBean;
import org.springframework.http.HttpRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author xym
* @since 2021-03-09
*/
public interface IAdminService extends IService<Admin> {
/**
* 用户登录
*/
public RespBean AdminLogin(String userName, String passWord, String code,HttpServletRequest request);
/**
* 根据用户名获取用户信息
* @param userName
* @return
*/
Admin getUserByUserName(String userName);
}
| true |
72a9d5ac6dc5755279c0fd8ded4869503a2cf971 | Java | sagek23/Java-Training | /dept/src/main/java/com/bit/dept/controller/DeptController.java | UTF-8 | 898 | 2.109375 | 2 | [] | no_license | package com.bit.dept.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.bit.dept.dao.DeptDao;
@Controller
public class DeptController {
@Autowired
DeptDao dao = new DeptDao();
public void setDao(DeptDao dao) {
this.dao = dao;
}
@RequestMapping(value = "/listEmp.do", method = RequestMethod.GET)
public void listForm()
{
System.out.println("컨트롤러 동작함");
}
@RequestMapping(value = "/listEmp.do", method = RequestMethod.POST)
public ModelAndView listAll(String name)
{
ModelAndView mav = new ModelAndView();
mav.addObject("list", dao.listAll(name));
mav.setViewName("listEmp");
return mav;
}
}
| true |
36e84f905d5e61263cf4a7c469d53de8ca98491f | Java | prakharparwal/JavaMaster | /CoreJava/src/com/prakhar/parwal/predicate/PredicateExample.java | UTF-8 | 1,471 | 3.453125 | 3 | [] | no_license | package com.prakhar.parwal.predicate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class PredicateExample
{
public static void main(String... q)
{
ArrayList<Person> persons = new ArrayList<Person>(){{
add(new Person(1, "Prakhar", 25));
add(new Person(2, "Sudeep", 24));
add(new Person(3, "Nikhil", 24));
}};
//persons.stream().filter(true/false).collect
System.out.println("Persons with age 24 :"+persons.stream().filter(new Predicate<Person>() {
@Override
public boolean test(Person p)
{
return p.getAge() == 24;
}
}).collect(Collectors.toList()));
persons.stream().filter(new Predicate<Person>() {
@Override
public boolean test(Person p) {
return p.getAge() == 24;
}
}).forEach(new Consumer<Person>() {
@Override
public void accept(Person p)
{
System.out.println("Persons [name in upper case] with age equals to 24 are:"+p.getName().toUpperCase());
}
});
//PersonFilters
persons.stream().filter(PersonFilters.personsAbove24()).collect(Collectors.toList());
persons.stream().filter(PersonFilters.personsEquals25()).collect(Collectors.toList());
PersonFilters.filterEmployee(persons, PersonFilters.personsAbove24());
}
}
| true |
21333695b338698d4027446827f88ab233f32fd1 | Java | sanchezalejandro86/sem | /src/main/java/org/example/sem/SEM.java | UTF-8 | 2,447 | 3.921875 | 4 | [] | no_license | package org.example.sem;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class SEM {
public static Map<Integer, Integer> process(int [] numbers){
Stack<Integer> s = new Stack<Integer>();
Map<Integer, Integer> result = new HashMap<>();
int element, next;
/* agrega el primer elemento a la pila */
s.push(numbers[0]);
// se itera el resto del array
for (int i = 1; i < numbers.length; i++) {
next = numbers[i];
if (s.isEmpty() == false) {
// Si la pila no está vacía, extrear un elemento de la pila
element = s.pop();
/* Si el elemento extraido es más chico que "next", entonces se imprime el par y se continua
extrayendo mientras los elementos sean más chicos y la pila no esté vacía */
while (element < next) {
result.put(element, next);
if (s.isEmpty() == true)
break;
element = s.pop();
}
/* Si el elemento es más grande que "next", entonces regresar el elemento a la pila */
if (element > next)
s.push(element);
}
/* agregar "next" a la pila para encontrar el siguiente más grande para este */
s.push(next);
}
/* Luego de iterar sobre el array, los elementos restantes en la pila no tienen siguiente elemento mayor
por lo que se imprime -1 para ellos */
while (s.isEmpty() == false)
{
element = s.pop();
next = -1;
result.put(element, next);
}
return result;
}
public static void main(String []args){
int[] arr1 = new int[]{4, 5, 2, 25};
Map<Integer, Integer> result1 = SEM.process(arr1);
printResults(arr1, result1);
int[] arr2 = new int[]{13, 7, 6, 12};
Map<Integer, Integer> result2 = SEM.process(arr2);
printResults(arr2, result2);
}
private static void printResults(int[] numbers, Map<Integer, Integer> results){
System.out.println("Elemento\t\tSEM");
for (int i=0; i<numbers.length; i++) {
System.out.println(numbers[i] + "\t\t-->\t" + results.get(numbers[i]));
}
System.out.println("================================");
}
}
| true |
9f9051c8125113c69391fc920c16e6c32ba012dc | Java | Tobben00/TicTacTrump-Bondesjakk | /java/no/woact/martob16/MainMenu.java | UTF-8 | 3,440 | 2.328125 | 2 | [] | no_license | package no.woact.martob16;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.content.Intent;
import android.widget.Button;
import android.widget.TextView;
public class MainMenu extends AppCompatActivity implements SetNameDialog.SetNameDialogListener
{
private String playerName;
private Button buttonSetName;
private TextView welcomeText;
private String loadWelcomeText;
public static final String SHARED_PREF = "sharedPrefs";
public static final String welcomeTextShared = "text";
public static final String playerNameTextShared = "text1";
DatabaseHelper mDatabaseHelper;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
mDatabaseHelper = new DatabaseHelper(this);
welcomeText = findViewById(R.id.textview_Welcome);
buttonSetName = findViewById(R.id.button_setName);
buttonSetName.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
setNameDialog();
}
});
loadPlayerName();
updateViews();
}
@Override
public void applyTexts(String playername)
{
// implementer: Brukeren må skrive in noe, kan ikke være tom.
playerName = playername;
welcomeText.setText("Welcome " + playerName + ", Trump will never fail!");
savePlayerName();
}
public void setNameDialog()
{
SetNameDialog setnamedialog = new SetNameDialog();
setnamedialog.show(getSupportFragmentManager(),"Eksempel dialog");
}
public void onClickPvAI(View view)
{
Intent toPvAI = new Intent(MainMenu.this, pvai.class);
startActivity(toPvAI);
}
public void onClickPVP(View view)
{
Intent toPVP = new Intent(MainMenu.this, pvp.class);
startActivity(toPVP);
}
public void onClickAbout(View view)
{
Intent toABOUT = new Intent(MainMenu.this, about.class);
startActivity(toABOUT);
}
public void onClickResetDatabase(View view)
{
deleteDatabase();
}
public void onClickStats(View view)
{
// Flytter data over til ny activity
Intent toSTATS = new Intent(MainMenu.this, stats.class);
startActivity(toSTATS);
}
public void deleteDatabase()
{
mDatabaseHelper.deleteDatabase();
}
public void savePlayerName()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(welcomeTextShared, welcomeText.getText().toString());
editor.putString(playerNameTextShared, playerName);
editor.apply();
}
public void loadPlayerName()
{
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREF, MODE_PRIVATE);
loadWelcomeText = sharedPreferences.getString(welcomeTextShared, welcomeText.getText().toString());
}
public void updateViews()
{
welcomeText.setText(loadWelcomeText);
}
}
| true |
748458bfc27023f253d4c31da90f78783c648254 | Java | smartcommunitylab/smartcampus.gamification | /game-engine.core/src/main/java/eu/trentorise/game/managers/drools/KieContainerFactory.java | UTF-8 | 224 | 1.664063 | 2 | [
"Apache-2.0"
] | permissive | package eu.trentorise.game.managers.drools;
import org.kie.api.runtime.KieContainer;
public interface KieContainerFactory {
KieContainer getContainer(String gameId);
KieContainer purgeContainer(String gameId);
}
| true |
0f94aa27a6fcf8e1c80cec3e91f0d24062a2fb24 | Java | kenzym04/Transportation-System-API-Integration | /service/src/main/java/org/broadinstitute/mbta/service/StopsMbtaService.java | UTF-8 | 416 | 2.09375 | 2 | [] | no_license | package org.broadinstitute.mbta.service;
import org.broadinstitute.mbta.core.Stop;
import java.io.IOException;
import java.util.List;
/**
* @author Colin Kegler
* @verion The Service method specification to retrieve MBTA Stops
*/
public interface StopsMbtaService {
final String BASE_URL_STOPS = "https://api-v3.mbta.com/stops?filter[route_type]=0,1&include=route,parent_station";
List<Stop> getStops();
}
| true |
0f59596ad3d8661ea4adb0dd28d0896e18059ca3 | Java | anshulmahipal/accounting-app | /CommonData/src/common/model/dto/StatsContent.java | UTF-8 | 1,471 | 2.640625 | 3 | [] | no_license | package common.model.dto;
import common.model.BaseEntity;
import common.model.entity.Product;
public class StatsContent extends BaseEntity
{
//this dto object - representation of product entity & some additional attributes
//equivalent to supplyContent/saleContent db table
private Product product; // need only ID for db, additional fields of product for view representation
private int productAmount;
private double productSummary; //calculated column for view representation
public StatsContent(Product product, int productAmount)
{
this.product = product;
this.productAmount = productAmount;
}
public StatsContent(Product product, int productAmount, double productSummary)
{
this.product = product;
this.productAmount = productAmount;
this.productSummary = productSummary;
}
public Product getProduct()
{
return product;
}
public void setProduct(Product product)
{
this.product = product;
}
public int getProductAmount()
{
return productAmount;
}
public void setProductAmount(int productAmount)
{
this.productAmount = productAmount;
productSummary = productAmount*product.getCost();
}
public double getProductSummary()
{
return productSummary;
}
public void setProductSummary(double productSummary)
{
this.productSummary = productSummary;
}
}
| true |
0e11de935d5392a76b6aae1a5865c6404628561b | Java | mingyen/argoPractice | /src/RemoveElement.java | UTF-8 | 1,669 | 4.375 | 4 | [] | no_license | public class RemoveElement {
/**
* https://leetcode.com/articles/remove-element/
*
* Given an array and a value, remove all instances of that value in place and return the new length.
* Do not allocate extra space for another array, you must do this in place with constant memory.
* The order of elements can be changed. It doesn't matter what you leave beyond the new length.
* Example:
* Given input array nums = [3,2,2,3], val = 3
* Your function should return length = 2, with the first two elements of nums being 2.
*
* 1. Try two pointers.
* 2. Did you use the property of "the order of elements can be changed"?
* 3. What happens when the elements to remove are rare?
*
*/
public static void main(String[] args) {
//System.out.println("Hello World!");
// int list[] = {3,2,2,3};
// int len = removeElement(list,3);
int list[] = {4,1,2,3,5};
int len = removeElement2(list, 4);
System.out.println(len);
}
public static int removeElement(int[] nums, int val) {
int i = 0;
for (int j = 0; j < nums.length; j++) {
if (nums[j] != val) {
nums[i] = nums[j];
i++;
}
}
return i;
}
public static int removeElement2(int[] nums, int val) {
int i = 0;
int n = nums.length;
while (i < n) {
if (nums[i] == val) {
nums[i] = nums[n - 1];
// reduce array size by one
n--;
} else {
i++;
}
}
return n;
}
}
| true |
4d62df6134634bae0a430c93157ba8ed65a296da | Java | chelloya/ProyectoPrueba | /app/src/main/java/com/example/proyprueba/proyectoprueba/DataRespuestaOut.java | UTF-8 | 1,188 | 2.71875 | 3 | [] | no_license | package com.example.proyprueba.proyectoprueba;
import java.io.Serializable;
public class DataRespuestaOut implements Serializable {
private static final long serialVersionUID = 1L;
private int tiempoSobrante;
private int puntajeObtenido;
private boolean contestoBien;
private Pregunta preg;
public DataRespuestaOut(int tiempoSobrante, int puntajeObtenido,
boolean contestoBien, Pregunta preg) {
super();
this.tiempoSobrante = tiempoSobrante;
this.puntajeObtenido = puntajeObtenido;
this.contestoBien = contestoBien;
this.preg = preg;
}
public int getTiempoSobrante() {
return tiempoSobrante;
}
public int getPuntajeObtenido() {
return puntajeObtenido;
}
public boolean isContestoBien() {
return contestoBien;
}
public Pregunta getPreg() {
return preg;
}
public String toString(){
Datapregunta auxDP = preg.ADataPregunta();
String aux = "\n"+ auxDP.toString();
aux = aux + "\nTiempo Sobrante: " + getTiempoSobrante();
aux = aux + "\nPuntaje Obtenido: " + getPuntajeObtenido();
if (isContestoBien())
{
aux = aux + "\nRespeusta: Correcta";
}
else
{
aux = aux + "\nRespeusta: Incorrecta";
}
return aux;
}
}
| true |
42b0fcf256edcd5b7e1132f1aa2edbbfeecdcb09 | Java | aghasyedbilal/intellij-community | /platform/dvcs-impl/src/com/intellij/dvcs/ui/BranchActionGroup.java | UTF-8 | 2,665 | 1.914063 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.dvcs.ui;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.project.DumbAware;
import com.intellij.ui.LayeredIcon;
import com.intellij.util.ui.EmptyIcon;
import icons.DvcsImplIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
public abstract class BranchActionGroup extends ActionGroup implements DumbAware, CustomIconProvider {
private boolean myIsFavorite;
private LayeredIcon myIcon;
private LayeredIcon myHoveredIcon;
public BranchActionGroup() {
super("", true);
setIcons(AllIcons.Nodes.Favorite, EmptyIcon.ICON_16, AllIcons.Nodes.Favorite, AllIcons.Nodes.NotFavoriteOnHover);
}
protected void setIcons(@NotNull Icon favorite,
@NotNull Icon notFavorite,
@NotNull Icon favoriteOnHover,
@NotNull Icon notFavoriteOnHover) {
myIcon = new LayeredIcon(favorite, notFavorite);
myHoveredIcon = new LayeredIcon(favoriteOnHover, notFavoriteOnHover);
getTemplatePresentation().setIcon(myIcon);
getTemplatePresentation().setSelectedIcon(myHoveredIcon);
updateIcons();
}
private void updateIcons() {
myIcon.setLayerEnabled(0, myIsFavorite);
myHoveredIcon.setLayerEnabled(0, myIsFavorite);
myIcon.setLayerEnabled(1, !myIsFavorite);
myHoveredIcon.setLayerEnabled(1, !myIsFavorite);
}
public boolean isFavorite() {
return myIsFavorite;
}
public void setFavorite(boolean favorite) {
myIsFavorite = favorite;
updateIcons();
}
public void toggle() {
setFavorite(!myIsFavorite);
}
public boolean hasIncomingCommits() {return false;}
public boolean hasOutgoingCommits() {return false;}
@Nullable
@Override
public Icon getRightIcon() {
if (hasIncomingCommits()) {
return hasOutgoingCommits() ? DvcsImplIcons.IncomingOutgoing : DvcsImplIcons.Incoming;
}
return hasOutgoingCommits() ? DvcsImplIcons.Outgoing : null;
}
}
| true |
91461511abefc2cc8861067136864129b4b9b9f3 | Java | YasinZhangX/meettingfilm-SpringCloud | /backend-apigw-zuul/src/main/java/com/yasin/meetingfilm/backend/zuul/config/ZuulConfig.java | UTF-8 | 683 | 1.796875 | 2 | [] | no_license | package com.yasin.meetingfilm.backend.zuul.config;
import com.yasin.meetingfilm.backend.zuul.filters.CorsFilter;
import com.yasin.meetingfilm.backend.zuul.filters.JWTFilter;
import com.yasin.meetingfilm.backend.zuul.filters.MyFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Yasin Zhang
*/
@Configuration
public class ZuulConfig {
@Bean
public MyFilter initMyFilter() {
return new MyFilter();
}
@Bean
public JWTFilter initJWTFilter() {
return new JWTFilter();
}
@Bean
public CorsFilter initCorsFilter() {
return new CorsFilter();
}
}
| true |
6cd1eb6fb0c2ae5a02a671be1ee086df0c73da26 | Java | taikinakano/learn_java | /JAVAunderstand/src/chapter16/Exercise16_2.java | UTF-8 | 475 | 3.40625 | 3 | [] | no_license | package chapter16;
import java.util.ArrayList;
public class Exercise16_2 {
public static void main(String[] args) {
class Hero {
private String name;
public Hero(String name) {this.name = name; }
public String getName() { return this.name; }
}
Hero h1 = new Hero("斉藤");
Hero h2 = new Hero("鈴木");
ArrayList<Hero> hero = new ArrayList<Hero>();
hero.add(h1);
hero.add(h2);
for (Hero h : hero) {
System.out.println(h.getName());
}
}
}
| true |
e9b27942fe1e24fb0d483586245880d178225ce0 | Java | maximAtanasov/QuackR | /quackr-server/src/main/java/de/webtech/quackr/service/event/EventAttendeeLimitReachedException.java | UTF-8 | 226 | 2.03125 | 2 | [
"MIT"
] | permissive | package de.webtech.quackr.service.event;
public class EventAttendeeLimitReachedException extends Throwable {
public EventAttendeeLimitReachedException(){
super("Cannot add more attendees to this event.");
}
}
| true |
7a3af0c933e2622e36a33f7110f5c98bda411fc6 | Java | bkerler/simplify | /smalivm/src/main/java/org/cf/smalivm/emulate/EmulatedMethod.java | UTF-8 | 265 | 1.929688 | 2 | [
"MIT"
] | permissive | package org.cf.smalivm.emulate;
import java.util.Set;
import org.cf.smalivm.SideEffect.Level;
import org.cf.smalivm.VirtualException;
public interface EmulatedMethod {
public Level getSideEffectLevel();
public Set<VirtualException> getExceptions();
}
| true |
24ea80b3ba7f78df3ee686b7df88b0b45187765a | Java | lixuan11/NetWorkSecurity | /src/application/RSATest.java | UTF-8 | 922 | 2.265625 | 2 | [] | no_license | package application;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.KeyPair;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class RSATest {
private RSA rsa = new RSA();
@Before
public void setUp() throws Exception {
}
@Test
public void test() throws Exception {
KeyPair keypair = rsa.buildKeyPair();
PublicKey publickey = keypair.getPublic();
PrivateKey privatekey = keypair.getPrivate();
String plainText = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
//assertEquals(plainText, new String(rsa.decryptWithPub(publickey, rsa.encryptWithPri(privatekey, plainText))));
assertEquals(plainText.getBytes(), rsa.decryptWithPri(privatekey, rsa.encryptWithPub(publickey, plainText)));
}
}
| true |
cd0a88cc6dedfab4790414095dddbcae28f79c9b | Java | HARISHA13/850290-HACKATHON-1-26-05-2020 | /CPU1.java | UTF-8 | 2,331 | 2.8125 | 3 | [] | no_license | import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import org.json.JSONObject;
import org.json.simple.parser.ParseException;
public class CPU1 {
String filepath = "CPU.txt";
ArrayList<Double> cpuArray = new ArrayList<Double>();
LinkedHashMap<String, Double> CpuMap = new LinkedHashMap<String, Double>();
void Reader() throws ParseException {
String lineText = null;
int line = 0;
double OverAllMemorySize = 0;
double AverageMemorySize = 0.0;
double MaxMemorySize = 0;
int count = 0;
int keyvalue=1;
try {
BufferedReader lineReader = new BufferedReader(new FileReader(filepath));
while ((lineText = lineReader.readLine()) != null) {
String Memory = lineText.substring(41, 46);
OverAllMemorySize = OverAllMemorySize + Double.parseDouble(Memory);
String key= keyvalue+"s";
CpuMap.put(key, (Double.parseDouble(Memory)));
cpuArray.add((Double.parseDouble(Memory)));
count++;
AverageMemorySize = OverAllMemorySize / count;
keyvalue++;
line++;
}
DecimalFormat decimalFormat =new DecimalFormat("###.##");
String formater=decimalFormat.format(AverageMemorySize);
AverageMemorySize=Double.parseDouble(formater);
MaxMemorySize=(Collections.max(CpuMap.values()));
lineReader.close();
} catch (IOException ex) {
System.err.println(ex);
}
JSONObject jsonObj = new JSONObject();
jsonObj.put("values",CpuMap.toString() );
jsonObj.put("avgcpu", String.valueOf(AverageMemorySize));
jsonObj.put("", MaxMemorySize);
JSONObject jsonobject= new JSONObject();
jsonobject.put("sampletranscation", jsonObj);
System.out.println(jsonobject);
try
{
FileWriter file = new FileWriter("CPUJson.json");
file.write(jsonobject.toString(3).replace("=", ":"));
file.flush();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws ParseException {
CPU1 obj = new CPU1();
obj.Reader();
}
} | true |
d1f62a24d84e812cbff08ccc48087adf4ce0adac | Java | chenleizhaoEdinboro/chenleizhaoedinboro.github.io | /NemoJava-2.0/src/test/java/FactoryAndData/B2C/NA27312.java | UTF-8 | 592 | 2.09375 | 2 | [
"MIT"
] | permissive | package FactoryAndData.B2C;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Factory;
import CommonFunction.Common;
import TestData.PropsUtils;
import TestScript.B2C.NA27312Test;
public class NA27312 {
@DataProvider(name = "27312")
public static Object[][] Data27133() {
return Common.getFactoryData(new Object[][] {
{ "IN" },
},
PropsUtils.getTargetStore("NA-27312"));
}
@Factory(dataProvider = "27312")
public Object[] createTest(String store) {
Object[] tests = new Object[1];
tests[0] = new NA27312Test(store);
return tests;
}
}
| true |
3d8e34330f467e8263f9b872a046c82e3dea821c | Java | lazlaz/arithmetic | /src/main/java/com/laz/arithmetic/LetCodeSortLearn.java | UTF-8 | 830 | 3.046875 | 3 | [] | no_license | package com.laz.arithmetic;
import org.junit.Test;
import com.laz.arithmetic.LetCodeTreeLearn.TreeNode;
public class LetCodeSortLearn {
// 合并两个有序数组
@Test
public void test1() {
int[] nums1 = new int[]{1,2,3,0,0,0};
int[] nums2 = new int[]{2,5,6};
merge(nums1,3,nums2,3);
for (int num : nums1) {
System.out.print(num+" ");
}
}
public void merge(int[] nums1, int m, int[] nums2, int n) {
for (int i=0;i<nums2.length;i++) {
nums1[m+i] = nums2[i];
}
for (int i=0;i<nums1.length-1;i++) {
for (int j=0;j<nums1.length-1;j++) {
if(nums1[j]>nums1[j+1])
{
int temp=nums1[j];
nums1[j]=nums1[j+1];
nums1[j+1]=temp;
}
}
}
}
}
| true |
e5662746c8ba952af11f4eec73d8e81b11cd7f97 | Java | Valerio-boi/Codewars-java | /Kata/GreetMe.java | UTF-8 | 180 | 2.828125 | 3 | [] | no_license | public class GreetMe{
public static String greet(String name){
return "Hello " + ((String) name.subSequence(0, 1)).toUpperCase() + name.substring(1).toLowerCase() +"!";
}
} | true |
37ae18298b688a156cd84e2feeec47c4ca51a0a8 | Java | greenjjun/computersystem | /java/test/src/coffee/Test.java | UHC | 974 | 2.9375 | 3 | [] | no_license | package coffee;
import java.util.*;
public class Test {
public static void main(String[] args) {
// Student student = new Student("̼", 1, 4, 20);
// Scanner scanner = new Scanner(System.in);
// String str = scanner.nextLine();
// System.out.println(str);
//
// scanner.close();
//
// System.out.println(student.getStudentId());
// student.introduce();
HighSchoolStudent hS = new HighSchoolStudent("", 1, 4, 29, "ĵ","õ");
hS.introduce();
Teacher teacher = new Teacher("", "α", 23423);
List<Identifiable> identities = new ArrayList<>();
identities.add(hS);
identities.add(teacher);
for (Identifiable iden : identities) {
System.out.println(iden.getId());
}
List<NameInterface> names = new ArrayList<>();
names.add(hS);
names.add(teacher);
for(NameInterface name : names) {
System.out.println(name.getName());
}
}
}
| true |
79592e4c2598b87c563e42b1e08b035d217f2c1a | Java | syluh/Examen | /src/examen/Numeros.java | UTF-8 | 1,298 | 3.640625 | 4 | [] | 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 examen;
import java.util.Scanner;
/**
*
* @author VICTOR
*/
public class Numeros {
public static void main(String[] args) {
Scanner leer = new Scanner(System.in);
//Declarar variables
double m4, m5, m6, total;
int n;
n = 0; m4 = 0; m5 = 0; m6 = 0; total = 0;
System.out.println("Programa que calcula los multiplos y realiza operaciones");
System.out.println("--------");
System.out.println("Ingrese el número a comparar");
n = leer.nextInt();
//Proceso
//Condiciones
if (n % 4 == 0) {
total = n / 2;
System.out.println("El resultado es " +total);
} else if (n % 5 == 0) {
total = n*n;
System.out.println("El resultado es" +total);
} else if (n % 6 == 0) {
total = n;
System.out.println("El resultado es " +total);
}
}
}
| true |
61f3dcf549d9f4ed97edc3102f8a9f387527d081 | Java | qq245271830/MagicPlugin | /CompatibilityLib/v1_17_0/src/main/java/com/elmakers/mine/bukkit/utility/platform/v1_17_0/SchematicUtils.java | UTF-8 | 10,346 | 2.125 | 2 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | package com.elmakers.mine.bukkit.utility.platform.v1_17_0;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.util.Vector;
import com.elmakers.mine.bukkit.utility.CompatibilityConstants;
import com.elmakers.mine.bukkit.utility.platform.Platform;
import com.elmakers.mine.bukkit.utility.platform.base.SchematicUtilsBase;
import com.elmakers.mine.bukkit.utility.schematic.LoadableSchematic;
import com.google.common.primitives.Bytes;
import net.minecraft.nbt.ByteArrayTag;
import net.minecraft.nbt.CompoundTag;
import net.minecraft.nbt.IntArrayTag;
import net.minecraft.nbt.ListTag;
import net.minecraft.nbt.NbtIo;
import net.minecraft.nbt.Tag;
public class SchematicUtils extends SchematicUtilsBase {
public SchematicUtils(Platform platform) {
super(platform);
}
@Override
public boolean loadSchematic(InputStream input, LoadableSchematic schematic, Logger log) {
if (input == null || schematic == null) return false;
try {
CompoundTag nbtData = NbtIo.readCompressed(input);
if (nbtData == null) {
return false;
}
short width = nbtData.getShort("Width");
short height = nbtData.getShort("Height");
short length = nbtData.getShort("Length");
CompoundTag palette = nbtData.getCompound("Palette");
byte[] blockData = nbtData.getByteArray("BlockData");
int[] blockMap = null;
Map<Integer, String> paletteMap = null;
if (palette != null) {
// Map the palette
paletteMap = new HashMap<>();
Set<String> keys = palette.getAllKeys();
for (String key : keys) {
int index = palette.getInt(key);
paletteMap.put(index, key);
}
}
if (blockData != null) {
int varInt = 0;
int varIntLength = 0;
int index = 0;
blockMap = new int[width * height * length];
for (int i = 0; i < blockData.length; i++) {
varInt |= (blockData[i] & 127) << (varIntLength++ * 7);
if ((blockData[i] & 128) == 128) {
continue;
}
blockMap[index++] = varInt;
varIntLength = 0;
varInt = 0;
}
if (index != blockMap.length) {
log.warning("Block data array length does not match dimensions in schematic");
}
}
// Load entities
Collection<Object> tileEntityData = new ArrayList<>();
Collection<Object> entityData = new ArrayList<>();
ListTag entityList = nbtData.getList("Entities", CompatibilityConstants.NBT_TYPE_COMPOUND);
ListTag tileEntityList = null;
if (nbtData.contains("BlockEntities")) {
tileEntityList = nbtData.getList("BlockEntities", CompatibilityConstants.NBT_TYPE_COMPOUND);
} else {
tileEntityList = nbtData.getList("TileEntities", CompatibilityConstants.NBT_TYPE_COMPOUND);
}
if (entityList != null) {
int size = entityList.size();
for (int i = 0; i < size; i++) {
Tag entity = entityList.get(i);
entityData.add(entity);
}
}
if (tileEntityList != null) {
int size = tileEntityList.size();
for (int i = 0; i < size; i++) {
Tag tileEntity = tileEntityList.get(i);
tileEntityData.add(tileEntity);
}
}
Vector origin = new Vector(0, 0, 0);
int[] offset = nbtData.getIntArray("Offset");
if (offset != null && offset.length == 3) {
origin.setX(offset[0]);
origin.setY(offset[1]);
origin.setZ(offset[2]);
}
schematic.load(width, height, length, blockMap, null, paletteMap, tileEntityData, entityData, origin);
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
@Override
public boolean saveSchematic(OutputStream output, String[][][] blockData) {
if (output == null || blockData == null || blockData.length == 0 || blockData[0].length == 0 || blockData[0][0].length == 0) {
return false;
}
CompoundTag nbtData = new CompoundTag();
int width = blockData.length;
int height = blockData[0].length;
int length = blockData[0][0].length;
nbtData.putShort("Width", (short)width);
nbtData.putShort("Height", (short)height);
nbtData.putShort("Length", (short)length);
// Iterate through blocks and build varint data list and block palette
Map<String, Integer> paletteLookup = new HashMap<>();
List<Byte> blockList = new ArrayList<>();
int currentId = 0;
for (int y = 0; y < height; y++) {
for (int z = 0; z < length; z++) {
for (int x = 0; x < width; x++) {
String block = blockData[x][y][z];
Integer paletteIndex = paletteLookup.get(block);
if (paletteIndex == null) {
paletteIndex = currentId++;
paletteLookup.put(block, paletteIndex);
}
while (paletteIndex > 128) {
// This is probably wrong ...
// TODO: test with a variety of blocks in a schematic!
blockList.add((byte)((paletteIndex & 127) | 128));
paletteIndex >>= 7;
}
blockList.add((byte)(int)paletteIndex);
}
}
}
// Save palette to NBT
CompoundTag palette = new CompoundTag();
for (Map.Entry<String, Integer> entry : paletteLookup.entrySet()) {
palette.putInt(entry.getKey(), entry.getValue());
}
nbtData.put("Palette", palette);
// Save block list to NBT
byte[] blockArray = Bytes.toArray(blockList);
nbtData.put("BlockData", new ByteArrayTag(blockArray));
// Add empty lists so they exist
nbtData.put("Entities", new ListTag());
nbtData.put("BlockEntities", new ListTag());
int[] offset = {0, 0, 0};
nbtData.put("Offset", new IntArrayTag(offset));
try {
NbtIo.writeCompressed(nbtData, output);
} catch (IOException ex) {
platform.getLogger().log(Level.WARNING, "Error writing schematic", ex);
return false;
}
return true;
}
@Override
public boolean loadLegacySchematic(InputStream input, LoadableSchematic schematic) {
if (input == null || schematic == null) return false;
try {
CompoundTag nbtData = NbtIo.readCompressed(input);
if (nbtData == null) {
return false;
}
// Version check
String materials = nbtData.getString("Materials");
if (!materials.equals("Alpha")) {
Bukkit.getLogger().warning("Schematic is not in Alpha format");
return false;
}
short width = nbtData.getShort("Width");
short height = nbtData.getShort("Height");
short length = nbtData.getShort("Length");
byte[] blockIds = nbtData.getByteArray("Blocks");
// Have to combine block ids to get 12 bits of ids
// Thanks to the WorldEdit team for showing me how to do this.
int[] blocks = new int[blockIds.length];
byte[] addBlocks = new byte[0];
if (nbtData.contains("AddBlocks")) {
addBlocks = nbtData.getByteArray("AddBlocks");
}
for (int index = 0; index < blocks.length; index++) {
if ((index >> 1) >= addBlocks.length) {
blocks[index] = (short) (blockIds[index] & 0xFF);
} else {
if ((index & 1) == 0) {
blocks[index] = (short) (((addBlocks[index >> 1] & 0x0F) << 8) + (blockIds[index] & 0xFF));
} else {
blocks[index] = (short) (((addBlocks[index >> 1] & 0xF0) << 4) + (blockIds[index] & 0xFF));
}
}
}
byte[] data = nbtData.getByteArray("Data");
Collection<Object> tileEntityData = new ArrayList<>();
Collection<Object> entityData = new ArrayList<>();
ListTag entityList = nbtData.getList("Entities", CompatibilityConstants.NBT_TYPE_COMPOUND);
ListTag tileEntityList = nbtData.getList("TileEntities", CompatibilityConstants.NBT_TYPE_COMPOUND);
if (entityList != null) {
int size = entityList.size();
for (int i = 0; i < size; i++) {
Object entity = entityList.get(i);
entityData.add(entity);
}
}
if (tileEntityList != null) {
int size = tileEntityList.size();
for (int i = 0; i < size; i++) {
Object tileEntity = tileEntityList.get(i);
tileEntityData.add(tileEntity);
}
}
int originX = nbtData.getInt("WEOriginX");
int originY = nbtData.getInt("WEOriginY");
int originZ = nbtData.getInt("WEOriginZ");
schematic.load(width, height, length, blocks, data, null, tileEntityData, entityData, new Vector(originX, originY, originZ));
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
}
| true |
6c7b0ffdc07a395d59fb31877e7387aaab728efa | Java | luyi1/quality | /quality/src/main/java/com/ge/digital/quality/QualityApplication.java | UTF-8 | 1,885 | 2.03125 | 2 | [] | no_license | package com.ge.digital.quality;
import java.lang.reflect.Type;
import java.util.Date;
import java.util.TimeZone;
import javax.annotation.PostConstruct;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
@EntityScan({ "com.ge.digital.quality.entity", "com.ge.digital.gearbox.common.autoIncrKey",
"com.ge.digital.schedule.entity" })
@EnableJpaRepositories({ "com.ge.digital.gearbox.common.autoIncrKey", "com.ge.digital.quality.mapper",
"com.ge.digital.schedule.mapper" })
@SpringBootApplication(scanBasePackages = { "com.ge.digital.gearbox.common", "com.ge.digital.quality" })
@EnableEurekaClient
public class QualityApplication {
@Bean
public Gson getGson() {
GsonBuilder builder = new GsonBuilder();
// Register an adapter to manage the date types as long values
builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return new Date(json.getAsJsonPrimitive().getAsLong());
}
});
Gson gson = builder.create();
return gson;
}
public static void main(String[] args) {
SpringApplication.run(QualityApplication.class, args);
}
@PostConstruct
void setDefaultTimezone() {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
}
}
| true |
7b2ffe068d64ae2518d26e9f374b3f48f3965f51 | Java | choloantonio09/ireserve | /Capstone/src/NameValidationFinal.java | UTF-8 | 4,605 | 2.984375 | 3 | [] | no_license |
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Scanner;
import java.util.regex.Matcher; //decimal
import java.util.regex.Pattern; //decimal
import org.apache.commons.validator.routines.EmailValidator;
public class NameValidationFinal {
Scanner sc = new Scanner(System.in);
public static void main(String[] args){
new NameValidationFinal();
}//Main
NameValidationFinal(){ //Constructor
System.out.println("Enter your text: isWhiteSpace isAlpha isstrNameValid isCheckEmail ");
String username = sc.nextLine();
boolean whitespace = isWhiteSpace(username);
System.out.println("whiteSpace (!space, enter, tab)= "+whitespace+"\n ----------------");//Output
boolean testing = isAlpha(username);
System.out.println("isAlpha ( a-z, 0-9, !char)= "+testing+"\n ----------------");
boolean strName = isstrNameValid(username);
System.out.println("isstrNameValid (O'hara) = "+strName+"\n ----------------");
boolean email = isCheckEmail(username);
System.out.println("CheckEmail (@yahoo.com , @yahoo.com.ph) = "+email+"\n ----------------\n\n");
System.out.println("Enter your no: isNumber priceFormat isCheckPhone isCheckAlpha ");
String no = sc.nextLine();
boolean number = isNumber(no);
System.out.println("numbers (1234) = "+number+"\n ----------------");
boolean format = priceFormat(no);
System.out.println("price format (100.00) = "+format+"\n ----------------");
boolean phoneno = isCheckPhone(no);
System.out.println("phone no (+6390 , 09 , 123-12-12 , 123-1212 , 1231212 = "+phoneno+"\n ----------------");
boolean alphanumeric = isCheckAlpha(no);
System.out.println("alphanumeric (letters & no) = "+alphanumeric+"\n ----------------");
} //Constructor
//Mary Start
public boolean isWhiteSpace(String name) { //enter and space
boolean containsWhitespace = true;
if (name.isEmpty()) {
containsWhitespace = false;
}else if(name != null) {
for (int i = 0; i < name.length() && containsWhitespace; i++) {
if (Character.isWhitespace(name.charAt(i))) {
containsWhitespace = false;
}
}
}
return containsWhitespace;
}
public boolean isNumber(String no) { //no only
String regex = "\\d+";
try {
if(no.matches(regex)) {
System.out.println("Valid number");
return true;
}else {
System.out.println("Invalid number");
return false;
}
}catch(Exception e){
return false;
}
}
//Mary End
public boolean isAlpha(String name) { //Example O'hara
return name.matches("[a-zA-Z]+");
}
public boolean isstrNameValid(String strname){ //Names Ex. O'hara , jan-jan
if (strname.matches("[a-zA-Z '-]+")){
return true;
}else {
return false;
}
}//Method
public boolean priceFormat(String no){ //mali pa ngoutput di nalalaman kapag 100.10.10 nagiging true
//pero nacocorrect nya pag mali input mo
String pattern = "[0-9]+([,.][0-9]{1,2})?";
// Create a Pattern object
Pattern r = Pattern.compile(pattern);
// Now create matcher object.
Matcher m = r.matcher(no);
if (m.find()) {
System.out.println("Found value: " + m.group(0));
return true;
}else {
System.out.println("INAPPROPRIATE DIGITS!");
return false;
}
}
public boolean isCheckAlpha(String name){ //Method for checking alphanumeric
if(name.matches("^[a-zA-Z0-9]*$")){
return true;
}else {
return false;
}
}//Method
public boolean isCheckEmail(String mail){ //Method for checking email
if(EmailValidator.getInstance().isValid(mail)){
return true;
}else {
return false;
}
}//Method
public boolean isCheckPhone(String phone){ //Method for checking phone number
boolean found = false;
if(phone.matches("^[09]{1,2}[0-9]{1,9}$")){
found = true;
//System.out.println("normal");
}
else if(phone.matches("^[+][63]{1,2}[0-9]{1,10}")){
found = true;
//System.out.println("special");
}
else if(phone.matches("^[0-9]{1,3}[-][0-9]{1,4}$") || phone.matches("^[0-9]{1,3}[-][0-9]{1,4}[-][0-9]{1,4}$")
|| phone.matches("^[0-9]{1,7}$")) {
found = true;
}
return found;
}//Method
public boolean isstrNameValid1(String strname){ //names O'hara
if (strname.matches("[a-zA-Z '-]+")){
strname = strname.substring(0,1).toUpperCase()+strname.substring(1).toLowerCase();
System.out.println(strname);
return true;
}else {
return false;
}
}//Method
}
| true |
5e6b392328f30c77a40ff401d347fad51738b3b0 | Java | scm-manager/scm-manager | /scm-core/src/main/java/sonia/scm/io/ZipUnArchiver.java | UTF-8 | 4,591 | 2.25 | 2 | [
"MIT"
] | permissive | /*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package sonia.scm.io;
//~--- non-JDK imports --------------------------------------------------------
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sonia.scm.util.IOUtil;
//~--- JDK imports ------------------------------------------------------------
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author Sebastian Sdorra
*/
public class ZipUnArchiver extends AbstractUnArchiver
{
/** Field description */
public static final String EXTENSION = ".zip";
/** the logger for ZipUnArchiver */
private static final Logger logger =
LoggerFactory.getLogger(ZipUnArchiver.class);
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param inputStream
* @param outputDirectory
*
* @throws IOException
* @since 1.21
*/
public void extractArchive(InputStream inputStream, File outputDirectory)
throws IOException
{
ZipInputStream input = new ZipInputStream(inputStream);
ZipEntry entry = input.getNextEntry();
while (entry != null)
{
extractEntry(outputDirectory, input, entry);
entry = input.getNextEntry();
}
}
/**
* Method description
*
*
* @param archive
* @param outputDirectory
*
* @throws IOException
*/
@Override
protected void extractArchive(File archive, File outputDirectory)
throws IOException
{
if (logger.isDebugEnabled())
{
logger.debug("extract zip \"{}\" to \"{}\"", archive.getPath(),
outputDirectory.getAbsolutePath());
}
InputStream input = null;
try
{
input = new FileInputStream(archive);
extractArchive(input, outputDirectory);
}
finally
{
IOUtil.close(input);
}
}
/**
* Method description
*
*
* @param outputDirectory
* @param name
*
* @return
*/
private File createFile(File outputDirectory, String name)
{
if (name.contains(".."))
{
throw new IllegalArgumentException("name is invalid");
}
return new File(outputDirectory, name);
}
/**
* Method description
*
*
* @param outputDirectory
* @param input
* @param entry
*
* @throws IOException
*/
private void extractEntry(File outputDirectory, ZipInputStream input,
ZipEntry entry)
throws IOException
{
try
{
File file = createFile(outputDirectory, entry.getName());
if (!entry.isDirectory())
{
File parent = file.getParentFile();
if (parent != null)
{
IOUtil.mkdirs(parent);
extractFile(input, file);
}
else
{
logger.warn("file {} has no parent", file.getPath());
}
}
else
{
IOUtil.mkdirs(file);
}
}
finally
{
input.closeEntry();
}
}
/**
* Method description
*
*
* @param input
* @param outputFile
*
* @throws IOException
*/
private void extractFile(ZipInputStream input, File outputFile)
throws IOException
{
FileOutputStream output = null;
try
{
output = new FileOutputStream(outputFile);
IOUtil.copy(input, output);
}
finally
{
IOUtil.close(output);
}
}
}
| true |
9b56ecc199413669dc11f27734c5bed62504dc8d | Java | smartsheet-platform/smartsheet-java-sdk | /src/main/java/com/smartsheet/api/RowResources.java | UTF-8 | 7,262 | 2.4375 | 2 | [
"Apache-2.0"
] | permissive | package com.smartsheet.api;
/*
* #[license]
* Smartsheet SDK for Java
* %%
* Copyright (C) 2014 Smartsheet
* %%
* 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.
* %[license]
*/
import com.smartsheet.api.models.*;
import com.smartsheet.api.models.enums.ObjectInclusion;
import java.util.EnumSet;
import java.util.List;
/**
* <p>This interface provides methods to access Row resources.</p>
*
* <p>Thread Safety: Implementation of this interface must be thread safe.</p>
*/
public interface RowResources {
/**
* <p>Get a row.</p>
*
* <p>It mirrors to the following Smartsheet REST API method: GET /row/{id}</p>
*
* @param id the id
* @param includes used to specify the optional objects to include.
* @return the row resource (note that if there is no such resource, this method will throw
* ResourceNotFoundException rather than returning null).
* @throws IllegalArgumentException if any argument is null or empty string
* @throws InvalidRequestException if there is any problem with the REST API request
* @throws AuthorizationException if there is any problem with the REST API authorization (access token)
* @throws ResourceNotFoundException if the resource cannot be found
* @throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
* @throws SmartsheetException if there is any other error during the operation
*/
public Row getRow(long id, EnumSet<ObjectInclusion> includes) throws SmartsheetException;
/**
* <p>Move a row.</p>
*
* <p>It mirrors to the following Smartsheet REST API method: PUT /row/{id}</p>
*
* @param id the id of the row to move
* @param rowWrapper the row wrapper that specifies where to move the row.
* @return the list of rows that have been moved by this operation.
* @throws IllegalArgumentException if any argument is null or empty string
* @throws InvalidRequestException if there is any problem with the REST API request
* @throws AuthorizationException if there is any problem with the REST API authorization (access token)
* @throws ResourceNotFoundException if the resource cannot be found
* @throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
* @throws SmartsheetException if there is any other error during the operation
*/
public List<Row> moveRow(long id, RowWrapper rowWrapper) throws SmartsheetException;
/**
* <p>Delete a row.</p>
*
* <p>It mirrors to the following Smartsheet REST API method: DELETE /row{id}</p>
*
* @param id the id of the row
* @throws IllegalArgumentException if any argument is null or empty string
* @throws InvalidRequestException if there is any problem with the REST API request
* @throws AuthorizationException if there is any problem with the REST API authorization (access token)
* @throws ResourceNotFoundException if the resource cannot be found
* @throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
* @throws SmartsheetException if there is any other error during the operation
*/
public void deleteRow(long id) throws SmartsheetException;
/**
* <p>Send a row via email to the designated recipients.</p>
*
* <p>It mirrors to the following Smartsheet REST API method: POST /row/{id}/emails</p>
*
* @param id the id
* @param email the email
* @throws IllegalArgumentException if any argument is null or empty string
* @throws InvalidRequestException if there is any problem with the REST API request
* @throws AuthorizationException if there is any problem with the REST API authorization (access token)
* @throws ResourceNotFoundException if the resource cannot be found
* @throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
* @throws SmartsheetException if there is any other error during the operation
*/
public void sendRow(long id, RowEmail email) throws SmartsheetException;
/**
* <p>Update the values of the Cells in a Row.</p>
*
* <p>It mirrors to the following Smartsheet REST API method: PUT /row/{id}/cells</p>
*
* @param rowId the row id
* @param cells the cells to update
* @return the list
* @throws IllegalArgumentException if any argument is null or empty string
* @throws InvalidRequestException if there is any problem with the REST API request
* @throws AuthorizationException if there is any problem with the REST API authorization (access token)
* @throws ResourceNotFoundException if the resource cannot be found
* @throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
* @throws SmartsheetException if there is any other error during the operation
*/
public List<Cell> updateCells(long rowId, List<Cell> cells) throws SmartsheetException;
/**
* <p>Get the cell modification history.</p>
*
* <p>It mirrors to the following Smartsheet REST API method: GET /row/{rowId}/column/{columnId}/history</p>
*
* @param rowId the row id
* @param columnId the column id
* @return the cell modification history (note that if there is no such resource, this method will throw
* ResourceeNotFoundException rather than returning null).
* @throws IllegalArgumentException if any argument is null or empty string
* @throws InvalidRequestException if there is any problem with the REST API request
* @throws AuthorizationException if there is any problem with the REST API authorization (access token)
* @throws ResourceNotFoundException if the resource cannot be found
* @throws ServiceUnavailableException if the REST API service is not available (possibly due to rate limiting)
* @throws SmartsheetException if there is any other error during the operation
*/
public List<CellHistory> getCellHistory(long rowId, long columnId) throws SmartsheetException;
/**
* <p>Return the AssociatedAttachmentResources object that provides access to attachment resources associated with Row
* resources.</p>
*
* @return the associated attachment resources
*/
public AssociatedAttachmentResources attachments();
/**
* <p>Return the AssociatedDiscussionResources object that provides access to discussion resources associated with
* Row resources.</p>
*
* @return the associated discussion resources
*/
public AssociatedDiscussionResources discussions();
} | true |
4f98a5c8a3f4387f41b8e727e183e4eec25259bd | Java | apurvparekh30/ucfprogrammingteam | /8thsep18/practice/solutions/upwards/upwards.java | UTF-8 | 1,459 | 3.59375 | 4 | [] | no_license | // Arup Guha
// 1/29/2014
// Solution to 2013 SI@UCF Final Contest Question: Upwards
// Used for COP 2014 COP 4516 Class
import java.util.*;
public class upwards {
public static int curRank;
public static int skip;
public static int len;
public static int rank;
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
int numCases = stdin.nextInt();
// Go through each case.
for (int loop=0; loop<numCases; loop++) {
// Read in this case and set up our current rank.
skip = stdin.nextInt();
len = stdin.nextInt();
rank = stdin.nextInt();
curRank = 0;
// Solve and output.
System.out.println(getRank());
}
}
// Wrapper function.
public static String getRank() {
char[] ans = new char[len];
return getRankRec(ans, 0);
}
public static String getRankRec(char[] cur, int k) {
// Base case, finished a string, see if it's the right one.
if (k == len) {
curRank++;
if (curRank == rank) return new String(cur);
else return null;
}
// Find the first possible character for slot k.
char start = 'a';
if (k > 0)
start = (char)(cur[k-1] + skip + 1);
// Try each possible letter in slot k.
for (char c=start; c<='z'; c++) {
cur[k] = c;
String tmp = getRankRec(cur, k+1);
if (tmp != null) return tmp;
}
// No string of the proper rank was found.
return null;
}
} | true |
778a0ef70301eb60406544899e52d827e663e7b4 | Java | HaydenBrewBrew/ee422c_hbl297 | /Project 1/src/assignment1/SortTools.java | UTF-8 | 3,862 | 3.890625 | 4 | [] | no_license | // SortTools.java
/*
* EE422C Project 1 submission by Hayden Lydick
* Hayden Lydick
* hbl297
* 16290
* Spring 2017
* Slip days used: 0
*/
package assignment1;
import java.util.Arrays;
public class SortTools {
/**
* This method tests to see if the given array is sorted.
* @param x is the array
* @param n is the size of the input to be checked
* @return true if array is sorted
*/
public static boolean isSorted(int[] x, int n) {
if(n<=0){ //solves edge condition of n=0
return false;
}
//Checks if a number in the array is greater than the next number in the array
for(int i = 0; i < n - 1; i++ ){
if(x[i] > x[i+1]){
return false;
}
}
return true;
}
//Searches
/**
* This method tests to see if the array possess a value v
* @param x: array to be tested
* @param n: length of array
* @param v: value to search for
* @return index of value or -1 if not found
*/
public static int find(int[] x, int n, int v) {
//binary sort
int index1 = 0;//lower index
int index2 = n - 1;//higher index
int mid; //center
while(index2 >= index1){
mid = (index1 + index2)/2;//find midpoint of the two index
if(x[mid] == v){//return if mid is the location of v
return mid;
}
if (x[mid] > v ){//set new upper bound if v is less than mid
index2 = mid-1;
}
else{//set new lower bound if v is greater than mid
index1 = mid+1;
}
}
return (-1);//value not found
}
/**\
* This method returns a new array of length n+1 with the value v inserted: non decreasing order
* @param x array to copy and insert
* @param n length of array
* @param v value to add
* @return array of n+1 length if v is not within the array already, length n if already present
*/
public static int[] insertGeneral(int[] x, int n, int v) {
//creates new array and initializes variables
int[] r = new int[n+1];
int index;
int flag=0;
if(n==0){//checks for edge case of n=0
r[n]=v;
return r;
}
for(index = 0; index < n; index++){ //cycle through all index
if(x[index]==v){//checks for v and return a copy of array if found
return(Arrays.copyOfRange(x, 0,n));
}
if(flag == 1){//shifts storage of x data by + 1 in new array r if v is placed
r[index+1] = x[index];
}
else{//inputs data from x into r
r[index] = x[index];
if(x[index]>v){//sets placed flag when v's location is found
r[index] = v;
r[index+1] = x[index];
flag = 1;
}
}
}
if(x[n-1] < v){//checks for edge condition where v> all current array values
r[n] = v;
}
return r;
}
/**
* This method edits the original array to insert the value v within it: non decreasing order
* @param x array to edit
* @param n length of array
* @param v value to insert
* @return
*/
public static int insertInPlace(int[] x, int n, int v){
int index;
//checks for v
//modification of insertion sort
if(find(x,n,v)!= -1){
return n;
}
for(index = n; index > 0; index--) {//cycles from last array value to first
if(x[index-1] < v) {//places v when location is found
x[index] = v;
break;
}
x[index] = x[index - 1];//shifts all data over 1 index until v location is found
}
if(index==0){// checks for edge condition that v is < all values in array
x[0] = v;
}
return n+1;
}
/**
* Sorts an array in non-decreasing order
* @param x array to be sorted
* @param n length of the array
*/
public static void insertSort(int[] x, int n){
//insert sort algorithm
for(int i = 1; i<n; i++){
int v = x[i];//sets current value to be sorted
int k;//location to sort from
for(k = i - 1; k>=0; k--){//shifts all data over 1 index until current value is sorted
if(x[k] <= v){
break;
}
x[k+1] = x[k];//shift data by 1 index
}
x[k+1] = v;
}
}
}
| true |
488086f0ae95d61f886abef06c86af199b037e1a | Java | FRC-Team-5957/PIDTest | /src/org/usfirst/frc/team5957/robot/Robot.java | UTF-8 | 4,955 | 2.328125 | 2 | [] | no_license | package org.usfirst.frc.team5957.robot;
import edu.wpi.first.wpilibj.ADXRS450_Gyro;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.SpeedControllerGroup;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.VictorSP;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
public class Robot extends IterativeRobot {
DifferentialDrive base;
SpeedController frontLeft;
SpeedController rearLeft;
SpeedController frontRight;
SpeedController rearRight;
SpeedControllerGroup left;
SpeedControllerGroup right;
Joystick joy;
ADXRS450_Gyro gyro;
Timer time;
Encoder leftE;
// PIDController frontLeftPID;
// PIDController rearLeftPID;
// PIDController frontRightPID;
// PIDController rearRightPID;
final double Kp = 0.2125;
final double Kd = 3.2; // Kd = 3.2 when Kp = 0.2125 can do 90 degrees turn
final double eKp = 0.0;
final double eKd = 0.0;
final double delay = 0.004;
double gyroTarget = 0;
double encTarget = 0;
double gyroP = 0; // 90 - 0
double gyroPLast = 0; // 90
double gyroD = 0; // 0
double output = 0; // 0.9 - 0
double gyroOut = 0;
double encP = 0;
double encPLast = 0;
double encD = 0;
double encOut = 0;
double done = 0;
@Override
public void robotInit() {
// Front left, rear left, front right, rear right
frontLeft = new VictorSP(2);
frontLeft.setInverted(true);
rearLeft = new VictorSP(3);
rearLeft.setInverted(true);
frontRight = new VictorSP(0);
frontRight.setInverted(true);
rearRight = new VictorSP(1);
rearRight.setInverted(true);
left = new SpeedControllerGroup(frontLeft, rearLeft);
right = new SpeedControllerGroup(frontRight, rearRight);
leftE = new Encoder(2, 3, false);
base = new DifferentialDrive(left, right);
joy = new Joystick(0);
gyro = new ADXRS450_Gyro();
time = new Timer();
gyro.reset();
gyro.calibrate();
// frontLeftPID = new PIDController(Kp, Ki, Kd, gyro, frontLeft);
// rearLeftPID = new PIDController(Kp, Ki, Kd, gyro, frontLeft);
// frontRightPID = new PIDController(Kp, Ki, Kd, gyro, frontLeft);
// rearRightPID = new PIDController(Kp, Ki, Kd, gyro, frontLeft);
}
@Override
public void robotPeriodic() {
gyroP = gyroTarget - gyro.getAngle(); // 90 - 0
gyroPLast = gyroP; // 90
gyroD = gyroPLast - gyroP; // 0
output = (gyroP * Kp) - (gyroD * Kd); // 0.9 - 0
}
@Override
public void disabledInit() {
}
@Override
public void disabledPeriodic() {
}
boolean straightAuto = true;
@Override
public void autonomousInit() {
time.reset();
time.start();
leftE.reset();
if (straightAuto == false) { // turn to 90 degrees
double target = 90;
double gyroP = target - gyro.getAngle(); // 90 - 0
double gyroPLast = gyroP; // 90
double gyroD = gyroPLast - gyroP; // 0
double output = (gyroP * Kp) - (gyroD * Kd); // 0.9 - 0
while (output != 0 && gyro.getAngle() != target) {
if (output > 0.6) {
output = 0.6;
} else if (output < -0.6) {
output = -0.6;
}
base.arcadeDrive(0, -output);
Timer.delay(delay);
gyroPLast = gyroP;
gyroP = target - gyro.getAngle();
gyroD = gyroPLast - gyroP;
output = (gyroP * Kp) - (gyroD * Kd);
}
} else { // drive for 2 meters (eventually)
gyroPID();
encPID();
encTarget = 4600; // ~2 yards
base.arcadeDrive(encOut, -gyroOut);
}
}
@Override
public void autonomousPeriodic() {
System.out.println(leftE.get());
if (leftE.get() > 5000) {
base.arcadeDrive(0, -output);
}
}
private void turn(double angle) {
gyroTarget = angle;
}
private void move(double dist) {
encTarget = dist;
}
private void gyroPID() {
gyroP = gyroTarget - gyro.getAngle(); // 90 - 0
gyroPLast = gyroP; // 90
gyroD = gyroPLast - gyroP; // 0
gyroOut = (gyroP * Kp) - (gyroD * Kd); // 0.9 - 0
if (gyroOut != 0 && gyro.getAngle() != gyroTarget) {
if (gyroOut > 0.6) {
gyroOut = 0.6;
} else if (gyroOut < -0.6) {
gyroOut = -0.6;
}
Timer.delay(delay);
gyroPLast = gyroP;
gyroP = gyroTarget - gyro.getAngle();
gyroD = gyroPLast - gyroP;
gyroOut = (gyroP * Kp) - (gyroD * Kd);
}
}
private void encPID() {
encP = encTarget - leftE.get();
encPLast = encP;
encD = encPLast - encP;
encOut = (encP * eKp) - (encD * eKd);
if (encOut != 0 && leftE.get() != encTarget)
if (encOut > 0.6) {
encOut = 0.6;
} else if (encOut < -0.6) {
encOut = -0.6;
}
Timer.delay(delay);
encPLast = encP;
encP = encTarget - leftE.get();
encD = encPLast - encP;
encOut = (encP * eKp) - (encD * eKd);
}
@Override
public void teleopInit() {
}
@Override
public void teleopPeriodic() {
base.arcadeDrive(joy.getRawAxis(1), -joy.getRawAxis(4));
System.out.print(leftE.getDistance());
}
@Override
public void testInit() {
}
@Override
public void testPeriodic() {
}
}
| true |
0b2737a397011b55dc13cd2b7e5b6c63a49f8476 | Java | MikhailChe/SortComparison | /src/sort/VecaRect.java | UTF-8 | 16,164 | 3.03125 | 3 | [] | no_license | package sort;
import java.awt.Color;
import java.awt.Font;
import java.util.Vector;
import acm.graphics.GLabel;
import acm.graphics.GRect;
public class VecaRect {
public VecaRect(Main m) {
/*
* Конструктор класса VecaRect. Принимает указатель на объект класса
* Main
*/
main = m;
NOS++;
/*
* Записываем в переменную main указатель на объект класса Main и
* прибавляем к статичной переменной NOS еденицу
*/
}
public VecaRect(Main m, Integer noel) {
/*
* Конструктор класса VecaRect. Принимает указатель на объект класса
* Main и количество элементов
*/
main = m;
NOS++;
initArray(noel, false, false);
/*
* Записываем в переменную main указатель на объект класса Main,
* прибавляем к статичной переменной NOS еденицу и инициализируем
* массив, передавая соответствующие параметры
*/
}
public synchronized void setTime(String time) {
/*
* setTime - функция для установки времени сортировки Данная функция
* является синхронизированой во избежание повреждения данных
*/
SortTime.setLabel(time);
SortTime.setVisible(true);
SortTime.setColor(timeColor);
SortTime.sendToFront();
/*
* Приравниваем надписи SortTime значение time Делаем её видимой
* Присваиваем цвет timeColor; Выкидываем надпись на передний план
*/
}
public void clearTime() {
/*
* Функция очистки времени сортировки Применяется когда начинается новая
* сортировка Просто делает надпись с временем невидимой
*/
SortTime.setVisible(false);
}
public synchronized void SelectElement(int index) {
/*
* Функция графического выделения элемента. По своей сути она просто
* добавляет в массив(вектор) Selected элемент с индексом элемента,
* который нужно выделить
*/
Selected.add(index);
}
public synchronized boolean lockUpdateRects() {
/*
* Функция блокировки перерисовки массива. Применяется для того чтобы
* анимация не дергалась.
*/
if (islockedUpdateRects())
return false;
lockUpdateRects = true;
return true;
/*
* Сначала проверяем установлено ли уже значение в true. Если значение
* установлено в true, то функция возвращает false и ничего не делает.
* Возврат булевого значения полезен для того чтобы знать, была ли уже
* заблокирована перерисовка или нет. Если lockUpdateRects было false,
* то меняем его в true и возвращаем true.
*/
}
public synchronized boolean unlockUpdateRects() {
/*
* Похожая на lockUpdateRects() функция, только делает всё наоборот.
*/
if (!islockedUpdateRects())
return false;
lockUpdateRects = false;
return true;
}
public synchronized boolean islockedUpdateRects() {
/*
* Функция которая проверяет установлена ли блокировка или нет
*/
return lockUpdateRects;
}
public synchronized boolean isSelected(int index) {
/*
* Проверяет установлено ли графическое выделение на элемент или нет
*/
for (int i = 0; i < Selected.size(); i++) {
if (Selected.get(i).equals(index)) {
return true;
}
}
return false;
/*
* Проходимся по массиву. Если находим наш элемент - возвращаем true.
* Если не находим - возвращаем false
*/
}
public synchronized void DeselectAll() {
/*
* Функция для снятия графического выделения со всех элементов
*/
Selected.clear();
}
public synchronized void initArray(Integer noel, boolean isSorted, boolean upSorted) {
/*
* Функция инициализации массива. Принимает параметры: noel: количество
* элементов в массиве isSorted: отсортирован ли массив upSorted:
* отсортирован ли массив вверх или вниз
*/
Numbers.clear();
/*
* Очищаем массив с значениями
*/
if (isSorted) {
/*
* Если нужно сортировать
*/
if (upSorted) {
/*
* И сортировать нужно вверз
*/
for (int i = 0; i < noel; i++) {
/*
* Добавляем подряд элементы
*/
Numbers.add(i);
}
} else {
/*
* Если вниз, то элементы добавляются в обратном порядке
*/
for (int i = 0; i < noel; i++) {
Numbers.add(noel - i);
}
}
} else {
/*
* Если не сортировать, то добавляются случайные числа
*/
for (int i = 0; i < noel; i++) {
Numbers.add((int) (Math.random() * (double) noel));
}
}
}
public synchronized void initArray(Vector<Integer> arr) {
/*
* Функция инициализации массива, принимает один параметр: массив,
* который нужно вставить. Данная функция используется, когда нужно
* создать одинаковые массивы
*/
Numbers.clear();
Numbers.addAll(arr);
/*
* Сначала очищаем массив, а потом добавляем все элементы из
* передаваемого массива
*/
}
public synchronized void initRects(Integer NIQ) {
/*
* Функция инициализации графики. Принимает один параметр - NIQ: номер в
* очереди. Параметр NIQ нужен для того, чтобы знать, куда конкретно
* вставлять элементы графики
*/
Rects.clear();
Values.clear();
vecs.clear();
/*
* Очщиаем все прямоугольники и надписи со значениями
*/
clearTime();
/*
* Очищаем время сортировки
*/
for (int i = 0; i < Numbers.size(); i++) {
/*
* Для каждого из элеметов массива делаем следующее
*/
GRect r = new GRect(0, 0, 0, 0);
/*
* Создаем новый прямоугольник
*/
r.setFilled(true);
/*
* Переключаем его в режим заливания - площадь внутри контура
* прямоугольника будет залита цветом
*/
Rects.add(r);
/*
* Добавляем его в вектор прямоугольников
*/
GLabel l = new GLabel("");
/*
* Создаем пустой лэйбл (надпись)
*/
Values.add(l);
/*
* Добавляем её в вектор надписей
*/
}
Name = new GLabel("");
/*
* Создаем пустое имя сотировки
*/
updateRects(NIQ);
/*
* Обновляем графику, чтобы всё приняло свои места
*/
}
public synchronized void updateRects(Integer NIQ) {
/*
* Функция обновления графики
*/
if (Numbers.size() != Rects.size()) {
/*
* Если количество чисел не совпадает с количеством прямоугольников
* - нужно заново инициализировать графику. Инициализируем, выходим
* из функции.
*/
initRects(NIQ);
return;
}
if (islockedUpdateRects()) {
/*
* Если графику обновлять запрещено, то выходим из функции
*/
return;
}
if (!lockUpdateRects()) {
/*
* Если заблокировать обновление графики не получилось, то это
* значит, что графика заблокирована, выходим из функции
*/
return;
}
for (int i = 0; i < Rects.size(); i++) {
/*
* Для каждого из прямоугольников делаем:
*/
Double BarHeight = (double) main.getHeight() * (double) Numbers.get(i) / Rects.size() / (double) NOS;
/*
* Вычисляем высоту прямоугольника
*/
Rects
.get(i)
.setLocation((double) i * (double) main.getWidth() / Rects.size(),
main.getHeight() * ((double) NIQ + (double) 1) / (double) NOS - BarHeight);
/*
* Устанавливаем положение прямоугольника: По X координате -
* вычисляем какой это прямоугольник по порядку, умножаем порядковое
* число на частное от щирины холста и количества прямоугольников
* Частным являеися ширина прямоугольника.
*
* По Y - умножаем высоту холста на порядковый номер массива (NIQ) и
* делим на количество массивов. Вчитаем высоту прямоугольника
*/
Rects.get(i).setSize((double) main.getWidth() / (double) Rects.size(), BarHeight);
/*
* Устанавливаем ширину прямоугольника как ширину холста деленая на
* количество прямоугольников, а высота уже пощитана - BarHeight
*/
if (isSelected(i)) {
/*
* Если прямоугольник нужно выделить - заливаем одним цветом,
* если нет, то другим
*/
Rects.get(i).setFillColor(selectedColor);
} else {
Rects.get(i).setFillColor(usualColor);
}
/*
* Если размер надписи значения очень маленький, то мы его не
* показываем
*/
if ((1.0 * main.getWidth() / Numbers.size() <= 10)
|| (Values.get(i).getHeight() > 1.0 * main.getHeight() / NOS)) {
Values.get(i).setVisible(false);
} else {
Values.get(i).setVisible(true);
Values.get(i).setLabel(Numbers.get(i).toString());
Values
.get(i)
.setFont(new Font("Sans-Serif", Font.PLAIN,
(int) ((double) main.getWidth() / (double) Numbers.size() * 0.75)));
if (!SortTime.isVisible())
Values.get(i).sendToFront();
Values
.get(i)
.setLocation((i + 0.5) * main.getWidth() / Numbers.size() - Values.get(i).getWidth() * 0.5,
(double) main.getHeight() / (double) NOS * (NIQ + 1));
}
}
/*
* Если название сортировки не нулевое, то перемещаем в нужную позицию
*/
if (Name != null) {
Name.setLocation(0, Name.getHeight() + (double) main.getHeight() / (double) NOS * (double) NIQ);
}
/*
* Если время сортировки нужно показывать, то перемещаем его в нужную
* позицию, задаем шрифт, и выбрасываем на передний план
*/
if (SortTime.isVisible()) {
SortTime.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, (int) (main.getHeight() / (double) NOS / 2.0)));
SortTime.setLocation(0, main.getHeight() / (double) NOS * (NIQ + 0.5) + SortTime.getHeight() / 2.0);
SortTime.sendToFront();
}
unlockUpdateRects();
/*
* Разблокировываем обновление графики
*/
}
public synchronized void setName(String name) {
if (Name != null) {
Name.setLabel(name);
} else {
Name = new GLabel(name);
}
}
public void Swap(int index1, int index2, boolean animation) {
/*
* Функция анимированой перестановки элементов местами
*/
lockUpdateRects();
/*
* Блокируем обновление графики данного массива, чтобы не дергалась
* анимация
*/
if (animation && Main.PAUSETIME.getValue() > 0) {
/*
* Высчитываем X координаты, помещаем перемещаемые прямоугольники и
* надписи на передний план, и запускаем анимацию из 100 кадров.
*/
double pos1 = Rects.get(index1).getX();
double pos2 = Rects.get(index2).getX();
Rects.get(index1).sendToFront();
Rects.get(index2).sendToFront();
Values.get(index1).sendToFront();
Values.get(index2).sendToFront();
for (int i = 0; i < 100; i++) {
Rects.get(index1).move((pos2 - pos1) / 100.0, (i - 50) / 50.0);
Values.get(index1).move((pos2 - pos1) / 100.0, (i - 50) / 50.0);
Rects.get(index2).move((pos1 - pos2) / 100.0, (50 - i) / 50.0);
Values.get(index2).move((pos1 - pos2) / 100.0, (50 - i) / 50.0);
Main.pause(Main.PAUSETIME.getValue() / 60);
}
}
/*
* После анимации меняем местами сами значения
*/
Integer bzz = Numbers.get(index1);
Numbers.set(index1, Numbers.get(index2));
Numbers.set(index2, bzz);
unlockUpdateRects();
/*
* Разблокировываем обновление графики
*/
}
public Vector<Integer> Numbers = new Vector<>();
/*
* Вектор из значений элементов
*/
public Vector<GRect> Rects = new Vector<>();
/*
* Вектор из прямоугольников
*/
public Vector<GLabel> Values = new Vector<>();
/*
* Вектор из надписей значений
*/
public Vector<Integer> Selected = new Vector<>();
/*
* Вектор из индексов элементов для выделения
*/
public GLabel Name = new GLabel("");
/*
* Надпись, содеражащая имя сортировки
*/
public GLabel SortTime = new GLabel("");
/*
* Надпись о времени, потраченом на сортировку
*/
public static Integer NOS = 0;
/*
* Статичная переменная, содержащая количество активных массивов(векторов)
*/
public static Vector<VecaRect> vecs = new Vector<>();
private Main main;
/*
* Переменная для хранения указателя на Main
*/
private static Color usualColor = Color.GREEN;
private static Color selectedColor = Color.RED;
private static Color timeColor = Color.RED;
/*
* Цвета, используемые в графике
*/
private boolean lockUpdateRects = false;
/*
* Переменная блокировки олбновления графики
*/
} | true |
bf133a9b68b3fe7b0c438e0b1e37563fc604a828 | Java | dsalexan/yogurt | /yogurt/src/main/DiagramaganttController.java | UTF-8 | 6,373 | 2.375 | 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 main;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
/**
* FXML Controller class
*
* @author rafae
*/
public class DiagramaganttController implements Initializable {
@FXML
private HBox hbxTimeline;
@FXML
private HBox hbxBoxes;
private Diagrama diagram;
private ControladorGeralSingleton CONTROL;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
CONTROL = ControladorGeralSingleton.getInstancia();
CONTROL.ProcessDiagram = this;
// TODO
//create dummy-test diagram
/*
Processo p1 = new Processo(0, 1, 1, "1", "#3399ff");
Processo p2 = new Processo(0, 1, 1, "2", "80B3FF");
Processo p3 = new Processo(0, 1, 1, "3", "FF8080");
Processo p4 = new Processo(0, 1, 1, "4", "AE592D");
ArrayList<DiagramaGantt> diagramG = new ArrayList<DiagramaGantt>();
diagramG.add(new DiagramaGantt(0, 1, p1));
diagramG.add(new DiagramaGantt(1, 2, p2));
diagramG.add(new DiagramaGantt(2, 4, p1));
diagramG.add(new DiagramaGantt(4, 8, p3));
diagramG.add(new DiagramaGantt(8, 11, p4));
diagramG.add(new DiagramaGantt(11, 12, p1));
diagramG.add(new DiagramaGantt(12, 17, p1));
diagramG.add(new DiagramaGantt(17, 21, p2));
diagramG.add(new DiagramaGantt(21, 24, p1));
diagramG.add(new DiagramaGantt(24, 28, p3));
diagramG.add(new DiagramaGantt(28, 31, p4));
diagramG.add(new DiagramaGantt(31, 37, p1));
//parse DiagramaGantt to Diagrama
diagram = new Diagrama(diagramG);
loadDiagram(diagram);*/
}
// CAPSULE METHODS //
public void loadDiagram(Diagrama d){
//clear all
hbxTimeline.getChildren().clear();
hbxBoxes.getChildren().clear();
hbxBoxes.setPrefWidth(0.0);
hbxTimeline.setPrefWidth(0.0);
// create timeline
drawTimeline(d, hbxTimeline);
// create diagram
drawDiagram(d, hbxBoxes);
}
// DRAWING METHODS //
public Label generateRegister(String text){
return generateRegister(text, 22.0, "#fafafa", null, null);
}
public Label generateRegister(String text, double width, String cor, Algoritmo a, Processo p){
final Label lbl = new Label(text);
lbl.setAlignment(Pos.CENTER);
lbl.setContentDisplay(ContentDisplay.CENTER);
lbl.setPrefHeight(22.0);
lbl.setPrefWidth(width);
lbl.setMinWidth(width);
lbl.setBackground(new Background(new BackgroundFill(Color.web(cor), CornerRadii.EMPTY, Insets.EMPTY)));
lbl.setTextAlignment(TextAlignment.CENTER);
if (a != null && p != null) {
final Tooltip ttp = new Tooltip(
"Tempo de espera: " + String.valueOf(p.getTempoEspera()) + "\n"+
"Tempo de espera médio (" + a.nome + "): " + String.valueOf(a.tempoMedio));
//ttp.setStyle("-fx-font: 11px;");
lbl.setTooltip(ttp);
}
return lbl;
}
public Label generateTime(String text, double width){
final Label lbl = new Label(text);
lbl.setAlignment(Pos.CENTER);
lbl.setContentDisplay(ContentDisplay.CENTER);
lbl.setPrefHeight(15.0);
lbl.setPrefWidth(width);
lbl.setMinWidth(width);
lbl.setBackground(new Background(new BackgroundFill(Color.rgb(244, 244, 244), CornerRadii.EMPTY, Insets.EMPTY)));
lbl.setTextAlignment(TextAlignment.CENTER);
lbl.setFont(Font.font("System", 10.0));
return lbl;
}
public void drawTimeline(Diagrama diagram, HBox timeline){
double currentSpace = 3.5 - 7.5; // primeira caixa n tem espaço a esquerda, só a padding
for(int t = diagram.getTempoInicial(); t <= diagram.getTempoFinal(); t++) {
currentSpace += 15.0 + 7.5;
if (currentSpace > timeline.getPrefWidth()){ // linha do tempo vai passar o limite da tela
timeline.setPrefWidth(currentSpace);
}
timeline.getChildren().add(generateTime(String.valueOf(t), 15.0));
}
// fill the rest of timeline space
double filledSpace = diagram.getTempoFinal() * (15.0 + 7.5) - 7.5;
double emptySpace = timeline.getPrefWidth() - filledSpace - 3.5;
timeline.getChildren().add(generateTime(String.valueOf("-"), emptySpace));
}
public void drawDiagram(Diagrama diagram, HBox boxes) {
//generate figures for each entry in the diagram
//merge equal figures wich are next to each other
double currentSpace = 1.0 - 1.0; // primeira caixa n tem espaço a esquerda, só a padding
for(Diagrama.Registro r : diagram.registros) {
double width = (22.0 + 1.0) * (r.fim - r.inicio) - 1;
currentSpace += width + 1.0;
if (currentSpace > boxes.getPrefWidth()){
boxes.setPrefWidth(currentSpace);
}
String text = r.processo != null ? r.processo.getId() : "-";
String cor = r.processo != null ? r.processo.getCor() : "#fafafa";
boxes.getChildren().add(generateRegister(text, width, cor, diagram.getAlgoritmo(), r.processo));
}
double filledSpace = diagram.getTempoFinal() * (22.0 + 1.0) - 1.0;
double emptySpace = boxes.getPrefWidth() - filledSpace;
boxes.getChildren().add(generateRegister(String.valueOf("-"), emptySpace, "#fafafa", null, null));
}
public void clearHBox(HBox hbx){
hbx.getChildren().removeAll();
}
}
| true |
565c59e563cefeff69f7ba603b9f64c3f8418fe4 | Java | step9819/Cibertec_dawii | /Examen_Servicios/JAX_WS_SOAP_Cliente_Plantilla/src/soap/cibertec/servicio/ViajeService.java | UTF-8 | 759 | 2.25 | 2 | [] | no_license | package soap.cibertec.servicio;
import java.util.List;
import soap.cibertec.interfaces.ViajeBean;
public class ViajeService {
private ViajeServiceImplService ws=null;
public List<ViajeBean> listaViaje(double precioDesde, double precioHasta){
List<ViajeBean> lista=null;
try {
ws=new ViajeServiceImplService();
Sericio soap=ws.getServicioViajePort();
lista=soap.listAllViajesXprecio(precioDesde, precioHasta);
}catch (Exception e) {
e.printStackTrace();
}
return lista;
}
public int saveViaje(ViajeBean bean) {
int salida= -1;
try {
ws=new ViajeServiceImplService();
Sericio soap=ws.getServicioViajePort();
salida=soap.saveViaje(bean);
}catch (Exception e) {
e.printStackTrace();
}
return salida;
}
}
| true |
202bb91d76fca2821ca9424495eeb7142e28f3f9 | Java | apache/commons-validator | /src/test/java/org/apache/commons/validator/routines/checkdigit/ISBNCheckDigitTest.java | UTF-8 | 3,097 | 2.625 | 3 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.validator.routines.checkdigit;
/**
* ISBN-10/ISBN-13 Check Digit Test.
*
* @since 1.4
*/
public class ISBNCheckDigitTest extends AbstractCheckDigitTest {
/**
* Constructor
* @param name test name
*/
public ISBNCheckDigitTest(final String name) {
super(name);
}
/**
* Set up routine & valid codes.
*/
@Override
protected void setUp() {
routine = ISBNCheckDigit.ISBN_CHECK_DIGIT;
valid = new String[] {
"9780072129519",
"9780764558313",
"1930110995",
"020163385X",
"1590596277", // ISBN-10 Ubuntu Book
"9781590596272" // ISBN-13 Ubuntu Book
};
missingMessage = "ISBN Code is missing";
zeroSum = "000000000000";
}
/**
* Set up routine & valid codes.
*/
public void testInvalidLength() {
assertFalse("isValid() Lth 9 ", routine.isValid("123456789"));
assertFalse("isValid() Lth 11", routine.isValid("12345678901"));
assertFalse("isValid() Lth 12", routine.isValid("123456789012"));
assertFalse("isValid() Lth 14", routine.isValid("12345678901234"));
try {
routine.calculate("12345678");
fail("calculate() Lth 8 - expected exception");
} catch (final Exception e) {
assertEquals("calculate() Lth 8", "Invalid ISBN Length = 8", e.getMessage());
}
try {
routine.calculate("1234567890");
fail("calculate() Lth 10 - expected exception");
} catch (final Exception e) {
assertEquals("calculate() Lth 10", "Invalid ISBN Length = 10", e.getMessage());
}
try {
routine.calculate("12345678901");
fail("calculate() Lth 11 - expected exception");
} catch (final Exception e) {
assertEquals("calculate() Lth 11", "Invalid ISBN Length = 11", e.getMessage());
}
try {
routine.calculate("1234567890123");
fail("calculate() Lth 13 - expected exception");
} catch (final Exception e) {
assertEquals("calculate() Lth 13", "Invalid ISBN Length = 13", e.getMessage());
}
}
}
| true |
6901dce6f4595ec9088b5b51667e17cad47c8291 | Java | mattvalli/MattValliCom | /src/main/java/com/mattvalli/RapidFramework/Model/UserSystem/dao/PersonDao.java | UTF-8 | 747 | 2.234375 | 2 | [] | no_license | package com.mattvalli.RapidFramework.Model.UserSystem.dao;
public interface PersonDao {
// CONSTANTS
public static final String CLASSNAME_MODEL = "Person";
// Database
public static final String DATABASE = "USER_SYSTEM";
public static final String TABLE = "PERSON";
// Columns
public static final String COLUMN_NAME_FIRST = "name_first";
public static final String COLUMN_NAME_LAST = "name_last";
public static final String COLUMN_DOB = "date_birth";
public static final String JOIN_CONTAINER_NAME = "fk_container_name";
public static final String JOIN_GENDER = "fk_gender";
public static final String JOIN_CONTACT = "fk_contact";
// Formatters
public static final String DATE_FORMAT = "yyyy-MM-dd";
}
| true |
d714109f1f61898250532fe67d5f285f6126fbbb | Java | pjhjohn/hsk4-dict-android | /app/src/main/java/com/hsk4dictionary/android/activity/MenuActivity.java | UTF-8 | 1,403 | 2.3125 | 2 | [
"Apache-2.0"
] | permissive | package com.hsk4dictionary.android.activity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import com.hsk4dictionary.android.R;
import butterknife.BindView;
import butterknife.ButterKnife;
public class MenuActivity extends Activity {
@BindView(R.id.menu_title) TextView mMenuTitle;
@BindView(R.id.menu_search) Button mMenuSearch;
@BindView(R.id.menu_bookmark) Button mMenuBookMark;
@BindView(R.id.menu_github) Button mMenuGitHub;
@BindView(R.id.menu_exit) Button mMenuExit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
ButterKnife.bind(this);
mMenuSearch.setOnClickListener(v -> this.startActivity(new Intent(this, MainActivity.class)));
mMenuBookMark.setOnClickListener(v -> this.startActivity(new Intent(this, BookmarkActivity.class)));
mMenuGitHub.setOnClickListener(v -> {
String url = "https://github.com/pjhjohn/hsk4-dict-android";
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
});
mMenuExit.setOnClickListener(v -> this.finishAffinity());
}
}
| true |
71863cb9d83694bd3afaaa3a7240a0cf63eb56ae | Java | itsightconsulting/runfit | /src/main/java/com/itsight/repository/VideoAudioFavoritoRepository.java | UTF-8 | 1,134 | 1.945313 | 2 | [] | no_license | package com.itsight.repository;
import com.itsight.domain.VideoAudioFavorito;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface VideoAudioFavoritoRepository extends JpaRepository<VideoAudioFavorito, Integer> {
@Query("SELECT U FROM VideoAudioFavorito U WHERE U.cliente.id = ?1 AND U.audio.id = ?2")
VideoAudioFavorito findByClienteAudio(Integer clienteId, Integer audioId);
@Query("SELECT U FROM VideoAudioFavorito U WHERE U.cliente.id = ?1 AND U.video.id = ?2")
VideoAudioFavorito findByClienteVideo(Integer clienteId, Integer videoId);
@Query("SELECT U FROM VideoAudioFavorito U LEFT JOIN FETCH U.video D LEFT JOIN FETCH U.audio A WHERE U.cliente.id = ?1 AND U.Tipo = ?2")
List<VideoAudioFavorito> findAllByClienteByTipo(Integer clienteId, int tipo);
@EntityGraph(value = "videoaudio_favorito")
List<VideoAudioFavorito> findByClienteId(Integer clienteId);
}
| true |
129f93428ab12fcedac55b06c196ebd436d32916 | Java | kriquero/Programacion | /Ejercicios/Ejercicio 7.2/ejercicio72.java | UTF-8 | 1,400 | 3.5625 | 4 | [] | no_license | import java.util.Scanner;
public class ejercicio72 {
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
persona p1 = new persona();
persona p2 = new persona();
System.out.println ("Escriba el nombre de la persona 1");
p1.nombre = sc.next();
System.out.println ("Escriba los apellidos de la persona 1");
p1.apellido = sc.next();
System.out.println ("Escriba el DNI de la persona 1");
p1.DNI = sc.next();
System.out.println ("Escriba la edad de la persona 1");
p1.edad = sc.nextInt();
System.out.println ("Escriba el nombre de la persona 2");
p2.nombre = sc.next();
System.out.println ("Escriba los apellidos de la persona2");
p2.apellido = sc.next();
System.out.println ("Escriba el DNI de la persona 2");
p2.DNI = sc.next();
System.out.println ("Escriba la edad de la persona 2");
p2.edad = sc.nextInt();
String mayoria1 = (p1.edad<18)? "es menor de edad":"es mayor de edad";
String mayoria2 = (p2.edad<18)? "es menor de edad":"es mayor de edad";
System.out.println(p1.nombre + " " + p1.apellido + " con DNI " + p1.DNI + " " + mayoria1);
System.out.println(p2.nombre + " " + p2.apellido + " con DNI " + p2.DNI + " " + mayoria2);
}
}
| true |
999b055793461f196b621ee65d5b4435254e809b | Java | vaginessa/BootToShell | /app/src/main/java/com/dukelight/boottoshell/MainActivity.java | UTF-8 | 12,057 | 2.40625 | 2 | [] | no_license | package com.dukelight.boottoshell;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import static com.dukelight.boottoshell.AdbCommandUtils.getAdbStatus;
public class MainActivity extends AppCompatActivity {
Button button; // 切换adb wifi
Button button2; // 切换adb usb
Button button3; // 关闭虚拟按键
Button button4; // 打开虚拟按键
Button button5; // 重启
TextView tvAdbStatus;
public final static String PROJECT_PATH = "BootToShell/config";
public final static String ADB_TO_WIFI_FILE = "adbToWifi.sh";
public final static String ADB_TO_USB_FILE = "adbToUsb.sh";
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
button4 = (Button) findViewById(R.id.button4);
button5 = (Button) findViewById(R.id.button5);
tvAdbStatus = (TextView) findViewById(R.id.tv_adb_status);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 切换为adb wifi模式
new Thread(new Runnable() {
@Override
public void run() {
AdbCommandUtils.runToWifi();
}
}).start();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
String result = getAdbStatus();
if (result != null && result.equals("5555")) {
toast("adb切换Wifi成功");
updateWifiView();
} else {
toast("adb切换Wifi失败");
}
}
}).start();
}
}, 500);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 切换为adb usb模式
new Thread(new Runnable() {
@Override
public void run() {
AdbCommandUtils.runToUsb();
}
}).start();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
String result = getAdbStatus();
if (result != null && result.equals("-1")) {
toast("adb切换usb成功");
updateUsbView();
} else {
toast("adb切换usb失败");
}
}
}).start();
}
}, 500);
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
if (!AdbCommandUtils.isBuildPropExist()) {
AdbCommandUtils.runAppendToBuildProp();
}
}
}).start();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
AdbCommandUtils.runCloseVitualButton();
}
}).start();
}
}, 500);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
boolean result = AdbCommandUtils.isVitualButtonClose();
if (!result) {
toast("关闭虚拟按钮失败,请检查原因");
} else {
toast("关闭成功!请重新启动以生效应用配置");
}
}
}).start();
}
}, 1000);
}
});
button4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
if (!AdbCommandUtils.isBuildPropExist()) {
AdbCommandUtils.runAppendToBuildProp();
}
}
}).start();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
AdbCommandUtils.runOpenVitualButton();
}
}).start();
}
}, 500);
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
boolean result = AdbCommandUtils.isVitualButtonOpen();
if (!result) {
toast("打开虚拟按钮失败,请检查原因");
} else {
toast("打开成功!请重新启动以生效应用配置");
}
}
}).start();
}
}, 1000);
}
});
button5.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new Thread(new Runnable() {
@Override
public void run() {
AdbCommandUtils.runReboot();
}
}).start();
}
});
initFolder();
}
@Override
protected void onResume() {
super.onResume();
initAdbStatus();
}
private void initAdbStatus() {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
new Thread(new Runnable() {
@Override
public void run() {
final String result = AdbCommandUtils.getAdbStatus();
if (result != null) {
if (result.equals("5555")) {
updateWifiView();
} else {
updateUsbView();
}
} else {
updateUsbView();
}
}
}).start();
}
}, 500);
}
private void initFolder() {
File adbToWifi = new File(Environment.getExternalStorageDirectory() + "/" + PROJECT_PATH + "/" + ADB_TO_WIFI_FILE);
File adbToUsb = new File(Environment.getExternalStorageDirectory() + "/" + PROJECT_PATH + "/" + ADB_TO_USB_FILE);
if (!adbToWifi.getParentFile().exists()) {
adbToWifi.mkdirs();
}
if (!adbToUsb.getParentFile().exists()) {
adbToUsb.mkdirs();
}
if (!adbToWifi.exists()) {
createAdbToWifiFile(adbToWifi);
} else {
if (adbToWifi.isDirectory()) {
adbToWifi.delete();
createAdbToWifiFile(adbToWifi);
}
}
if (!adbToUsb.exists()) {
createAdbToUsbFile(adbToUsb);
} else {
if (adbToUsb.isDirectory()) {
adbToUsb.delete();
createAdbToUsbFile(adbToUsb);
}
}
}
private void createAdbToWifiFile(File adbToWifi) {
try {
StringBuilder sb = new StringBuilder();
sb.append("su -c 'setprop service.adb.tcp.port 5555'");
sb.append("\n");
sb.append("su -c 'stop adbd'");
sb.append("\n");
sb.append("su -c 'start adbd'");
sb.append("\n");
// sb.append("su");
// sb.append("\n");
// sb.append("setprop service.adb.tcp.port 5555");
// sb.append("\n");
// sb.append("stop adbd");
// sb.append("\n");
// sb.append("start adbd");
// sb.append("\n");
FileOutputStream fileOutputStream = new FileOutputStream(adbToWifi);
fileOutputStream.write(sb.toString().getBytes());
toast("创建adbToWifi成功");
} catch (IOException e) {
e.printStackTrace();
}
}
private void createAdbToUsbFile(File adbToUsb) {
try {
StringBuilder sb = new StringBuilder();
sb.append("su -c 'setprop service.adb.tcp.port -1'");
sb.append("\n");
sb.append("su -c 'stop adbd'");
sb.append("\n");
sb.append("su -c 'start adbd'");
sb.append("\n");
// sb.append("su");
// sb.append("\n");
// sb.append("setprop service.adb.tcp.port -1");
// sb.append("\n");
// sb.append("stop adbd");
// sb.append("\n");
// sb.append("start adbd");
// sb.append("\n");
FileOutputStream fileOutputStream = new FileOutputStream(adbToUsb);
fileOutputStream.write(sb.toString().getBytes());
toast("创建adbToUsb成功");
} catch (IOException e) {
e.printStackTrace();
}
}
private void toast(final String s) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
}
});
}
private void updateWifiView() {
runOnUiThread(new Runnable() {
@Override
public void run() {
tvAdbStatus.setText("adb状态:wifi模式");
}
});
}
private void updateUsbView() {
runOnUiThread(new Runnable() {
@Override
public void run() {
tvAdbStatus.setText("adb状态:usb模式");
}
});
}
}
| true |
85e145b1d05ce1e87b1e06c7188b72c9c1b5c7f5 | Java | zhangshilin9527/netty_study | /src/main/java/com/xiaolinzi/netty/study/unpacking/PackNettyServerHandler.java | UTF-8 | 852 | 2.53125 | 3 | [] | no_license | package com.xiaolinzi.netty.study.unpacking;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
/**
* @author xiaolinzi
* @Date 2021/3/30 17:22
* @email xiaolinzi95_27@163.com
*/
public class PackNettyServerHandler extends SimpleChannelInboundHandler<MyMessageProtocol> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, MyMessageProtocol msg) throws Exception {
System.out.println("====服务端接收到消息如下====");
System.out.println("长度=" + msg.getLen());
System.out.println("内容=" + new String(msg.getContent(), CharsetUtil.UTF_8));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
| true |
60ce2fbb251d9b6f31a78552081c7e2ed735b0e8 | Java | notafiscaltolegal/tolegal | /to-legal/src/main/java/gov/to/service/PessoaFisicaToLegalService.java | UTF-8 | 677 | 1.898438 | 2 | [] | no_license | package gov.to.service;
import java.util.List;
import javax.ejb.Local;
import gov.to.entidade.EnderecoToLegal;
import gov.to.entidade.PessoaFisicaToLegal;
import gov.to.filtro.FiltroPessoaFisicaToLegal;
/**
*
* @author pedro.oliveira
*
*
*/
@Local
public interface PessoaFisicaToLegalService {
/**
*
* @param filtro
* @param hibernateInitialize
* @return
*/
List<PessoaFisicaToLegal> pesquisar(FiltroPessoaFisicaToLegal filtro, String... propriedadesHbInitialize);
EnderecoToLegal enderecoPorCpf(String cpf);
PessoaFisicaToLegal primeiroRegistro(FiltroPessoaFisicaToLegal filtro, String string, String string2);
}
| true |
08249599cb95a2ae2872944547a55fd3045ed854 | Java | SeelabFhdo/lemma | /de.fhdo.lemma.model_processing.eclipse.launcher/xtend-gen/de/fhdo/lemma/model_processing/eclipse/launcher/processing_configurations/shortcut/java_base_generator/AbstractJavaBaseGeneratorTemplate.java | UTF-8 | 5,591 | 1.867188 | 2 | [
"MIT"
] | permissive | package de.fhdo.lemma.model_processing.eclipse.launcher.processing_configurations.shortcut.java_base_generator;
import com.google.common.collect.Iterables;
import de.fhdo.lemma.model_processing.eclipse.launcher.Utils;
import de.fhdo.lemma.model_processing.eclipse.launcher.processing_configurations.ProcessorExecutableType;
import de.fhdo.lemma.model_processing.eclipse.launcher.processing_configurations.arguments.Argument;
import de.fhdo.lemma.model_processing.eclipse.launcher.processing_configurations.shortcut.AbstractCodeGeneratorCompletionDialog;
import de.fhdo.lemma.model_processing.eclipse.launcher.processing_configurations.shortcut.AbstractCodeGeneratorTemplate;
import de.fhdo.lemma.model_processing.eclipse.launcher.processing_configurations.shortcut.ProcessingConfigurationWithLaunchConfigurationName;
import de.fhdo.lemma.service.Microservice;
import de.fhdo.lemma.service.ServiceModel;
import de.fhdo.lemma.service.TechnologyReference;
import de.fhdo.lemma.technology.mapping.MicroserviceMapping;
import de.fhdo.lemma.technology.mapping.TechnologyMapping;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.xtext.xbase.lib.CollectionLiterals;
import org.eclipse.xtext.xbase.lib.Functions.Function1;
import org.eclipse.xtext.xbase.lib.IterableExtensions;
import org.eclipse.xtext.xbase.lib.ListExtensions;
/**
* Abstract superclass for launch configuration templates targeting code generation with the Java
* Base Generator.
*
* @author <a href="mailto:florian.rademacher@fh-dortmund.de">Florian Rademacher</a>
*/
@SuppressWarnings("all")
public abstract class AbstractJavaBaseGeneratorTemplate extends AbstractCodeGeneratorTemplate {
private Argument generationSerializerArgument;
/**
* Constructor
*/
public AbstractJavaBaseGeneratorTemplate(final ProcessorExecutableType generatorExecutableType, final Shell parentShell, final String name, final IProject project, final IFile file) {
super(generatorExecutableType, parentShell, name, project, file);
}
/**
* Extend the model processing configuration template initialized by the superclass
*/
@Override
public ProcessingConfigurationWithLaunchConfigurationName extendInitializedProcessingConfigurationTemplate(final ProcessingConfigurationWithLaunchConfigurationName configuration) {
super.extendInitializedProcessingConfigurationTemplate(configuration);
this.generationSerializerArgument = Argument.newArgument().singleValued().stringPair().parameter(JavaBaseGeneratorParameters.GENERATION_SERIALIZER_PARAMETER).value(JavaBaseGeneratorParameters.instance().getDefaultGenerationSerializer());
configuration.getArguments().add(this.generationSerializerArgument);
return configuration;
}
/**
* Return the dialog for template completion
*/
@Override
public final AbstractCodeGeneratorCompletionDialog getCodeGeneratorCompletionDialog() {
final AbstractJavaBaseGeneratorCompletionDialog dialog = this.getJavaBaseGeneratorCompletionDialog();
dialog.setGenerationSerializerArgument(this.generationSerializerArgument);
return dialog;
}
/**
* Implementers must provide a specialized completion dialog. getCodeGeneratorCompletionDialog()
* invokes this method to retrieve the specialized dialog and assign it the argument for the
* selected code generation serializer.
*/
public abstract AbstractJavaBaseGeneratorCompletionDialog getJavaBaseGeneratorCompletionDialog();
/**
* The template is applicable when the source service or mapping model applies the Java
* technology to at least one microservice
*/
@Override
public Boolean isApplicable(final EObject modelRoot, final Map<String, String> technologyNamePerAlias) {
Iterable<TechnologyReference> _switchResult = null;
boolean _matched = false;
if (modelRoot instanceof ServiceModel) {
_matched=true;
final Function1<Microservice, EList<TechnologyReference>> _function = (Microservice it) -> {
return it.getTechnologyReferences();
};
_switchResult = Iterables.<TechnologyReference>concat(ListExtensions.<Microservice, EList<TechnologyReference>>map(((ServiceModel)modelRoot).getMicroservices(), _function));
}
if (!_matched) {
if (modelRoot instanceof TechnologyMapping) {
_matched=true;
final Function1<MicroserviceMapping, EList<TechnologyReference>> _function = (MicroserviceMapping it) -> {
return it.getTechnologyReferences();
};
_switchResult = Iterables.<TechnologyReference>concat(ListExtensions.<MicroserviceMapping, EList<TechnologyReference>>map(((TechnologyMapping)modelRoot).getServiceMappings(), _function));
}
}
if (!_matched) {
_switchResult = CollectionLiterals.<TechnologyReference>emptyList();
}
final Iterable<TechnologyReference> technologyReferences = _switchResult;
Utils.makeImportPathsAbsolute(modelRoot, this.file);
final Function1<TechnologyReference, Boolean> _function = (TechnologyReference it) -> {
boolean _xblockexpression = false;
{
final String alias = it.getTechnology().getName();
final String technologyName = technologyNamePerAlias.get(alias);
_xblockexpression = "java".equalsIgnoreCase(technologyName);
}
return Boolean.valueOf(_xblockexpression);
};
return Boolean.valueOf(IterableExtensions.<TechnologyReference>exists(technologyReferences, _function));
}
}
| true |
34e7da7e394d169ad0b97435f0717896adca746b | Java | robototes/InfiniteRecharge2020 | /src/main/java/frc/team2412/robot/RobotMapConstants.java | UTF-8 | 2,059 | 2.453125 | 2 | [] | no_license | package frc.team2412.robot;
public class RobotMapConstants {
public final static boolean CLIMB_CONNECTED = true;
public final static boolean CONTROL_PANEL_CONNECTED = false;
public final static boolean SHOOTER_CONNECTED = true;
public final static boolean INDEX_CONNECTED = true;
public final static boolean INTAKE_CONNECTED = true;
public final static boolean LIFT_CONNECTED = true;
public final static boolean DRIVE_BASE_CONNECTED = true;
public static enum CANBus {
INTAKE1(11), INDEX1(12), INTAKE2(21), INDEX2(22), INTAKE3(31), INDEX3(32), INDEX_LEFT_MID(40),
INDEX_RIGHT_MID(41), DRIVE_LEFT_FRONT(3), DRIVE_LEFT_BACK(4), DRIVE_RIGHT_FRONT(1), DRIVE_RIGHT_BACK(2),
CLIMB1(5), CLIMB2(6), TURRET(7), FLYWHEEL_LEFT(8), FLYWHEEL_RIGHT(9), CONTROL_PANEL(10);
public final int id;
private CANBus(int canBusId) {
id = canBusId;
}
}
public static enum PneumaticPort {
DRIVE(2), CLIMB_LEFT(4), CLIMB_RIGHT(5), INTAKE_FRONT_UP(7), INTAKE_BACK_UP(6), LIFT_UP(0), LIFT_DOWN(1);
public final int id;
private PneumaticPort(int pneumaticPortId) {
id = pneumaticPortId;
}
}
public static enum DIOPort {
FRONT_SENSOR(5), FRONT_MID_SENSOR(6), FRONT_INNER_SENSOR(7), BACK_INNER_SENSOR(3), BACK_MID_SENSOR(2),
BACK_SENSOR(1), INTAKE_BACK_SENSOR(0), INTAKE_FRONT_SENSOR(4);
public final int id;
private DIOPort(int dioPortId) {
id = dioPortId;
}
}
public static enum PWMPort {
HOOD_SERVO_1(0), HOOD_SERVO_2(1);
public final int id;
private PWMPort(int pwmPortId) {
id = pwmPortId;
}
}
// CHOICE FOR INDEX/INTAKE MODULE
public static enum IndexIntakeModule {
ONE(CANBus.INTAKE1.id, CANBus.INDEX1.id), TWO(CANBus.INTAKE2.id, CANBus.INDEX2.id),
THREE(CANBus.INTAKE3.id, CANBus.INDEX3.id);
private final int indexCANID;
private final int intakeCANID;
private IndexIntakeModule(int intakeID, int indexID) {
indexCANID = indexID;
intakeCANID = intakeID;
}
public int getIntakeCANID() {
return intakeCANID;
}
public int getIndexCANID() {
return indexCANID;
}
}
}
| true |
aa7194aff07db4cdc948066ad76bb4afb32439be | Java | LIUNANYAN/-Java- | /java_files/mo_kuai_hua/Test1.java | UTF-8 | 153 | 2.4375 | 2 | [] | no_license |
public class Test1 {
String name="sdk";
int age=21;
public void person(){
System.out.println(name+" "+age);
}
} | true |
ee55089782f40284881e579687a0ffd2c7fdf19d | Java | matuobasyouca/com.software5000.ma | /com.software5000.ma.server/src/main/java/com/software5000/base/mybatis/plugins/PermissionRule.java | UTF-8 | 2,888 | 2.140625 | 2 | [
"MIT"
] | permissive | package com.software5000.base.mybatis.plugins;
import com.software5000.base.Constant;
import com.software5000.base.entity.SystemCode;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Created by cc on 2016/12/24.<br>
* SystemCode.codeType == PermissionRule
*/
public class PermissionRule {
private static final Log log = LogFactory.getLog(PermissionRule.class);
/**
* codeName<br>
* 适用角色列表<br>
* 格式如: ,RoleA,RoleB,
*/
private String roles;
/**
* codeValue<br>
* 主实体,多表联合
* 格式如: ,SystemCode,User,
*/
private String fromEntity;
/**
* codeDesc<br>
* 过滤表达式字段, <br>
* <code>{uid}</code>会自动替换为当前用户的userId<br>
* <code>{me}</code> main entity 主实体名称
* <code>{me.a}</code> main entity alias 主实体别名
* 格式如:
* <ul>
* <li>userId = {uid}</li>
* <li>(userId = {uid} AND authType > 3)</li>
* <li>((userId = {uid} AND authType) > 3 OR (dept in (select dept from depts where manager.id = {uid})))</li>
* </ul>
*/
private String exps;
/**
* codeShowName<br>
* 规则说明
*/
private String ruleComment;
private static List<PermissionRule> allRule = null;
private static long refreshTime = 0L;
public static List getAllRules() {
if (Constant.refreshTime() > refreshTime) {
log.debug("尝试更新权限限制规则!");
allRule = new ArrayList<>();
refreshTime = Constant.refreshTime();
for (SystemCode c :
Constant.getAllCodes()) {
if ("PermissionRule".equals(c.getCodeType())) {
PermissionRule rule = new PermissionRule();
rule.setExps(c.getCodeDesc());
rule.setRoles(c.getCodeName());
rule.setFromEntity(c.getCodeValue());
rule.setRuleComment(c.getCodeShowName());
allRule.add(rule);
}
}
log.debug("更新权限限制规则完成!");
}
return allRule;
}
public String getRoles() {
return roles;
}
public void setRoles(String roles) {
this.roles = roles;
}
public String getRuleComment() {
return ruleComment;
}
public void setRuleComment(String ruleComment) {
this.ruleComment = ruleComment;
}
public String getFromEntity() {
return fromEntity;
}
public void setFromEntity(String fromEntity) {
this.fromEntity = fromEntity;
}
public String getExps() {
return exps;
}
public void setExps(String exps) {
this.exps = exps;
}
}
| true |
df1f6c44499d5734c9f0ba4ffa04567186bdf772 | Java | SimiaCryptus/java-reference-counter | /autocoder/src/main/java/com/simiacryptus/ref/core/ops/LoggingASTVisitor.java | UTF-8 | 4,716 | 1.789063 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (c) 2020 by Andrew Charneski.
*
* The author licenses this file to you under the
* Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance
* with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.simiacryptus.ref.core.ops;
import com.simiacryptus.ref.core.CollectableException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
public abstract class LoggingASTVisitor extends ASTVisitor {
protected static final Logger logger = LoggerFactory.getLogger(ASTOperator.class);
@Nonnull
protected final CompilationUnit compilationUnit;
protected final AST ast;
@Nonnull
protected final File file;
private final ArrayList<CollectableException> exceptions = new ArrayList<>();
private boolean failAtEnd = false;
public LoggingASTVisitor(@Nonnull CompilationUnit compilationUnit, @Nonnull File file) {
this.compilationUnit = compilationUnit;
this.ast = compilationUnit.getAST();
this.file = file;
}
public boolean isFailAtEnd() {
return failAtEnd;
}
public void setFailAtEnd(boolean failAtEnd) {
this.failAtEnd = failAtEnd;
}
public final void debug(@Nonnull ASTNode node, String formatString, Object... args) {
debug(1, node, formatString, args);
}
public final void warn(@Nonnull ASTNode node, @Nonnull String formatString, Object... args) {
warn(1, node, formatString, args);
}
public final void debug(int frames, @Nonnull ASTNode node, String formatString, Object... args) {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
final StackTraceElement caller = stackTrace[2 + frames];
logger.debug(String.format(getLogPrefix(node, caller) + formatString, args));
}
@SuppressWarnings("unused")
public final void info(@Nonnull ASTNode node, @Nonnull String formatString, Object... args) {
info(1, node, formatString, args);
}
public final void info(int frames, @Nonnull ASTNode node, @Nonnull String formatString, @Nonnull Object... args) {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
final StackTraceElement caller = stackTrace[2 + frames];
logger.info(String.format(getLogPrefix(node, caller) + formatString, Arrays.stream(args).map(o -> o == null ? null : o.toString().trim()).toArray()));
}
public final void warn(int frames, @Nonnull ASTNode node, @Nonnull String formatString, Object... args) {
warnRaw(frames + 1, node, String.format(formatString, args));
}
public final void fatal(@Nonnull ASTNode node, @Nonnull String formatString, Object... args) {
CollectableException collectableException = new CollectableException("(" + getLocation(node) + ") " + String.format(formatString, args));
if (isFailAtEnd()) {
warn(1, node, formatString, args);
exceptions.add(collectableException);
} else {
throw collectableException;
}
}
@Override
public void endVisit(CompilationUnit node) {
throwQueuedExceptions();
}
public void warnRaw(int frames, @Nonnull ASTNode node, String format) {
final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
final StackTraceElement caller = stackTrace[2 + frames];
logger.warn(getLogPrefix(node, caller) + format);
}
protected final void throwQueuedExceptions() {
if (!exceptions.isEmpty()) throw CollectableException.combine(exceptions);
}
@Nonnull
protected final String getLocation(@Nonnull ASTNode node) {
return file.getName() + ":" + compilationUnit.getLineNumber(node.getStartPosition());
}
@Nonnull
protected final String toString(@Nonnull StackTraceElement caller) {
return caller.getFileName() + ":" + caller.getLineNumber();
}
@Nonnull
private String getLogPrefix(@Nonnull ASTNode node, @Nonnull StackTraceElement caller) {
return "(" + toString(caller) + ") (" + getLocation(node) + ") - ";
}
}
| true |
81ae118b9acafdfeb89a86c08580a96775e57721 | Java | zkk950815/gateway | /gateway/src/main/java/com/cpic/myuul/filter/route/RoutingFilter.java | UTF-8 | 834 | 2.09375 | 2 | [] | no_license | package com.cpic.myuul.filter.route;
import com.cpic.myuul.filter.MyuulFilter;
import com.cpic.myuul.http.RequestContext;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class RoutingFilter implements MyuulFilter {
public String filterType() {
return "route";
}
public int filterOrder() {
return 0;
}
public void run() {
RequestContext context = RequestContext.getCurrentContext();
RequestEntity requestEntity = context.getRequestEntity();
RestTemplate template = new RestTemplate();
ResponseEntity<byte[]> responseEntity = template.exchange(requestEntity, byte[].class);
context.setResponseEntity(responseEntity);
}
}
| true |
afdbfa02ca9e2fcaeb9b6016c4130e072055308f | Java | bellmit/teach | /teach-service/src/main/java/com/wst/service/sys/service/AppAccessService.java | UTF-8 | 2,696 | 1.976563 | 2 | [] | no_license | /*
* AppAccessService.java Created on 2017年3月25日 下午2:24:27
* Copyright (c) 2017 HeWei Technology Co.Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.wst.service.sys.service;
import java.util.List;
import com.hiwi.common.dao.Page;
import com.wst.service.sys.dto.AppAccessDTO;
import com.wst.service.sys.dto.AppIpDTO;
/**
* 第三方应用接入Service
*
* @author <a href="mailto:liqg@hiwitech.com">liqiangen</a>
* @version 1.0
*/
public interface AppAccessService {
/**
* 根据appId获取接入信息
*
* @param appId
* @return
* @throws Exception
*/
public AppAccessDTO getByAppId(String appId) throws Exception;
/**
* 获取白名单IP列表
*
* @param accsId
* @return
* @throws Exception
*/
public List<AppIpDTO> findWhiteIpList(long accsId) throws Exception;
/* *//**
* 保存/更新第三方应用接入配置
*
* @param appAccessDTO
* @throws Exception
*/
/*
* public ResultDTO<String> saveorUpdate(AppAccessDTO appAccessDTO) throws
* Exception;
*
*//**
* 更新应用秘钥
*
* @param accsId
* @param opId
* @throws Exception
*/
/*
* public ResultDTO<String> upAppSecret(long accsId, long opId) throws
* Exception
*/;
/**
* 第三方应用接入配置信息分页查询
*
* @param pageParam
* @param appAccess
* @return
* @throws Exception
*/
public Page<AppAccessDTO> findPage(Page<AppAccessDTO> pageParam, AppAccessDTO appAccess) throws Exception;
/**
* 根据Id获取第三方应用接入配置信息(包括有效和禁用状态)
*
* @param accsId
* @return
* @throws Exception
*/
public AppAccessDTO getAllById(long accsId) throws Exception;
/**
* 根据appId获取第三方应用接入配置信息(包括有效和禁用状态)
*
* @param appId
* @return
* @throws Exception
*/
public AppAccessDTO getAllByAppId(String appId) throws Exception;
}
| true |
c8fe0a3d2aeb2557f89a19d63b23193b186bb63d | Java | MAXJOKER/keep-learning | /com.finn/src/main/java/leetcode/dynamicprogramming/HouseRobber3.java | UTF-8 | 2,684 | 3.96875 | 4 | [] | no_license | package leetcode.dynamicprogramming;
import leetcode.binarytree.TreeNode;
/**
* @author maxjoker
* @date 2022-05-30 23:50
*
* 337. 打家劫舍 III
* 小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为 root 。
*
* 除了 root 之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果 两个直接相连的房子在同一天晚上被打劫 ,房屋将自动报警。
*
* 给定二叉树的 root 。返回 在不触动警报的情况下 ,小偷能够盗取的最高金额 。
*
*
*
* 示例 1:
*
* https://assets.leetcode.com/uploads/2021/03/10/rob1-tree.jpg
*
*
* 输入: root = [3,2,3,null,3,null,1]
* 输出: 7
* 解释: 小偷一晚能够盗取的最高金额 3 + 3 + 1 = 7
* 示例 2:
*
* https://assets.leetcode.com/uploads/2021/03/10/rob2-tree.jpg
*
*
* 输入: root = [3,4,5,1,3,null,1]
* 输出: 9
* 解释: 小偷一晚能够盗取的最高金额 4 + 5 = 9
*
*
* 提示:
*
* 树的节点数在 [1, 10^4] 范围内
* 0 <= Node.val <= 10^4
*
*/
public class HouseRobber3 {
/**
* dp[node][j] :这里 node 表示一个结点,以 node 为根结点的树,并且规定了 node 是否偷取能够获得的最大价值。
* j = 0 表示 node 结点不偷取;
* j = 1 表示 node 结点偷取。
*
* 根据当前结点偷或者不偷,就决定了需要从哪些子结点里的对应的状态转移过来。
* 如果当前结点不偷,左右子结点偷或者不偷都行,选最大者;
* 如果当前结点偷,左右子结点均不能偷。
*
* @param root
* @return
*/
public static int rob(TreeNode root) {
int[] res = dfs(root);
return Math.max(res[0], res[1]);
}
private static int[] dfs(TreeNode node) {
if (node == null) {
return new int[]{0, 0};
}
// 分类讨论的标准是:当前结点偷或者不偷
// 由于需要后序遍历,所以先计算左右子结点,然后计算当前结点的状态值
int[] left = dfs(node.left);
int[] right = dfs(node.right);
int[] dp = new int[2];
// dp[0]:以当前 node 为根结点的子树能够偷取的最大价值,规定 node 结点不偷
dp[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
// dp[1]:以当前 node 为根结点的子树能够偷取的最大价值,规定 node 结点偷
dp[1] = node.val + left[0] + right[0];
return dp;
}
}
| true |
a93a25e64f5884a5bd7019f012f600ce2a347e13 | Java | 13110992819/cs-wellet | /src/main/java/com/cdkj/coin/wallet/ao/impl/EthAddressAOImpl.java | UTF-8 | 6,814 | 1.9375 | 2 | [] | no_license | /**
* @Title EthAddressAOImpl.java
* @Package com.cdkj.coin.ao.impl
* @Description
* @author leo(haiqing)
* @date 2017年10月27日 下午5:43:34
* @version V1.0
*/
package com.cdkj.coin.wallet.ao.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.web3j.crypto.WalletUtils;
import com.cdkj.coin.wallet.ao.IEthAddressAO;
import com.cdkj.coin.wallet.bo.IAccountBO;
import com.cdkj.coin.wallet.bo.ICollectionBO;
import com.cdkj.coin.wallet.bo.ICtqBO;
import com.cdkj.coin.wallet.bo.IEthAddressBO;
import com.cdkj.coin.wallet.bo.IEthTransactionBO;
import com.cdkj.coin.wallet.bo.ISYSConfigBO;
import com.cdkj.coin.wallet.bo.IWithdrawBO;
import com.cdkj.coin.wallet.bo.base.Paginable;
import com.cdkj.coin.wallet.enums.EAddressType;
import com.cdkj.coin.wallet.enums.EBoolean;
import com.cdkj.coin.wallet.enums.ESysUser;
import com.cdkj.coin.wallet.enums.ESystemAccount;
import com.cdkj.coin.wallet.enums.EWAddressStatus;
import com.cdkj.coin.wallet.enums.EYAddressStatus;
import com.cdkj.coin.wallet.ethereum.EthAddress;
import com.cdkj.coin.wallet.exception.BizException;
import com.cdkj.coin.wallet.exception.EBizErrorCode;
/**
* @author: haiqingzheng
* @since: 2017年10月27日 下午5:43:34
* @history:
*/
@Service
public class EthAddressAOImpl implements IEthAddressAO {
private static final Logger logger = LoggerFactory
.getLogger(EthAddressAOImpl.class);
@Autowired
private IEthAddressBO ethAddressBO;
@Autowired
private ICollectionBO collectionBO;
@Autowired
private IWithdrawBO withdrawBO;
@Autowired
private IEthTransactionBO ethTransactionBO;
@Autowired
private IAccountBO accountBO;
@Autowired
private ICtqBO ctqBO;
@Autowired
private ISYSConfigBO sysConfigBO;
@Override
public void addEthAddress(String address, String label, String userId,
String smsCaptcha, String isCerti, String tradePwd,
String googleCaptcha) {
// 地址有效性校验
if (!WalletUtils.isValidAddress(address)) {
throw new BizException(EBizErrorCode.DEFAULT.getCode(), "地址"
+ address + "不符合以太坊规则,请仔细核对");
}
List<String> typeList = new ArrayList<String>();
typeList.add(EAddressType.X.getCode());
typeList.add(EAddressType.M.getCode());
typeList.add(EAddressType.W.getCode());
EthAddress condition = new EthAddress();
condition.setAddress(address);
condition.setTypeList(typeList);
if (ethAddressBO.getTotalCount(condition) > 0) {
throw new BizException(EBizErrorCode.DEFAULT.getCode(),
"提现地址已经在本平台被使用,请仔细核对!");
}
String status = EYAddressStatus.NORMAL.getCode();
// 是否设置为认证账户
if (EBoolean.YES.getCode().equals(isCerti)) {
status = EYAddressStatus.CERTI.getCode();
}
ethAddressBO.saveEthAddress(EAddressType.Y, userId, address, label,
null, BigDecimal.ZERO, status, null, null);
}
@Override
public void abandonAddress(String code) {
EthAddress ethAddress = ethAddressBO.getEthAddress(code);
if (EWAddressStatus.INVALID.getCode().equals(ethAddress.getStatus())) {
throw new BizException(EBizErrorCode.DEFAULT.getCode(),
"地址已失效,无需重复弃用");
}
ethAddressBO.abandonAddress(ethAddress);
}
@Override
public EAddressType getType(String address) {
EAddressType type = EAddressType.Y;
EthAddress condition = new EthAddress();
condition.setAddress(address);
List<EthAddress> results = ethAddressBO.queryEthAddressList(condition);
if (CollectionUtils.isNotEmpty(results)) {
EthAddress ethAddress = results.get(0);
type = EAddressType.getAddressType(ethAddress.getType());
}
return type;
}
@Override
public String generateMAddress() {
String address = ethAddressBO.generateAddress(EAddressType.M,
ESysUser.SYS_USER.getCode(),
ESystemAccount.SYS_ACOUNT_ETH.getCode());
// 通知橙提取
ctqBO.uploadEthAddress(address, EAddressType.M.getCode());
return address;
}
@Override
public String importWAddress(String address) {
if (ethAddressBO.isEthAddressExist(address)) {
throw new BizException(EBizErrorCode.DEFAULT.getCode(), "地址"
+ address + "已经在平台内被使用,请仔细核对");
}
// 地址有效性校验
if (!WalletUtils.isValidAddress(address)) {
throw new BizException(EBizErrorCode.DEFAULT.getCode(), "地址"
+ address + "不符合以太坊规则,请仔细核对");
}
return ethAddressBO.saveEthAddress(EAddressType.W,
ESysUser.SYS_USER_COLD.getCode(),
ESystemAccount.SYS_ACOUNT_SC_COLD.getCode(), address, null,
BigDecimal.ZERO, EWAddressStatus.NORMAL.getCode(), null, null);
}
@Override
@Transactional
public Paginable<EthAddress> queryEthAddressPage(int start, int limit,
EthAddress condition) {
Paginable<EthAddress> results = ethAddressBO.getPaginable(start, limit,
condition);
for (EthAddress ethAddress : results.getList()) {
// 归集地址统计
if (EAddressType.W.getCode().equals(ethAddress.getType())) {
EthAddress xAddress = collectionBO.getAddressUseInfo(ethAddress
.getAddress());
ethAddress.setUseCount(xAddress.getUseCount());
ethAddress.setUseAmount(xAddress.getUseAmount());
}
// 散取地址统计
if (EAddressType.M.getCode().equals(ethAddress.getType())) {
EthAddress xAddress = withdrawBO.getAddressUseInfo(ethAddress
.getAddress());
ethAddress.setUseCount(xAddress.getUseCount());
ethAddress.setUseAmount(xAddress.getUseAmount());
}
}
return results;
}
@Override
public EthAddress getEthAddress(String code) {
return ethAddressBO.getEthAddress(code);
}
@Override
public BigDecimal getTotalBalance(EAddressType type) {
return ethAddressBO.getTotalBalance(type);
}
}
| true |
23531b13d19879323e573a86af95d21a6915ac78 | Java | yuchende/blog | /HibernateStruts/src/test/java/edu/xaut/test/TestCase.java | GB18030 | 929 | 2.21875 | 2 | [] | no_license | package edu.xaut.test;
import java.util.List;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import edu.xaut.bean.User;
import edu.xaut.dao.UserDaoImpl;
import edu.xaut.service.UserService;
import edu.xaut.service.UserServiceImpl;
public class TestCase {
public static void main(String[] args) {
}
//ѯ
@Test
public void test1() {
ClassPathXmlApplicationContext ca;
ca = new ClassPathXmlApplicationContext("conf/applicationContext.xml");
UserService us = ca.getBean("UserService",UserService.class);
List<User> list = us.findAll();
for(int i=0; i<list.size();i++) {
System.out.println(list.get(i));
}
}
//ģѯ
@Test
public void test2() {
/* UserDaoImpl ud = new UserDaoImpl();
List<User> list = ud.queryUser("s");
for(int i=0; i<list.size();i++) {
System.out.println(list.get(i));
}*/
}
}
| true |
ae391aa25695ffc59bac46180677821b55e209b5 | Java | dmitrykochanov/SportPredictions | /app/src/main/java/com/dmko/sportpredictions/injection/application/DataModule.java | UTF-8 | 1,410 | 2.203125 | 2 | [] | no_license | package com.dmko.sportpredictions.injection.application;
import com.dmko.sportpredictions.data.api.NewsApi;
import com.dmko.sportpredictions.data.NewsRepository;
import com.dmko.sportpredictions.data.NewsRepositoryImpl;
import com.dmko.sportpredictions.injection.scopes.ApplicationScope;
import com.dmko.sportpredictions.utils.SchedulersFacade;
import com.dmko.sportpredictions.utils.SchedulersFacadeImpl;
import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
@Module
public class DataModule {
@Provides
@ApplicationScope
public Retrofit provideRetrofit() {
return new Retrofit.Builder()
.baseUrl(NewsApi.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
}
@Provides
@ApplicationScope
public SchedulersFacade provideSchedulersFacade() {
return new SchedulersFacadeImpl();
}
@Provides
@ApplicationScope
public NewsApi provideNewsApi(Retrofit retrofit) {
return retrofit.create(NewsApi.class);
}
@Provides
@ApplicationScope
public NewsRepository provideNewsRepository(NewsApi newsApi) {
return new NewsRepositoryImpl(newsApi);
}
}
| true |
064fa479a0f205416212d18821c0813e91940fca | Java | todorgrigorov/post-box | /app/src/main/java/com/tgrigorov/postbox/services/data/UserService.java | UTF-8 | 2,540 | 2.265625 | 2 | [] | no_license | package com.tgrigorov.postbox.services.data;
import com.microsoft.aad.adal.AuthenticationResult;
import com.tgrigorov.postbox.PostBox;
import com.tgrigorov.postbox.data.entities.Person;
import com.tgrigorov.postbox.data.entities.User;
import com.tgrigorov.postbox.http.data.MailDetailModel;
import com.tgrigorov.postbox.utils.IPredicate;
import com.tgrigorov.postbox.utils.ListUtils;
import java.util.List;
public class UserService implements IUserService {
public User loadByAddress(final String address) {
List<User> users = PostBox.getDbContext().getContext(User.class).list();
List<User> filtered = ListUtils.filter(users, new IPredicate<User>() {
public boolean filter(User item) {
return item.getPerson().getAddress().equals(address);
}
});
return ListUtils.firstOrDefault(filtered);
}
public User loadCurrent() {
List<User> users = PostBox.getDbContext().getContext(User.class).list();
List<User> filtered = ListUtils.filter(users, new IPredicate<User>() {
public boolean filter(User item) {
return item.isCurrent();
}
});
return ListUtils.firstOrDefault(filtered);
}
public User create(AuthenticationResult result) {
String address = result.getUserInfo().getDisplayableId();
User user = loadByAddress(address);
if (user == null) {
MailDetailModel.PersonInfo info = new MailDetailModel().new PersonInfo();
info.name = result.getUserInfo().getGivenName() + " " + result.getUserInfo().getFamilyName();
info.address = address;
Person person = PostBox.getPersonService().create(info);
user = new User();
user.setPerson(person);
user.setToken(result.getAccessToken());
user.setRefreshToken(result.getRefreshToken());
user.setCurrent(true);
user.setExternalId(result.getIdToken());
user = PostBox.getDbContext().getContext(User.class).create(user);
} else {
user.setCurrent(true);
update(result, user);
}
return user;
}
public User update(AuthenticationResult result, User user) {
user.setToken(result.getAccessToken());
user.setRefreshToken(result.getRefreshToken());
user = PostBox.getDbContext().getContext(User.class).update(user);
return user;
}
} | true |
612fccee57402e1ae666f8e98ee3173ba1130b1b | Java | outsidereal/master-work | /src/main/java/com/diploma/classdiagram/model/relationships/Relationship.java | UTF-8 | 2,257 | 2.84375 | 3 | [] | no_license | package com.diploma.classdiagram.model.relationships;
import com.diploma.classdiagram.model.XMLElement;
/**
* User: ZIM
* Date: 25.08.12
* Time: 16:19
*/
public interface Relationship extends XMLElement {
/**
* This method should return identifier
* of source (also known as parent or supplier)
* element of relationships.
* <p/>
* For example, if class A generalizing class B
* method should return identifier of class B.
*
* @return - Source (also known as parent or supplier) identifier of relationship.
*/
public String getSource();
/**
* @param source - Set the source (also known as parent or supplier) of relationship
* @see #setSource(String) for detail information.
*/
public void setSource(String source);
/**
* This method should return identifier
* of destination (also known as child or client)
* element of relationship.
* <p/>
* For example, if class A generalizing class B
* method should return identifier of class A.
*
* @return - Destination (also known as child or client) identifier of relationship.
*/
public String getDestination();
/**
* @param destination - Set the destination (also known as child or client) identifier of relationship.
* @see #setDestination(String) for detail information.
*/
public void setDestination(String destination);
/**
* This method should return
* <b>true</b> if element is single in xml file and
* <b>false</b> if element if a part(child) of owner packaged element.
*/
public boolean isSingleElement();
/**
* @param isSingleElement - Set <b>true</b> if it is single and <b>false</b> if not.
* @see #isSingleElement() for detail information.
*/
public void setSingleElement(boolean isSingleElement);
/**
* Method should return relationship type
* witch is one of:
*
* @return - RelationshipImpl type.
* @see RelationshipType
*/
public RelationshipType getRelationshipType();
/**
* Method set the relationship type.
*
* @param type - RelationshipImpl type.
*/
public void setRelationshipType(RelationshipType type);
}
| true |
d8d0e1264052961aa2ab847f244192c26c47232c | Java | armen-zakaryan/POS_EJB_JBOSS | /Pos_ejb/ejb/src/com/aua/businesslogic/ArchiveRecord.java | UTF-8 | 664 | 2.59375 | 3 | [] | no_license | package com.aua.businesslogic;
import java.util.Date;
/**
* Created by Armen on 19-Oct-14.
*/
public class ArchiveRecord {
private String owner;
private Sale sale = null;
private Date date = null;
public ArchiveRecord(Sale sale){
this.owner = sale.getShopingCart().getOwner();
this.sale = sale;
this.date = new Date();
}
/**
*
* @return
*/
public String getOwner() {
return this.owner;
}
/**
*
* @return
*/
public Sale getSale() {
return sale;
}
/**
*
* @return
*/
public Date getDate() {
return date;
}
}
| true |
350bf87dc99825575d8690d21699c921bd99f908 | Java | burningcl/LeetcodeSolutions | /src/com/skyline/leetcode/solution/Q16.java | UTF-8 | 1,412 | 3.421875 | 3 | [] | no_license | package com.skyline.leetcode.solution;
import java.util.Arrays;
/**
* 3Sum Closest
*
* https://leetcode.com/problems/3sum-closest/
*
* @author jairus
*
*/
public class Q16 {
public int threeSumClosest(int[] nums, int target) {
int sum = 0;
if (nums == null || nums.length < 3) {
return sum;
}
Arrays.sort(nums);
int min = Integer.MAX_VALUE;
for (int i = 0; i < nums.length - 2; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
for (int j = i + 1; j < nums.length - 1; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
int l = target - nums[i] - nums[j];
int low = j + 1;
int high = nums.length - 1;
int mid = 0;
while (low <= high) {
mid = (low + high) / 2;
if (nums[mid] == l) {
return target;
} else if (nums[mid] < l) {
low = mid + 1;
} else {
high = mid - 1;
}
}
for (int k = mid - 1; k <= mid + 1; k++) {
if (k < 0 || k >= nums.length || k == i || k == j) {
continue;
}
int d = l - nums[k];
if (d < 0) {
d = -d;
}
if (d < min) {
min = d;
sum = nums[i] + nums[j] + nums[k];
}
}
}
}
return sum;
}
public static void main(String... strings) {
Q16 q = new Q16();
int[] nums = { 0, 1, 2 };
for (int i = 0; i < 20; i++) {
System.out.println(q.threeSumClosest(nums, i - 10));
}
}
}
| true |
0174af8fce398b8fb3be7e6a8f683c9c9b8149d8 | Java | qnhlli/RxAndroid-Retrofit | /MyRxAndroid2/app/src/main/java/com/example/qnhlli/myrxandroid2/GithubService.java | UTF-8 | 349 | 1.742188 | 2 | [] | no_license | package com.example.qnhlli.myrxandroid2;
import java.util.Map;
import retrofit.http.GET;
import retrofit.http.QueryMap;
import rx.Observable;
/**
* Created by qnhlli on 2016/6/12.
*/
public interface GithubService {
@GET("/search/repositories")
Observable<GithubResults> getTopNewAndroidRepos(@QueryMap Map<String, String> queryMap);
}
| true |
b6d2c05f3dd5af383e418172633ff06428530ddd | Java | nawsheenahmed18103377/Procurement-Management-System | /src/incognitocoders/ProductModel.java | UTF-8 | 885 | 2.421875 | 2 | [] | no_license | package incognitocoders;
public class ProductModel {
String pid, pname, pquantity, pprice;
public ProductModel(String pid, String pname, String pquantity, String pprice) {
this.pid = pid;
this.pname = pname;
this.pquantity = pquantity;
this.pprice = pprice;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public String getPquantity() {
return pquantity;
}
public void setPquantity(String pquantity) {
this.pquantity = pquantity;
}
public String getPprice() {
return pprice;
}
public void setPprice(String pprice) {
this.pprice = pprice;
}
}
| true |
d1489cd5a16b9b81c082683ec8dd10715835577e | Java | utsav0904/OnlineQuiz | /src/co/oep/quiz/controller/RegistrationController.java | UTF-8 | 3,103 | 2.484375 | 2 | [] | no_license | package co.oep.quiz.controller;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Collection;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import co.oep.quiz.DatabaseConnectionFactory;
/**
* Servlet implementation class RegistrationController
*/
@MultipartConfig
@WebServlet("/checkRegister")
public class RegistrationController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RegistrationController() {
super();
// TODO Auto-generated constructor stub
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Collection<Part> parts = request.getParts();
String resp = "/WEB-INF/jsps/regSuccess.jsp";
if (parts.size() != 3) {
//can write error page saying all details are not entered
}
Part filePart = request.getPart("photo");
InputStream imageInputStream = filePart.getInputStream();
//read imageInputStream
//filePart.write("somefiepath");
//can also write the photo to local storage
String username=request.getParameter("username");
String email=request.getParameter("email");
String password=request.getParameter("password");
String mobile=request.getParameter("mobile");
String city=request.getParameter("City");
Connection con=DatabaseConnectionFactory.createConnection();
try
{
PreparedStatement ps = con.prepareStatement("INSERT INTO users(username,password,email,mobile,address,photo) values(?,?,?,?,?,?)");
//String sql = "INSERT INTO users(username,password,email,mobile,address) values ('"+username+"','"+password+"','"+email+"','"+mobile+"','"+city+"')";
// System.out.println(sql);
ps.setString(1, username);
ps.setString(2, password);
ps.setString(3, email);
ps.setString(4, mobile);
ps.setString(5, city);
ps.setBinaryStream(6,imageInputStream,imageInputStream.available());
int i = ps.executeUpdate();
if(i!=0){
System.out.println("image inserted successfully");
}else{
System.out.println("problem in image insertion");
}
}catch(SQLException sqe){
resp = "/WEB-INF/jsps/register.jsp";
System.out.println("Error : While Inserting record in database");
request.setAttribute("err",sqe.getMessage());
}
try
{
con.close();
}catch(SQLException se){
System.out.println("Error : While Closing Connection");
}
request.setAttribute("newUser",username);
RequestDispatcher dispatcher=request.getRequestDispatcher(resp);
dispatcher.forward(request, response);
}
}
| true |
a8501d7f20169ac5cf2bb9777a17a8ba56fd8a44 | Java | JosueRJ/Ejercicio4_PDF2 | /src/ejercicio4/Fraccion.java | UTF-8 | 2,750 | 3.5625 | 4 | [] | no_license |
package ejercicio4;
public class Fraccion {
//atributos
private int numerador;
private int denominador;
//Constructores
//por defecto
public Fraccion(){
numerador = 0;
denominador = 1;
}
//con parametros
public Fraccion(int x, int y){
this.numerador = x;
if (y == 0){
y = 1;
}
this.denominador = y;
Simplificar();
}
//copia
public Fraccion(int numerador) {
this.numerador = numerador;
this.denominador = 1;
}
//Setter y Getters
public int getNumerador() {
return numerador;
}
public void setNumerador(int numerador) {
this.numerador = numerador;
}
public int getDenominador() {
return denominador;
}
public void setDenominador(int denominador) {
this.denominador = denominador;
}
//Metodos
public Fraccion SumarFraccion(Fraccion f){
Fraccion c = new Fraccion();
c.numerador = this.numerador * f.denominador + this.denominador * f.numerador;
c.denominador = this.denominador * f.denominador;
c.Simplificar();
return c;
}
public Fraccion RestarFraccion(Fraccion f) {
Fraccion c = new Fraccion();
c.numerador = this.numerador * f.denominador - this.denominador * f.numerador;
c.denominador = this.denominador * f.denominador;
c.Simplificar();
return c;
}
public Fraccion MultiplicarFraccion(Fraccion f) {
Fraccion c = new Fraccion();
c.numerador = this.numerador * f.numerador;
c.denominador = this.denominador * f.denominador;
c.Simplificar();
return c;
}
public Fraccion DividirFraccion(Fraccion f) {
Fraccion c = new Fraccion();
c.numerador = this.numerador * f.denominador;
c.denominador = this.denominador * f.numerador;
c.Simplificar();
return c;
}
//mcd
private int mcd() {
int u = Math.abs(numerador); //valor absoluto del numerador
int v = Math.abs(denominador); //valor absoluto del denominador
if (v == 0) {
return u;
}
int r;
while (v != 0) {
r = u % v;
u = v;
v = r;
}
return u;
}
private void Simplificar() {
int n = mcd();
numerador = numerador / n;
denominador = denominador / n;
}
//Medoto ToString
@Override
public String toString() {
Simplificar();
return numerador + "/" + denominador;
}
}
| true |
54e482e0682749ac78d206147babb7574aec7df8 | Java | angel-ramoscardona/pentaho-hadoop-shims | /common-fragment-V1/src/main/java/com/pentaho/big/data/bundles/impl/shim/hdfs/HadoopFileSystemFactoryImpl.java | UTF-8 | 4,160 | 1.789063 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*******************************************************************************
* Pentaho Big Data
* <p>
* Copyright (C) 2002-2020 by Hitachi Vantara : http://www.pentaho.com
* <p>
* ******************************************************************************
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
******************************************************************************/
package com.pentaho.big.data.bundles.impl.shim.hdfs;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalFileSystem;
import org.pentaho.hadoop.shim.api.internal.Configuration;
import org.pentaho.hadoop.shim.api.cluster.NamedCluster;
import org.pentaho.hadoop.shim.api.hdfs.HadoopFileSystem;
import org.pentaho.hadoop.shim.api.hdfs.HadoopFileSystemFactory;
import org.pentaho.hadoop.shim.spi.HadoopShim;
import org.pentaho.hadoop.shim.api.core.ShimIdentifierInterface;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
/**
* Created by bryan on 5/28/15.
*/
public class HadoopFileSystemFactoryImpl implements HadoopFileSystemFactory {
public static final String SHIM_IDENTIFIER = "shim.identifier";
public static final String HDFS = "hdfs";
protected static final Logger LOGGER = LoggerFactory.getLogger( HadoopFileSystemFactoryImpl.class );
protected final boolean isActiveConfiguration;
protected final HadoopShim hadoopShim;
protected final ShimIdentifierInterface shimIdentifier;
public HadoopFileSystemFactoryImpl( HadoopShim hadoopShim, ShimIdentifierInterface shimIdentifier ) {
this( true, hadoopShim, "hdfs", shimIdentifier );
}
public HadoopFileSystemFactoryImpl( boolean isActiveConfiguration, HadoopShim hadoopShim,
String scheme, ShimIdentifierInterface shimIdentifier ) {
this.isActiveConfiguration = isActiveConfiguration;
this.hadoopShim = hadoopShim;
this.shimIdentifier = shimIdentifier;
}
@Override public boolean canHandle( NamedCluster namedCluster ) {
String shimIdentifier = namedCluster.getShimIdentifier();
//handle only if we do not use gateway
return ( shimIdentifier == null && !namedCluster.isUseGateway() )
|| ( this.shimIdentifier.getId().equals( shimIdentifier ) && !namedCluster.isUseGateway() );
}
@Override
public HadoopFileSystem create( NamedCluster namedCluster ) throws IOException {
return create( namedCluster, null );
}
@Override
public HadoopFileSystem create( NamedCluster namedCluster, URI uri ) throws IOException {
final Configuration configuration = hadoopShim.createConfiguration( namedCluster );
FileSystem fileSystem = (FileSystem) hadoopShim.getFileSystem( configuration ).getDelegate();
if ( fileSystem instanceof LocalFileSystem ) {
LOGGER.error( "Got a local filesystem, was expecting an hdfs connection" );
throw new IOException( "Got a local filesystem, was expecting an hdfs connection" );
}
final URI finalUri = fileSystem.getUri() != null ? fileSystem.getUri() : uri;
HadoopFileSystem hadoopFileSystem = new HadoopFileSystemImpl( () -> {
try {
return finalUri != null
? (FileSystem) hadoopShim.getFileSystem( finalUri, configuration, (NamedCluster) namedCluster ).getDelegate()
: (FileSystem) hadoopShim.getFileSystem( configuration ).getDelegate();
} catch ( IOException | InterruptedException e ) {
LOGGER.debug( "Error looking up/creating the file system ", e );
return null;
}
} );
( (HadoopFileSystemImpl) hadoopFileSystem ).setNamedCluster( namedCluster );
return hadoopFileSystem;
}
}
| true |