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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
f2715f8bbb0b87608ea0687c65339c32eb15ca54 | Java | bear43/dbfiller | /src/main/java/com/hiber/Generator/LimitGenerator.java | UTF-8 | 690 | 2.578125 | 3 | [] | no_license | package com.hiber.Generator;
import com.hiber.DBClass.Limit;
import java.sql.Date;
public class LimitGenerator extends SkeletonGenerator
{
public static Limit generateLimit()
{
Date startDate = generator.generateDate();
int plusDays = generator.generateInt(360);
return new Limit(generator.generateLong(), startDate,
Date.valueOf(startDate.toLocalDate().plusDays(plusDays)));
}
public static Limit generateLimit(Date startDate)
{
int plusDays = generator.generateInt(360);
return new Limit(generator.generateLong(), startDate,
Date.valueOf(startDate.toLocalDate().plusDays(plusDays)));
}
}
| true |
f6612723ae9600bf225ec15b194254f1c2d41a71 | Java | MohammadTaher/Testgithub | /SeleniumProject/.svn/pristine/aa/aa9b17cd1b9d21c9694ec7278b49787fc668bb19.svn-base | UTF-8 | 1,613 | 2.765625 | 3 | [] | no_license | package jdbc.selenium.betech.nyc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertDataInMySql {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String Driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/betechdb";
String uName ="root";
String pwd = "password";
Connection conn=null;
try {
Class.forName(Driver).newInstance();
conn = DriverManager.getConnection(url, uName, pwd);
Statement st= conn.createStatement();
// String sql="insert into student values('Maksud Chowdhury','236598655','maksudchowdhury@gmail.com')";
String sql="update student set studentName = 'Jahangir Majumder', email='jmajumder@noakhali.com' where cellNumber = '1254358'";
st.executeUpdate(sql);
System.out.println("Data Inserted sucessfully");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} | true |
65f1db9c0a8a388cefc70d8f339b94a9c4b5f2fd | Java | MarKrol/LawFinancialAccouting | /src/main/java/pl/camp/it/model/employee/Employee.java | UTF-8 | 1,653 | 2.375 | 2 | [] | no_license | package pl.camp.it.model.employee;
import pl.camp.it.model.employee.EmployeeRole;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.time.LocalDate;
@Entity(name = "temployee")
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String surname;
private String role;
private boolean quantity;
private LocalDate localDateAddToDB;
public void setRole(String role) {
this.role = role;
}
private LocalDate localDateDeleteFromDB;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public boolean isQuantity() {
return quantity;
}
public void setQuantity(boolean quantity) {
this.quantity = quantity;
}
public LocalDate getLocalDateAddToDB() {
return localDateAddToDB;
}
public void setLocalDateAddToDB(LocalDate localDateAddToDB) {
this.localDateAddToDB = localDateAddToDB;
}
public LocalDate getLocalDateDeleteFromDB() {
return localDateDeleteFromDB;
}
public void setLocalDateDeleteFromDB(LocalDate localDateDeleteFromDB) {
this.localDateDeleteFromDB = localDateDeleteFromDB;
}
}
| true |
c7a3c7bbd4c0cee170f42c9d4f33220956279676 | Java | Newdream-College2019/nd-Java001 | /贺梦馨/第七章/Test01.java | GB18030 | 394 | 3.359375 | 3 | [] | no_license | import java.util.Scanner;
public class Test01{
public static void main(String[] args){
int sum=1;
System.out.print("һ");
Scanner in=new Scanner(System.in);
int num=in.nextInt();
if(1<=num&&num<10){
for(int i=1;i<=num;i++){
sum=sum*i;
}
System.out.print(num+"Ľ׳Ϊ"+sum);
}else{
System.out.print("룡");
}
}
} | true |
dcd9e461e3d99b1afb81b59a0d593e3cd0327f5c | Java | yorichpoka/JavaEE-TP-Students | /Students/src/java/Model/BO/Utilisateur.java | UTF-8 | 1,831 | 2.5625 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Model.BO;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.codehaus.jackson.map.ObjectMapper;
/**
*
* @author POKA
*/
public class Utilisateur extends BO implements Serializable {
public String mot_de_passe;
public Utilisateur() {
}
public Utilisateur(String compte, String nom_utilisateur, String mot_de_passe) {
this.setCode(compte);
this.setLibelle(nom_utilisateur);
this.mot_de_passe = mot_de_passe;
}
public String getMot_de_passe() {
return mot_de_passe;
}
public void setMot_de_passe(String motdepasse) {
this.mot_de_passe = motdepasse;
}
// @Override
// public void creerId() {
// long id = 0;
// for(Utilisateur val : Program.db.utilisateurs)
// {
// id = (id < val.getId()) ? val.getId()
// : id;
// }
// this.setId(id);
// }
@Override
public boolean equals(Object obj) {
return
((Utilisateur)obj).getId() == this.getId();
}
public String toJSONString(Utilisateur obj) {
try {
return
new ObjectMapper().writeValueAsString(obj);
} catch (IOException ex) {
Logger.getLogger(Utilisateur.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
@Override
public String toString() {
return "Utilisateur {" + "mot_de_passe=" + mot_de_passe + ", " + super.toString() + "}";
}
}
| true |
77ea7c9500a3d0db59c6e8255587c9858982940a | Java | PubliProyect/Publici | /Bussines/src/test/java/com/vimso/padyu/integracion/aprovisionamiento/contextoxCDI/WebAppContext.java | UTF-8 | 2,063 | 2.03125 | 2 | [] | no_license | package com.vimso.padyu.integracion.aprovisionamiento.contextoxCDI;
import com.vimso.padyu.config.*;
import com.mangofactory.swagger.plugin.EnableSwagger;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
@EnableSwagger
@EnableJpaRepositories(basePackages={"com.vimso.padyu.bussines.dao.repositorios"})
@ComponentScan(basePackages = {"com.vimso.padyu.web.webservice.rest.services.*","com.vimso.padyu.bussines.*","com.vimso.padyu.utils.traductor"})
public class WebAppContext extends WebMvcConfigurerAdapter{
private static final String MESSAGE_SOURCE_BASE_NAME = "i18n/messageSource";
//
// @Inject
// private SpringSwaggerConfig springSwaggerConfig;
// @Bean
// public SwaggerSpringMvcPlugin customImplementation() {
// return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
// .apiInfo(apiInfo());
// }
// private ApiInfo apiInfo() {
// ApiInfo apiInfo = new ApiInfo(
// "My Apps API Title",
// "My Apps API Description",
// "My Apps API terms of service",
// "My Apps API Contact Email",
// "My Apps API Licence Type",
// "My Apps API License URL"
// );
// return apiInfo;
// }
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename(MESSAGE_SOURCE_BASE_NAME);
messageSource.setUseCodeAsDefaultMessage(true);
return messageSource;
}
}
| true |
3005076341bf730f04e87d37f6a8ba4fe39da2b7 | Java | DragonsLover/enhanced-portals | /src/main/java/enhancedportals/client/gui/GuiRedstoneInterface.java | UTF-8 | 3,181 | 2.171875 | 2 | [] | no_license | package enhancedportals.client.gui;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.nbt.NBTTagCompound;
import enhancedportals.EnhancedPortals;
import enhancedportals.inventory.ContainerRedstoneInterface;
import enhancedportals.network.packet.PacketGuiData;
import enhancedportals.tile.TileRedstoneInterface;
public class GuiRedstoneInterface extends BaseGui
{
public static final int CONTAINER_SIZE = 68;
TileRedstoneInterface redstone;
public GuiRedstoneInterface(TileRedstoneInterface ri, EntityPlayer p)
{
super(new ContainerRedstoneInterface(ri, p.inventory), CONTAINER_SIZE);
name = "gui.redstoneInterface";
redstone = ri;
setHidePlayerInventory();
}
@Override
public void initGui()
{
super.initGui();
buttonList.add(new GuiButton(0, guiLeft + 8, guiTop + 18, xSize - 16, 20, ""));
buttonList.add(new GuiButton(1, guiLeft + 8, guiTop + 40, xSize - 16, 20, ""));
}
@Override
protected void actionPerformed(GuiButton button)
{
NBTTagCompound tag = new NBTTagCompound();
tag.setInteger("id", button.id);
EnhancedPortals.packetPipeline.sendToServer(new PacketGuiData(tag));
}
@Override
public void updateScreen()
{
super.updateScreen();
String stateText = "";
boolean flag = redstone.isOutput;
switch (redstone.state)
{
case 0:
stateText = flag ? EnhancedPortals.localize("gui.portalCreated") : EnhancedPortals.localize("gui.createPortalOnSignal");
break;
case 1:
stateText = flag ? EnhancedPortals.localize("gui.portalRemoved") : EnhancedPortals.localize("gui.removePortalOnSignal");
break;
case 2:
stateText = flag ? EnhancedPortals.localize("gui.portalActive") : EnhancedPortals.localize("gui.createPortalOnPulse");
break;
case 3:
stateText = flag ? EnhancedPortals.localize("gui.portalInactive") : EnhancedPortals.localize("gui.removePortalOnPulse");
break;
case 4:
stateText = flag ? EnhancedPortals.localize("gui.entityTeleport") : EnhancedPortals.localize("gui.dialStoredIdentifier");
break;
case 5:
stateText = flag ? EnhancedPortals.localize("gui.playerTeleport") : EnhancedPortals.localize("gui.dialStoredIdentifier2");
break;
case 6:
stateText = flag ? EnhancedPortals.localize("gui.animalTeleport") : EnhancedPortals.localize("gui.dialRandomIdentifier");
break;
case 7:
stateText = flag ? EnhancedPortals.localize("gui.monsterTeleport") : EnhancedPortals.localize("gui.dialRandomIdentifier2");
break;
}
((GuiButton) buttonList.get(0)).displayString = redstone.isOutput ? EnhancedPortals.localize("gui.output") : EnhancedPortals.localize("gui.input");
((GuiButton) buttonList.get(1)).displayString = stateText;
}
}
| true |
a44acf12981a01da5f96e1c745257216ef462c4c | Java | FengliLin/HTF-Missions-Management-System | /Product/app/src/main/java/htf/htfmms/Account/RegisterActivity.java | UTF-8 | 4,958 | 2.28125 | 2 | [] | no_license | package htf.htfmms.Account;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import htf.htfmms.R;
import htf.htfmms.Database.UserManger;
public class RegisterActivity extends AppCompatActivity {
EditText editTextUsername;
EditText editTextKey;
EditText certainKey;
Button bRegister;
//先采用sharedPreference方法存储数据
SharedPreferences preferences;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
editTextUsername = (EditText)findViewById(R.id.editTextUsername);
editTextKey = (EditText)findViewById(R.id.editTextKey);
certainKey = (EditText)findViewById(R.id.certainKey);
bRegister = (Button)findViewById(R.id.btnRegister);
//获取preferce实例
// preferences = getSharedPreferences("account",MODE_PRIVATE);
// editor = preferences.edit();
//监听按钮
bRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String userName = editTextUsername.getText().toString();
String key = editTextKey.getText().toString();
String cKey = certainKey.getText().toString();
//检查合法性
if (userName == "") {
Toast.makeText(RegisterActivity.this, "请输入用户名!", Toast.LENGTH_SHORT).show();
editTextUsername.setText("");
return;
}
String regex = "^[a-z0-9A-Z]+$";
if (!userName.matches(regex)) {
Toast.makeText(RegisterActivity.this, "用户名必须由字母数字组成!", Toast.LENGTH_SHORT).show();
editTextUsername.setText("");
return;
}
if (userName.length()>10) {
Toast.makeText(RegisterActivity.this, "最多十位!", Toast.LENGTH_SHORT).show();
editTextUsername.setText("");
return;
}
// String existOrnot = preferences.getString(userName,"");
// if (existOrnot != "") {
// Toast.makeText(RegisterActivity.this, "已被使用!", Toast.LENGTH_SHORT).show();
// editTextUsername.setText("");
// return;
// }
UserManger.checkUser(RegisterActivity.this,userName);
if (key == "") {
Toast.makeText(RegisterActivity.this, "请输入密码!", Toast.LENGTH_SHORT).show();
return;
}
if (!key.matches(regex)) {
Toast.makeText(RegisterActivity.this, "密码必须由字母数字组成!",
Toast.LENGTH_SHORT).show();
editTextKey.setText("");
return;
}
if (key.length()>10) {
Toast.makeText(RegisterActivity.this, "最多十位!", Toast.LENGTH_SHORT).show();
editTextKey.setText("");
return;
}
if (cKey==""){
Toast.makeText(RegisterActivity.this, "请再次输入密码!", Toast.LENGTH_SHORT).show();
return;
}
if (!cKey.equals(key)){
Toast.makeText(RegisterActivity.this, "两次密码输入不匹配!", Toast.LENGTH_SHORT).show();
return;
}
UserManger.signIn(RegisterActivity.this,userName,key);
//存储
// editor.putString(userName,key);
// editor.commit();
//显示成功对话框
// builder = new AlertDialog.Builder(RegisterActivity.this);
// alert = builder.setTitle("提示")
// .setMessage("注册成功!")
// .setPositiveButton("确定", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialog, int which) {
// Intent return2login = new Intent(RegisterActivity.this,AccountActivity.class);
// startActivity(return2login);
// }
// })
// .create();
// alert.show();
}
});
}
}
| true |
81ce0547ca414ccfb6eb863c579d008756d602a7 | Java | ontop/ontop | /db/rdb/src/main/java/it/unibz/inf/ontop/model/term/functionsymbol/db/impl/MySQLEncodeURLorIRIFunctionSymbolImpl.java | UTF-8 | 759 | 2.109375 | 2 | [
"CC-BY-4.0",
"Apache-2.0"
] | permissive | package it.unibz.inf.ontop.model.term.functionsymbol.db.impl;
import com.google.common.collect.ImmutableMap;
import it.unibz.inf.ontop.model.type.DBTermType;
import it.unibz.inf.ontop.utils.StringUtils;
public class MySQLEncodeURLorIRIFunctionSymbolImpl extends DefaultSQLEncodeURLorIRIFunctionSymbol {
protected MySQLEncodeURLorIRIFunctionSymbolImpl(DBTermType dbStringType, boolean preserveInternationalChars) {
super(dbStringType, preserveInternationalChars);
}
private static final ImmutableMap<Character, String> BACKSLASH = ImmutableMap.of('\\', "\\\\");
@Override
protected String encodeSQLStringConstant(String constant) {
return super.encodeSQLStringConstant(StringUtils.encode(constant, BACKSLASH));
}
}
| true |
73cba4b310ec7d3cca0dd262ad16bb54dbdd9fde | Java | Jing-J-Lee/HBCTradeLtd | /app/src/main/java/com/example/xps/hbctradeltd/v/folder/ContractAdapterFolder.java | UTF-8 | 2,600 | 2.328125 | 2 | [] | no_license | package com.example.xps.hbctradeltd.v.folder;
import android.content.Context;
import android.graphics.Outline;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewOutlineProvider;
import android.widget.TextView;
import com.example.xps.hbctradeltd.R;
import com.zhy.autolayout.AutoLinearLayout;
import java.util.List;
public class ContractAdapterFolder extends RecyclerView.Adapter<ContractAdapterFolder.MyViewHolder> {
private List<String> mDatas;
private Context mContext;
private LayoutInflater inflater;
private ViewOutlineProvider mOutlineProviderCircle;
int mElevation = 5;
int margin = 20;
public ContractAdapterFolder(Context context, List<String> datas) {
this.mContext = context;
this.mDatas = datas;
inflater = LayoutInflater.from(mContext);
mOutlineProviderCircle = new CircleOutlineProvider();
}
public void adddata(List<String> data) {
mDatas.addAll(data);
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return mDatas.size();
}
//重写onCreateViewHolder方法,返回一个自定义的ViewHolder
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.re_item, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
//填充onCreateViewHolder方法返回的holder中的控件
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.tv.setText(mDatas.get(position));
holder.item_ll.setOutlineProvider(mOutlineProviderCircle);
holder.item_ll.setClipToOutline(true);
holder.item_ll.setElevation(mElevation);
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView tv;
AutoLinearLayout item_ll;
public MyViewHolder(View view) {
super(view);
tv = (TextView) view.findViewById(R.id.tv_item);
item_ll = (AutoLinearLayout) view.findViewById(R.id.item_ll);
}
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private class CircleOutlineProvider extends ViewOutlineProvider {
@Override
public void getOutline(View view, Outline outline) {
outline.setRoundRect(margin, margin, view.getWidth() - margin, view.getHeight(), 15);
}
}
}
| true |
147a5483e9bec01d882746e267f7f1b6eb3efd98 | Java | divyaagarwal24/coderspree | /AR-VR/arshivaastha_Astha_2024cse1096_2/Patterns/Pattern3.java | UTF-8 | 374 | 2.890625 | 3 | [] | no_license | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int n=scn.nextInt();
int p=0;
for(int i =n; i>=0;i--)
{
for(int j =0;j<i;j++)
System.out.print(" \t");
p++;
for(int k=0;k<p;k++)
System.out.print("*\t");
System.out.println();
}
// write ur code here
}
} | true |
bf5443fb80716fb9d74b75e27c401f32d13eb0e9 | Java | alldatacenter/alldata | /studio/micro-services/CloudEon/cloudeon-server/src/main/java/org/dromara/cloudeon/processor/DeleteServiceDataDirTask.java | UTF-8 | 1,568 | 2.140625 | 2 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | package org.dromara.cloudeon.processor;
import cn.hutool.extra.spring.SpringUtil;
import org.dromara.cloudeon.dao.ClusterNodeRepository;
import org.dromara.cloudeon.entity.ClusterNodeEntity;
import org.dromara.cloudeon.service.SshPoolService;
import org.dromara.cloudeon.utils.SshUtils;
import lombok.NoArgsConstructor;
import org.apache.sshd.client.session.ClientSession;
import java.io.IOException;
@NoArgsConstructor
public class DeleteServiceDataDirTask extends BaseCloudeonTask {
@Override
public void internalExecute() {
ClusterNodeRepository clusterNodeRepository = SpringUtil.getBean(ClusterNodeRepository.class);
String serviceInstanceName = taskParam.getServiceInstanceName();
ClusterNodeEntity nodeEntity = clusterNodeRepository.findByHostname(taskParam.getHostName());
SshPoolService sshPoolService = SpringUtil.getBean(SshPoolService.class);
try {
ClientSession clientSession = sshPoolService.openSession(nodeEntity.getIp(), nodeEntity.getSshPort(), nodeEntity.getSshUser(), nodeEntity.getSshPassword());
String remoteDataDirPath = "/opt/edp/" + serviceInstanceName;
String command = "rm -rf " + remoteDataDirPath;
log.info("执行远程命令:" + command);
SshUtils.execCmdWithResult(clientSession, command);
sshPoolService.returnSession(clientSession,nodeEntity.getIp());
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("打开sftp失败:" + e);
}
}
}
| true |
1f43ee0663de8cbfd418675ad73782edd290939e | Java | mustaghfirinaru/Java-Fundamental | /07. Exception Handle dan Assertion/TestStudent.java | UTF-8 | 374 | 2.625 | 3 | [] | no_license | /**
* @author Moh Mustaghfirin A11201811347
* @version 1.0
*/
class TestStudent {
public static void main(String[] args) {
Student S=new Student(2,"Wijan5arto",21,"PBO");
System.out.println("RollNo "+S.rollNo);
System.out.println("Nama "+S.Nama);
System.out.println("Usia "+S.Usia);
System.out.println("MataKuliah "+S.MataKuliah);
}
} | true |
73f1846e8c797559a06e5261aa6868290cbdf3f8 | Java | bhupendrarautela7/prozo_assignment_web | /src/test/java/common/TestBase.java | UTF-8 | 11,553 | 1.929688 | 2 | [] | no_license | package common;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import junit.framework.Assert;
public class TestBase {
public static WebDriver dvr;
public static Properties propConfig, propObjctRepo;
public static Logger log;
private static final String APPLICATION_NAME = "Caroobi Automation Data Sheet";
/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"),
".credentials/sheets.googleapis.com-java-quickstart");
/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;
/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;
@SuppressWarnings("deprecation")
public void initBrowser(String browser) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println("==============================================" );
System.out.println("Test started at : "+ dtf.format(now));
System.out.println("==============================================" );
String OS = TestBase.OSDetector();
if (browser.equalsIgnoreCase("chrome") && OS == "Linux") {
System.out.println("OS Detected : Linux , Browser Launched : Chrome" );
System.setProperty("webdriver.chrome.driver", "/usr/bin/chromedriver");
ChromeOptions options = new ChromeOptions();
/*options.addArguments("start-maximized"); // open Browser in maximized mode
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-gpu"); // applicable to windows os only
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems */
//options.addArguments("--no-sandbox"); // Bypass OS security model
options.addArguments("--headless");
dvr = new ChromeDriver(options);
dvr.manage().window().fullscreen();
//dvr = new ChromeDriver();
}
else if (browser.equalsIgnoreCase("chrome") && OS == "Mac") {
System.out.println("==============================================" );
System.out.println("OS Detected : MAC , Browser Launched : Chrome" );
System.out.println("==============================================" );
System.setProperty("webdriver.chrome.driver", "./lib/chromedriver");
Boolean headlesschrome = false;
if (headlesschrome==true) {
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--headless");
chromeOptions.addArguments("--start-maximized");
chromeOptions.addArguments("--window-size=1200,800");
chromeOptions.addArguments("--disable-user-media-security=true");
dvr = new ChromeDriver(chromeOptions);
//dvr.manage().window().fullscreen();
}else if (headlesschrome==false)
{
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addArguments("--disable-user-media-security=true");
dvr = new ChromeDriver(chromeOptions);
dvr.manage().window().fullscreen();
}
}
else if (browser.equalsIgnoreCase("firefox") && OS == "Windows") {
System.out.println("OS Detected : Windows , Browser Launched : Firefox" );
System.setProperty("webdriver.gecko.driver", "./lib/geckodriver.exe");
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(true);
profile.setAssumeUntrustedCertificateIssuer(false);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(FirefoxDriver.PROFILE, profile);
capabilities.setCapability("marionette", true);
dvr = new FirefoxDriver(capabilities);
} else {
throw new IllegalArgumentException("Error with launching browser driver.....");
}
// dvr.manage().window().maximize();
dvr.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
public static String OSDetector() {
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")) {
return "Windows";
} else if (os.contains("nux") || os.contains("nix")) {
return "Linux";
} else if (os.contains("mac")) {
return "Mac";
} else if (os.contains("sunos")) {
return "Solaris";
} else {
return "Other";
}
}
public void loadPropertiesFile() throws FileNotFoundException, IOException {
propConfig = new Properties();
propConfig.load(new FileInputStream("./object_repo/config.properties"));
propObjctRepo = new Properties();
propObjctRepo.load(new FileInputStream("./object_repo/objects.properties"));
}
/**
* @throws InterruptedException
*/
public int randomNumber()
{
Random rand = new Random();
int rand_int = rand.nextInt(100000);
//System.out.println("Random Integers: "+rand_int);
return rand_int;
}
public void openURL(String url) {
dvr.get(url);
System.out.println("Opening : " + url);
}
public void deleteCookies() {
dvr.manage().deleteAllCookies();
}
public void quitInstance() {
dvr.quit();
System.out.println("Closed instance");
}
protected void addlogs(String Message) throws IOException {
log.info(Message);
}
protected void addErrorlogs(Exception e, String errormsg) throws IOException {
log.info(errormsg);
}
public void mouseHover(By by) {
Actions act = new Actions(dvr);
act.moveToElement(dvr.findElement(by)).build().perform();
}
public void explicit_wait(By by, long time) {
WebDriverWait wd = new WebDriverWait(dvr, time);
// wd.until(ExpectedElementConditions.isVisible())
wd.until(ExpectedConditions.visibilityOfElementLocated(by));
}
public void explicit_wait_presence(By by, long time) {
WebDriverWait wd = new WebDriverWait(dvr, time);
// wd.until(ExpectedElementConditions.isVisible())
wd.until(ExpectedConditions.presenceOfElementLocated(by));
}
public void explicit_wait_click(By by, long time) {
WebDriverWait wd = new WebDriverWait(dvr, time);
wd.until(ExpectedConditions.elementToBeClickable(by));
}
public void scrolltoTop() {
((JavascriptExecutor) dvr).executeScript("window.scroll(0,0);");
}
public void handleAlert() {
// System.out.println("Test inside alert");
WebDriverWait wait = new WebDriverWait(dvr, 5);
wait.until(ExpectedConditions.alertIsPresent());
System.out.println("Test inside alert");
Alert alert = dvr.switchTo().alert();
alert.accept();
}
public void type(By element, String value) {
Assert.assertTrue(dvr.findElements(element).size()>0);
dvr.findElement(element).sendKeys(value);
}
public void enter(By element) {
dvr.findElement(element).sendKeys(Keys.ENTER);
}
public void clickjs(By element) {
((JavascriptExecutor) dvr).executeScript("arguments[0].click();", element);
}
public void typejs(By element, String value) {
((JavascriptExecutor) dvr).executeScript("arguments[0].value='" + value + "';", dvr.findElement(element));
}
public void clear(By element) {
dvr.findElement(element).clear();
Assert.assertTrue(dvr.findElements(element).size()>0);
}
public String getCurrentUrl() {
String currenturl= dvr.getCurrentUrl();
return currenturl;
}
public void refreshpage() {
dvr.navigate().refresh();
}
public String getText(By element) {
String text=(new WebDriverWait(dvr, 20).until(ExpectedConditions.visibilityOfElementLocated(element)).getAttribute("innerHTML"));
return text;
}
private boolean Assert(String string, boolean b) {
// TODO Auto-generated method stub
return false;
}
public void click(By element) {
Assert.assertTrue(dvr.findElements(element).size()>0);
dvr.findElement(element).click();
}
public void selectValueDropdown(By element, String text) {
Select sel = new Select(dvr.findElement(element));
sel.selectByVisibleText(text);
}
public void verifyElement(By element) throws Exception {
try {
Assert.assertTrue(dvr.findElement(element).isDisplayed());
addlogs("Element " + element + " found on page");
System.out.println("Element " + element + " found on page");
} catch (AssertionError e) {
System.out.println("Element " + element + " not found on page");
throw new Exception("element " + element + " not found on page");
} catch (Exception e) {
System.out.println("Element " + element + " not found on page");
throw new Exception("element " + element + " not found on page");
}
}
public boolean isElementDisplayed(By element) throws Exception {
try {
Assert.assertTrue(dvr.findElement(element).isDisplayed());
addlogs("Element " + element + " found on page");
System.out.println("Element " + element + " found on page");
return true;
} catch (AssertionError e) {
System.out.println("Element " + element + " not found on page");
return false;
} catch (Exception e) {
System.out.println("Element " + element + " not found on page");
return false;
}
}
public void verifyElementPresence(By element) throws Exception {
try {
Assert.assertTrue(dvr.findElement(element).isEnabled());
addlogs("Element " + element + " found on page");
System.out.println("Element " + element + " found on page");
} catch (AssertionError e) {
System.out.println("Element " + element + " not found on page");
throw new Exception("element " + element + " not found on page");
} catch (Exception e) {
System.out.println("Element " + element + " not found on page");
throw new Exception("element " + element + " not found on page");
}
}
public String getAttribute(By element, String attribute) {
try {
String attributeval = dvr.findElement(element).getAttribute(attribute);
return attributeval;
} catch (Exception e) {
e.printStackTrace();
Assert.fail();
return null;
}
}
protected void scrolltoElement(By element) {
((JavascriptExecutor) dvr).executeScript("arguments[0].scrollIntoView();", dvr.findElement(element));
}
protected List<WebElement> getMultipleWebElement(By element) {
List<WebElement> elements = dvr.findElements(element);
return elements;
}
protected void escape() {
Actions action = new Actions(dvr);
action.sendKeys(Keys.ESCAPE).perform();
}
}
| true |
563a828f395aebf3a66ec40316390d4274876f47 | Java | thewisebro/New-Entrants | /MyApplication/app/src/main/java/models/SeniorModel.java | UTF-8 | 339 | 1.546875 | 2 | [] | no_license | package models;
/**
* Created by ankush on 11/1/15.
*/
public class SeniorModel {
public String name;
public String town;
public String state;
public String contact;
public String email;
public String fblink;
public String branch;
public String dp_link;
public int year;
public boolean toggle;
}
| true |
39f11a181b56828ee1509954077751dd1156486f | Java | skosko00/seongmin | /KH-WEB-Project-v2-master/src/jsp/member/model/vo/QuestionVo.java | UTF-8 | 1,781 | 2.359375 | 2 | [] | no_license | package jsp.member.model.vo;
import java.sql.Timestamp;
public class QuestionVo {
private int qNo;
private String qName, qContents, qWriter, qAnswerCheck;
private Timestamp qWriteDate, qAnswerDate;
public QuestionVo() {
}
public QuestionVo(int qNo, String qName, String qContents, String qWriter, String qAnswerCheck,
Timestamp qWriteDate, Timestamp qAnswerDate) {
super();
this.qNo = qNo;
this.qName = qName;
this.qContents = qContents;
this.qWriter = qWriter;
this.qAnswerCheck = qAnswerCheck;
this.qWriteDate = qWriteDate;
this.qAnswerDate = qAnswerDate;
}
@Override
public String toString() {
return "QuestionVo [qNo=" + qNo + ", qName=" + qName + ", qContents=" + qContents + ", qWriter=" + qWriter
+ ", qAnswerCheck=" + qAnswerCheck + ", qWriteDate=" + qWriteDate + ", qAnswerDate=" + qAnswerDate
+ "]";
}
public int getqNo() {
return qNo;
}
public void setqNo(int qNo) {
this.qNo = qNo;
}
public String getqName() {
return qName;
}
public void setqName(String qName) {
this.qName = qName;
}
public String getqContents() {
return qContents;
}
public void setqContents(String qContents) {
this.qContents = qContents;
}
public String getqWriter() {
return qWriter;
}
public void setqWriter(String qWriter) {
this.qWriter = qWriter;
}
public String getqAnswerCheck() {
return qAnswerCheck;
}
public void setqAnswerCheck(String qAnswerCheck) {
this.qAnswerCheck = qAnswerCheck;
}
public Timestamp getqWriteDate() {
return qWriteDate;
}
public void setqWriteDate(Timestamp qWriteDate) {
this.qWriteDate = qWriteDate;
}
public Timestamp getqAnswerDate() {
return qAnswerDate;
}
public void setqAnswerDate(Timestamp qAnswerDate) {
this.qAnswerDate = qAnswerDate;
}
}
| true |
b21187c8053855bcac4aa5110886581d496b1cf1 | Java | fuss2120/review-system | /src/main/java/project/reviewsystem/DAO/domain/RatingMapper.java | UTF-8 | 1,047 | 1.96875 | 2 | [] | no_license | package project.reviewsystem.DAO.domain;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Insert;
import project.reviewsystem.domain.Rating;
import project.reviewsystem.domain.Paper;
@Mapper
public interface RatingMapper {
@Select("SELECT REVEMAIL, PAPERID, TECHMERIT, READABILITY, ORIGINALITY, RELAVANCE, OVERALLRECOMM FROM REVIEWS")
public List<Rating> getRatingList();
@Select(
"SELECT "
+ "REVEMAIL, PAPERID, TECHMERIT, READABILITY, "
+ "ORIGINALITY, RELAVANCE, OVERALLRECOMM "
+ "FROM REVIEWS "
+ "WHERE paperid = #{paperid}"
)
public List<Rating> getRatingListForPaper(Paper paper);
@Insert(
"INSERT INTO "
+ "reviews(revemail, paperid, techmerit, readability, originality, relavance, overallrecomm) "
+ "Values "
+ "(#{revemail}, #{paperid}, #{techmerit}, #{readability}, #{originality}, #{relavance}, #{overallrecomm})"
)
public void uploadRating(Rating rating);
}
| true |
e2bc233ccd9681aa2ad54e15189f76a5e7eac23c | Java | Mudassir-ops/mudassir-ops | /app/src/main/java/com/example/CSC_Mudassir/freelancing/UpdateSellingActivity.java | UTF-8 | 3,809 | 2.0625 | 2 | [] | no_license | package com.example.CSC_Mudassir.freelancing;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.CSC_Mudassir.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
public class UpdateSellingActivity extends AppCompatActivity {
public static final String PROJECT_ID = "Project_Id";
EditText project_Name, project_Description, teacher_ContactNo, teacher_Department;
Button upload;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_selling);
ColorDrawable colorDrawable=new ColorDrawable(Color.TRANSPARENT);
getWindow().setBackgroundDrawable(colorDrawable);
getWindow().setLayout(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
project_Name = findViewById(R.id.projectName);
project_Description = findViewById(R.id.projectDescription);
teacher_ContactNo = findViewById(R.id.contactNo);
teacher_Department = findViewById(R.id.teacherDepartment);
upload = findViewById(R.id.uploadButton);
Intent intent = getIntent();
final String mProjectId = intent.getStringExtra(PROJECT_ID);
Log.d("ProjectId", "" + mProjectId);
final DatabaseReference DataRef = FirebaseDatabase.getInstance().getReference().child("Projects");
upload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String projectName = project_Name.getText().toString().trim();
final String projectDescription = project_Description.getText().toString().trim();
final String teacherContactNo = teacher_ContactNo.getText().toString().trim();
final String teacherDepartment = teacher_Department.getText().toString().trim();
Query query = DataRef.orderByChild("PrimaryID").equalTo((String) mProjectId);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
ds.getRef().child("ProjectName").setValue(projectName);
ds.getRef().child("ProjectDescription").setValue(projectDescription);
ds.getRef().child("TeacherContactNo").setValue(teacherContactNo);
ds.getRef().child("TeacherDepartment").setValue(teacherDepartment);
}
startActivity(new Intent(UpdateSellingActivity.this,SellingProjectsActivity.class));
Toast.makeText(getApplicationContext(), "Project Updated", Toast.LENGTH_LONG).show();
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}
});
}
} | true |
9006cbe0971ef49abacf7c7ff1a37e8a07acea5c | Java | tulitas/Country-Validator | /src/test/java/validator/controllers/ValidationControllerTest.java | UTF-8 | 316 | 1.953125 | 2 | [] | no_license | package validator.controllers;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class ValidationControllerTest {
private String message = "oops! Where is it?";
@Test
void getCharNum() {
assertEquals(message, new ValidationController().getMessage());
}
} | true |
2f3b3377f1f69ab6567f0fe2eb0e5c155e08337d | Java | vkurnavenkov/algorithms | /leetcode/backtracking/leetcode-46-permutations.java | UTF-8 | 1,105 | 3.625 | 4 | [] | no_license | // Leetcode 46. Permutations.
//
// Given a collection of distinct integers, return all possible permutations.
//
// Example:
//
// Input: [1,2,3]
// Output:
// [
// [1,2,3],
// [1,3,2],
// [2,1,3],
// [2,3,1],
// [3,1,2],
// [3,2,1]
// ]
//
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
doPermute(nums, 0, results);
return results;
}
private void doPermute(int[] nums, int start, List<List<Integer>> results) {
if (start == nums.length) {
List<Integer> list = new ArrayList<Integer>();
for (int val : nums) {
list.add(val);
}
results.add(list);
return;
}
for (int i = start; i < nums.length; i++) {
swap(nums, start, i);
doPermute(nums, start + 1, results);
swap(nums, start, i);
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
| true |
78ae9dc4bf201a57faab8a5993a97a58c33aa581 | Java | hxq300/ClockIn | /app/src/main/java/com/lsy/wisdom/clockin/activity/add/AddClientActivity.java | UTF-8 | 6,219 | 1.898438 | 2 | [] | no_license | package com.lsy.wisdom.clockin.activity.add;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.lsy.wisdom.clockin.R;
import com.lsy.wisdom.clockin.request.OKHttpClass;
import com.lsy.wisdom.clockin.request.RequestURL;
import com.lsy.wisdom.clockin.utils.L;
import com.lsy.wisdom.clockin.utils.StatusBarUtil;
import com.lsy.wisdom.clockin.utils.TimeUtils;
import com.lsy.wisdom.clockin.utils.ToastUtils;
import com.lsy.wisdom.clockin.widget.IToolbar;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by lsy on 2020/5/12
* todo : 添加客户
*/
public class AddClientActivity extends AppCompatActivity {
@BindView(R.id.aclient_toolbar)
IToolbar aclientToolbar;
@BindView(R.id.aclient_name)
EditText aclientName;
@BindView(R.id.aclient_sex)
EditText aclientSex;
@BindView(R.id.client_job_title)
EditText clientJobTitle;
@BindView(R.id.aclient_department)
EditText aclientDepartment;
@BindView(R.id.aclient_phone)
EditText aclientPhone;
@BindView(R.id.cusm_commit)
Button cusmCommit;
private int items_id = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_client);
setSupportActionBar(aclientToolbar);
ButterKnife.bind(this);
StatusBarUtil.setRootViewFitsSystemWindows(this, false);
StatusBarUtil.setTranslucentStatus(this);
if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
StatusBarUtil.setStatusBarColor(this, 0xF3ef3ed);
}
Intent intent = getIntent();
items_id = intent.getIntExtra("items_id", 0);
initBar();
}
private void initBar() {
aclientToolbar.inflateMenu(R.menu.toolbar_menu);
aclientToolbar.setIToolbarCallback(new IToolbar.IToolbarCallback() {
@Override
public void onClickListener(int pos) {
switch (pos) {
case 0:
finish();
Log.v("TTT", "返回");
break;
default:
break;
}
}
});
}
@OnClick({R.id.cusm_commit})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.cusm_commit:
if (is_input()) {
addCLient();
}
break;
}
}
public void addCLient() {
Map<String, Object> listcanshu = new HashMap<>();
OKHttpClass okHttpClass = new OKHttpClass();
//传参:client_name(联系人姓名),client_sex(性别),client_position(职务),client_department(所在部门),client_phone(联系电话),staff_id,items_id(客户id)
listcanshu.put("client_name", "" + aclientName.getText().toString());
listcanshu.put("client_sex", "" + aclientSex.getText().toString());
listcanshu.put("client_position", "" + clientJobTitle.getText().toString());
listcanshu.put("client_department", "" + aclientDepartment.getText().toString());
listcanshu.put("client_phone", "" + aclientPhone.getText().toString());
listcanshu.put("staff_id", OKHttpClass.getUserId(this));
listcanshu.put("items_id", items_id);
//设置请求类型、地址和参数
okHttpClass.setPostCanShu(AddClientActivity.this, RequestURL.addClient, listcanshu);
okHttpClass.setGetIntenetData(new OKHttpClass.GetData() {
@Override
public String requestData(String dataString) {
//请求成功数据回调
L.log("customerQuery", "" + dataString);
// Gson gson = new Gson();
//{"message":"客户添加成功,暂无联系人!","data":null,"code":200}
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(dataString);
String message = jsonObject.getString("message");
String data = jsonObject.getString("data");
int code = jsonObject.getInt("code");
if (code == 200) {
ToastUtils.showBottomToast(AddClientActivity.this, "" + message);
finish();
} else {
ToastUtils.showBottomToast(AddClientActivity.this, "" + message);
}
} catch (JSONException e) {
e.printStackTrace();
}
return dataString;
}
});
}
/**
* 判断输入完成情况
*/
private boolean is_input() {
if (aclientName.getText().toString().trim().length() < 1) {
Toast.makeText(AddClientActivity.this, "请输入联系人姓名", Toast.LENGTH_SHORT).show();
return false;
}
if (aclientSex.getText().toString().trim().length() < 1) {
Toast.makeText(AddClientActivity.this, "请输入性别", Toast.LENGTH_SHORT).show();
return false;
}
if (clientJobTitle.getText().toString().trim().length() < 1) {
Toast.makeText(AddClientActivity.this, "请输入职位", Toast.LENGTH_SHORT).show();
return false;
}
if (aclientPhone.getText().toString().trim().length() < 11) {
Toast.makeText(AddClientActivity.this, "手机号不正确", Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
}
| true |
f435ff9ea7c9720fbce9957874129dc6be1e6733 | Java | Soocone/K01JAVA | /src/ex04controlstatement/E01If02Practice.java | UTF-8 | 660 | 4.03125 | 4 | [] | no_license | package ex04controlstatement;
public class E01If02Practice {
public static void main(String[] args) {
int num = 101;
if(num%2 == 0)
System.out.println("짝수입니다.");
else
System.out.println("홀수입니다.");
// 홀짝 판단 후 100이상인지를 판단하는 프로그램을 if else로 작성
int num2 = 120;
if(num2%2 == 0) {
if(num>=100) {
System.out.println("짝수 100이상임");
}
else {
System.out.println("짝수 100미만임");
}
}
else {
if(num2>=100) {
System.out.println("홀수 100이상임");
}
else {
System.out.println("홀수 100미만임");
}
}
}
}
| true |
b3da94927af1fce50c4b5c6c2c724dc46613e139 | Java | Eltsine/A2 | /src/main/java/azimut/service/mapper/PeriodeMapper.java | UTF-8 | 525 | 2.265625 | 2 | [] | no_license | package azimut.service.mapper;
import azimut.domain.*;
import azimut.service.dto.PeriodeDTO;
import org.mapstruct.*;
/**
* Mapper for the entity {@link Periode} and its DTO {@link PeriodeDTO}.
*/
@Mapper(componentModel = "spring", uses = {})
public interface PeriodeMapper extends EntityMapper<PeriodeDTO, Periode> {
default Periode fromId(Long id) {
if (id == null) {
return null;
}
Periode periode = new Periode();
periode.setId(id);
return periode;
}
}
| true |
564e98a78004fdebbbddec4521c423506d7123fb | Java | jianghan200/wxsrc6.6.7 | /app/src/main/java/com/tencent/mm/boot/svg/a/a/xv.java | UTF-8 | 4,382 | 1.796875 | 2 | [] | no_license | package com.tencent.mm.boot.svg.a.a;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.os.Looper;
import com.tencent.mm.svg.WeChatSVGRenderC2Java;
import com.tencent.mm.svg.c;
public final class xv
extends c
{
private final int height = 48;
private final int width = 48;
protected final int b(int paramInt, Object... paramVarArgs)
{
switch (paramInt)
{
}
for (;;)
{
return 0;
return 48;
return 48;
Canvas localCanvas = (Canvas)paramVarArgs[0];
paramVarArgs = (Looper)paramVarArgs[1];
Object localObject1 = c.f(paramVarArgs);
float[] arrayOfFloat = c.e(paramVarArgs);
Object localObject2 = c.i(paramVarArgs);
((Paint)localObject2).setFlags(385);
((Paint)localObject2).setStyle(Paint.Style.FILL);
Paint localPaint = c.i(paramVarArgs);
localPaint.setFlags(385);
localPaint.setStyle(Paint.Style.STROKE);
((Paint)localObject2).setColor(-16777216);
localPaint.setStrokeWidth(1.0F);
localPaint.setStrokeCap(Paint.Cap.BUTT);
localPaint.setStrokeJoin(Paint.Join.MITER);
localPaint.setStrokeMiter(4.0F);
localPaint.setPathEffect(null);
c.a(localPaint, paramVarArgs).setStrokeWidth(1.0F);
localCanvas.save();
localObject2 = c.a((Paint)localObject2, paramVarArgs);
((Paint)localObject2).setColor(-5592406);
arrayOfFloat = c.a(arrayOfFloat, 1.0F, 0.0F, -70.0F, 0.0F, 1.0F, -199.0F);
((Matrix)localObject1).reset();
((Matrix)localObject1).setValues(arrayOfFloat);
localCanvas.concat((Matrix)localObject1);
localCanvas.save();
arrayOfFloat = c.a(arrayOfFloat, 1.0F, 0.0F, 69.0F, 0.0F, 1.0F, 98.0F);
((Matrix)localObject1).reset();
((Matrix)localObject1).setValues(arrayOfFloat);
localCanvas.concat((Matrix)localObject1);
localCanvas.save();
arrayOfFloat = c.a(arrayOfFloat, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 101.67347F);
((Matrix)localObject1).reset();
((Matrix)localObject1).setValues(arrayOfFloat);
localCanvas.concat((Matrix)localObject1);
localCanvas.save();
localObject1 = c.a((Paint)localObject2, paramVarArgs);
localObject2 = c.j(paramVarArgs);
((Path)localObject2).moveTo(0.0F, 6.3265305F);
((Path)localObject2).cubicTo(0.0F, 2.9596574F, 2.6835413F, 0.3265306F, 6.0F, 0.3265306F);
((Path)localObject2).lineTo(42.0F, 0.3265306F);
((Path)localObject2).cubicTo(45.31085F, 0.3265306F, 48.0F, 2.9541647F, 48.0F, 6.3265305F);
((Path)localObject2).lineTo(48.0F, 41.32653F);
((Path)localObject2).cubicTo(48.0F, 44.693405F, 45.31646F, 47.32653F, 42.0F, 47.32653F);
((Path)localObject2).lineTo(6.0F, 47.32653F);
((Path)localObject2).cubicTo(2.6891508F, 47.32653F, 0.0F, 44.698895F, 0.0F, 41.32653F);
((Path)localObject2).lineTo(0.0F, 6.3265305F);
((Path)localObject2).lineTo(0.0F, 6.3265305F);
((Path)localObject2).close();
((Path)localObject2).moveTo(4.0F, 6.3265305F);
((Path)localObject2).cubicTo(4.0F, 5.198393F, 4.89154F, 4.3265305F, 6.0F, 4.3265305F);
((Path)localObject2).lineTo(42.0F, 4.3265305F);
((Path)localObject2).cubicTo(43.10578F, 4.3265305F, 44.0F, 5.195782F, 44.0F, 6.3265305F);
((Path)localObject2).lineTo(44.0F, 41.32653F);
((Path)localObject2).cubicTo(44.0F, 42.45467F, 43.10846F, 43.32653F, 42.0F, 43.32653F);
((Path)localObject2).lineTo(6.0F, 43.32653F);
((Path)localObject2).cubicTo(4.894218F, 43.32653F, 4.0F, 42.45728F, 4.0F, 41.32653F);
((Path)localObject2).lineTo(4.0F, 6.3265305F);
((Path)localObject2).lineTo(4.0F, 6.3265305F);
((Path)localObject2).close();
WeChatSVGRenderC2Java.setFillType((Path)localObject2, 2);
localCanvas.drawPath((Path)localObject2, (Paint)localObject1);
localCanvas.restore();
localCanvas.restore();
localCanvas.restore();
localCanvas.restore();
c.h(paramVarArgs);
}
}
}
/* Location: /Users/Han/Desktop/wxall/微信反编译/反编译 6.6.7/dex2jar-2.0/classes-dex2jar.jar!/com/tencent/mm/boot/svg/a/a/xv.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | true |
baffa21b65a29b19b8de4f1d52434baace14e7e9 | Java | sergeassaad/NBody_solution | /src/NBody.java | UTF-8 | 3,427 | 3.421875 | 3 | [
"MIT"
] | permissive | import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class NBody {
public static double readRadius(String filename){ //reads radius from text file
double radius = 0;
try {
File f = new File(filename);
Scanner sc = new Scanner(f);
sc.nextDouble();
radius = sc.nextDouble();
sc.close();
}
catch (FileNotFoundException e) { // stops the program if file not found
e.printStackTrace();
}
return radius;
}
public static Planet[] readPlanets(String filename){ //extracts array of Planets from text file
ArrayList<Planet> pArrayList = new ArrayList<Planet>(); //creates an ArrayList of Planets
try {
File f = new File(filename);
Scanner sc = new Scanner(f);
sc.nextDouble();
sc.nextDouble();
while (sc.hasNextDouble()){ //while the scanner still has data to go through
Planet p = new Planet(0,0,0,0,0,""); //initializes a planet
p.myXPos = sc.nextDouble(); //fields of the planet are defined by text file
p.myYPos = sc.nextDouble();
p.myXVel = sc.nextDouble();
p.myYVel = sc.nextDouble();
p.myMass = sc.nextDouble();
p.myFileName = sc.next();
pArrayList.add(p); // adds the planet to the ArrayList
}
sc.close();
}
catch (FileNotFoundException e) { // stops the program if file not found
e.printStackTrace();
}
Planet [] pArray = pArrayList.toArray(new Planet[pArrayList.size()]); // converts ArrayList to array
return pArray;
}
public static void main (String[] args){ //creates animation and prints final state
// int count = 1;
// String[] mystrarray = {"data/kaleidoscope.txt", "data/3body.txt", "data/hypnosis.txt"};
double T = 157788000.0; //total time (in seconds)
double dt = 25000.0; //time increment (in seconds)
String filename = "data/planets.txt";
// String filename = mystrarray[count];
Planet[] pArray = readPlanets(filename); //creates array of planets
double radius = readRadius(filename); //reads radius
StdDraw.setScale(-radius, radius);
StdDraw.square(0, 0, radius);
StdDraw.picture(0, 0, "images/starfield.jpg"); //draws background
for (int c=0; c<pArray.length; c++){
pArray[c].draw(pArray[c]); //draws initial state of planets
}
for (double time =0; time<T; time+=dt){//loops through time by increments dt until T reached
double xForces[] = new double[pArray.length];
double yForces[] = new double[pArray.length];
for (int k=0; k<pArray.length; k++){ //calculates force on each planet
xForces[k] = pArray[k].calcNetForceExertedByX(pArray);
yForces[k] = pArray[k].calcNetForceExertedByY(pArray);
}
for (int i = 0; i<pArray.length; i++){
pArray[i].update(dt, xForces[i],yForces[i]); //updates planet positions
}
StdDraw.square(0, 0, radius);
StdDraw.picture(0, 0, "images/starfield.jpg"); //draws background
for (int c=0; c<pArray.length; c++){
pArray[c].draw(pArray[c]); //draws planets at current time
}
StdDraw.show(10);
}
System.out.printf("%d\n", pArray.length); //prints number of planets
System.out.printf("%.2e\n", radius); //prints radius of the universe
for (int k = 0; k < pArray.length; k++) { //prints final state of all planets
System.out.printf("%11.4e %11.4e %11.4e %11.4e %11.4e %12s\n",
pArray[k].myXPos, pArray[k].myYPos,
pArray[k].myXVel, pArray[k].myYVel,
pArray[k].myMass, pArray[k].myFileName);
}
}
}
| true |
b2d1b597ad63c1d87bb64b9cb835ee2e0856a914 | Java | moutainhigh/dispatch-1 | /FileService/src/main/java/com/chainway/fileservice/excetion/ExceptionCode.java | UTF-8 | 241 | 1.570313 | 2 | [] | no_license | package com.chainway.fileservice.excetion;
public class ExceptionCode {
public final static int ERROR_SYSTEM_DEFAULT=1;
public final static int ERROR_FILE_TEMPLATE_UNMATCHED_DATA=5000000;//模板列和上传数据列不匹配
}
| true |
f0c8ed2827c76a11cdf4ed399ef36ef4d2aefc2f | Java | majian-shsxt/shop-parent | /shop-www/shop-service/src/main/java/com/shop/service/BrandService.java | UTF-8 | 719 | 2.140625 | 2 | [] | no_license | package com.shop.service;
import com.shop.dao.BrandDao;
import com.shop.model.Brand;
import com.shop.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by TW on 2017/8/24.
*/
@Service
public class BrandService {
@Autowired
private BrandDao brandDao;
/**
* 获取分类下的品牌
* @param productCategoryId
* @return
*/
public List<Brand> findProductCategoryBrands(Integer productCategoryId) {
AssertUtil.intIsNotEmpty(productCategoryId);
List<Brand> brands = brandDao.findProductCategoryBrands(productCategoryId);
return brands;
}
}
| true |
b45c27990f19fecee8b711991e9a9714224d5c29 | Java | shenkuen88/MallOnlineApp | /.svn/pristine/55/559026ccab0502cdc964ae653b1f7322d38ba6d0.svn-base | UTF-8 | 9,763 | 1.695313 | 2 | [] | no_license | package com.nannong.mall.activity.index;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.nannong.mall.R;
import com.nannong.mall.response.index.NoticeListResponse;
import java.util.ArrayList;
import java.util.List;
import cn.nj.www.my_module.adapter.CommonAdapter;
import cn.nj.www.my_module.adapter.ViewHolder;
import cn.nj.www.my_module.bean.BaseResponse;
import cn.nj.www.my_module.bean.NetResponseEvent;
import cn.nj.www.my_module.bean.NoticeEvent;
import cn.nj.www.my_module.constant.Constants;
import cn.nj.www.my_module.constant.ErrorCode;
import cn.nj.www.my_module.constant.NotiTag;
import cn.nj.www.my_module.main.base.BaseActivity;
import cn.nj.www.my_module.main.base.BaseApplication;
import cn.nj.www.my_module.main.base.HeadView;
import cn.nj.www.my_module.network.GsonHelper;
import cn.nj.www.my_module.network.UserServiceImpl;
import cn.nj.www.my_module.tools.CMLog;
import cn.nj.www.my_module.tools.GeneralUtils;
import cn.nj.www.my_module.tools.NetLoadingDialog;
import cn.nj.www.my_module.tools.ToastUtil;
import cn.nj.www.my_module.view.banner.ConvenientBanner;
import cn.nj.www.my_module.view.varyview.VaryViewHelper;
/**
* 兑换记录
*/
public class ExchangeActivity extends BaseActivity implements View.OnClickListener
{
private ListView lvZhengWu;
private int page = 1;
private int loadPage = 1;
private CommonAdapter<NoticeListResponse.NoticeListBean> lvAdapter;
private List<NoticeListResponse.NoticeListBean> datas = new ArrayList<NoticeListResponse.NoticeListBean>();
private int tolcount = 0;
private boolean isloading;
private int lastVisibileItem;
private View loadingView;
private LinearLayout llLoading;
private TextView tvSeeMoreDate;
private VaryViewHelper mVaryViewHelper;
/**
* 默认的本地地址
*/
private ArrayList<Integer> localImages = new ArrayList<Integer>();
/**
* 网络图片地址
*/
private List<String> networkImages = new ArrayList<>();
private ConvenientBanner mBanner;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zhengwu_list);
initAll();
initData();
}
@Override
public void initView()
{
initTitle();
lvZhengWu = (ListView) findViewById(R.id.zw_lv);
lvScrollLoadData();
initAdapter();
}
private void initAdapter()
{
lvAdapter = new CommonAdapter<NoticeListResponse.NoticeListBean>(mContext, datas, R.layout.item_zhengwu)
{
@Override
public void convert(ViewHolder helper, final NoticeListResponse.NoticeListBean item)
{
}
};
lvZhengWu.setAdapter(lvAdapter);
}
private void lvScrollLoadData()
{
lvZhengWu.setOnScrollListener(new AbsListView.OnScrollListener()
{
@Override
public void onScrollStateChanged(AbsListView absListView, int scrollState)
{
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && (lastVisibileItem + 1) == lvZhengWu.getCount())
{
if (!isloading)
{
if (tolcount > page * Constants.LIST_NUM)
{
loadPage++;
initData();
}
else
{
// ToastUtil.makeText(getActivity(), "当前是最后一页");
}
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
{
lastVisibileItem = firstVisibleItem + visibleItemCount - 1;
}
});
loadingView = LayoutInflater.from(mContext).inflate(R.layout.ef_loading_foot, null);
llLoading = (LinearLayout) loadingView.findViewById(R.id.loading_test_ll);
tvSeeMoreDate = (TextView) loadingView.findViewById(R.id.load_more_tv);
tvSeeMoreDate.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (tolcount > page * Constants.LIST_NUM)
{
loadPage++;
initData();
}
else
{
// ToastUtil.makeText(getActivity(), "当前是最后一页");
}
}
});
tvSeeMoreDate.setVisibility(View.GONE);
lvZhengWu.addFooterView(loadingView);
}
private void initData()
{
isloading = true;
llLoading.setVisibility(View.VISIBLE);
if (loadPage == 1)
{
mVaryViewHelper.showLoadingView();
}
UserServiceImpl.instance().getNotice(loadPage, NoticeListResponse.class.getName());
}
@Override
public void initViewData()
{
if (datas.size() == 0)
{
mVaryViewHelper = new VaryViewHelper.Builder()
.setDataView(findViewById(R.id.content_view))//放数据的父布局,逻辑处理在该Activity中处理
.setEmptyView(R.mipmap.ic_launcher, "暂无")//空页面,图+文字
.setRefreshListener(new View.OnClickListener()//断网等错误时并且没有数据,显示错误,点击按钮刷新
{
@Override
public void onClick(View v)
{
if (GeneralUtils.isNetworkConnected(mContext))
{
mVaryViewHelper.showLoadingView();
loadPage = 1;
initData();
}
else
{
ToastUtil.showError(mContext);
}
}
})//错误页点击刷新实现
.build(mContext);
mVaryViewHelper.showLoadingView();
}
}
@Override
public void initEvent()
{
}
@Override
public void netResponse(BaseResponse event)
{
if (event instanceof NoticeEvent)
{
String tag = ((NoticeEvent) event).getTag();
if (NotiTag.TAG_CLOSE_ACTIVITY.equals(tag) && BaseApplication.currentActivity.equals(this.getClass().getName()))
{
finish();
}
}
if (event instanceof NetResponseEvent)
{
NetLoadingDialog.getInstance().dismissDialog();
String tag = ((NetResponseEvent) event).getTag();
String result = ((NetResponseEvent) event).getResult();
llLoading.setVisibility(View.GONE);
tvSeeMoreDate.setVisibility(View.VISIBLE);
mVaryViewHelper.showDataView();
if (tag.equals(NoticeListResponse.class.getName()))
{
CMLog.e(Constants.HTTP_TAG, result);
if (GeneralUtils.isNotNullOrZeroLenght(result))
{
NoticeListResponse orderResponse = GsonHelper.toType(result, NoticeListResponse.class);
if (Constants.SUCESS_CODE.equals(orderResponse.getResultCode()))
{
if (loadPage == 1)
{
datas.clear();
}
page = loadPage;
tolcount = orderResponse.getTotalCount();
datas.addAll(orderResponse.getNoticeList());
lvAdapter.setData(datas);
lvAdapter.notifyDataSetChanged();
isloading = false;
if (tolcount <= page * Constants.LIST_NUM)
{
tvSeeMoreDate.setText("已加载完毕");
}
if (datas.size() == 0)
{
mVaryViewHelper.showEmptyView();
}
}
else
{
page = loadPage;
if (datas.size() == 0)
{
mVaryViewHelper.showEmptyView();
}
ErrorCode.doCode(mContext, orderResponse.getResultCode(), orderResponse.getDesc());
}
}
else
{
page = loadPage;
if (datas.size() == 0)
{
mVaryViewHelper.showErrorView();
}
ToastUtil.showError(mContext);
}
}
}
}
private void initTitle()
{
View view = findViewById(R.id.common_back);
HeadView headView = new HeadView((ViewGroup) view);
headView.setTitleText("政务");
headView.setLeftImage(R.mipmap.app_title_back);
headView.setHiddenRight();
}
@Override
public void onClick(View view)
{
switch (view.getId())
{
}
}
}
| true |
42bceaabd1ede05937af7520e51abb0517e9e88e | Java | Dancibela87/JavaProgramming_B23 | /src/day46_InheritanceContinue/ShapeTAsk/Shape.java | UTF-8 | 793 | 3.640625 | 4 | [] | no_license | package day46_InheritanceContinue.ShapeTAsk;
public class Shape {
private final String name;
public final static boolean isShape ;
public final static boolean hasArea ;
public final static boolean hasPerimeter ;
static {
isShape = true;
hasArea = true;
hasPerimeter = true;
}
public Shape(String name) {
this.name = name;
}
public String getName() {
return name;
}
public double calcArea(){
return 0;
}
public double calcPerimeter(){
return 0;
}
@Override
public String toString() {
return "Shape{" +
"name='" + name + '\'' +
"area= " +calcArea()+
"perimeter= " + calcPerimeter() +
'}';
}
}
| true |
8ddd5ef5f6c155afd9e1a80db00ceea53f25f6ef | Java | samsic-r/raeder | /src/Reader/CommandLineArgumentSupplier.java | UTF-8 | 2,673 | 3.125 | 3 | [] | no_license | package Reader;
import java.io.File;
public class CommandLineArgumentSupplier implements ArgumentSupplier {
private String[] argumentsArray;
public CommandLineArgumentSupplier(String[] argumentsArray) {
this.argumentsArray = argumentsArray;
}
@Override
public Arguments processArguments() throws ArgumentsException {
checkArgumentsSize();
String directoryForScan = checkAndGetDirectoryForScan( argumentsArray[0] );
String reportPath = checkAndGetReportPath( argumentsArray[1] );
String reportFileName = checkAndGetReportFileName( argumentsArray[2] );
String extensionFilter = argumentsArray.length == 4 ? argumentsArray[3] : "";
return new Arguments( directoryForScan, reportPath, reportFileName, extensionFilter );
}
public void checkArgumentsSize() throws ArgumentsException {
if (argumentsArray == null || argumentsArray.length < 3) {
throw new ArgumentsException( "Неверное число введенных аргументов. Минимальное число аргументов (3)" );
} else if (argumentsArray.length > 4) {
throw new ArgumentsException( "Превышено число введенных аргументов. Максимальное число аргументов (4)" );
}
}
public String checkAndGetDirectoryForScan(String directory) throws ArgumentsException {
File file = new File( directory );
if (!file.exists()) throw new ArgumentsException( "Директория для сканирования не найдена!!!\n" );
else return directory;
}
public String checkAndGetReportPath(String reportPath) throws ArgumentsException {
File file = new File( reportPath );
if (!file.exists())
throw new ArgumentsException( "Директория для сохранения файла не найдена или введена не верно!!!\n" +
"Примеры ввода (D:/ или D:/Название папки)" );
else return reportPath;
}
public String checkAndGetReportFileName(String reportFileName) throws ArgumentsException {
char[] chars = {'\\', '/', ':', '*', '?', '"', '<', '>', '|'};
for (char c : chars) {
if (reportFileName.indexOf( c ) != -1)
throw new ArgumentsException( "Введено недопустимое имя файла.\n" +
"Имя файла не должно содержать символов (\\, /, |, :, *, ?, '', <, >)" );
}
return reportFileName;
}
}
| true |
2e1e83b0ebd40bd1f28d95f195f1bf5be3751867 | Java | tengxinkeji/SmartMall | /app/src/main/java/cn/lanmei/com/smartmall/customization/F_custom_right.java | UTF-8 | 10,565 | 1.523438 | 2 | [] | no_license | package cn.lanmei.com.smartmall.customization;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import com.common.app.BaseScrollFragment;
import com.common.app.Common;
import com.common.app.MyApplication;
import com.common.app.StaticMethod;
import com.common.app.degexce.CustomExce;
import com.common.app.degexce.L;
import com.common.app.sd.Enum_Dir;
import com.common.app.sd.SDCardUtils;
import com.common.myinterface.DataCallBack;
import com.common.myui.MyGridView;
import com.common.net.NetData;
import com.common.net.RequestParams;
import com.common.popup.SelectPicPopupWindow;
import com.common.tools.PhotoSelectActivityResult;
import com.oss.ManageOssUpload;
import com.pulltorefresh.library.PullToRefreshBase;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import cn.lanmei.com.smartmall.R;
import cn.lanmei.com.smartmall.adapter.AdapterImgUpload;
import cn.lanmei.com.smartmall.main.BaseActivity;
import cn.lanmei.com.smartmall.parse.ParserJson;
import cn.lanmei.com.smartmall.post.Activity_list_post;
/**
*
*/
public class F_custom_right extends BaseScrollFragment implements PhotoSelectActivityResult.UploadImgResult{
private String TAG="F_custom_right";
private int goodsId;
private EditText editCustom;
private MyGridView gridImgs;
private TextView txtPost;
private TextView txtPostSelect;
private TextView txtRefer;
private int postId;
private Resources res;
private List<String> goodsErrImgs;
private AdapterImgUpload adapterImgUpload;
private ManageOssUpload manageOssUpload;
private PhotoSelectActivityResult<BaseActivity> photoSelectActivityResult;
public static F_custom_right newInstance(int goodsId) {
F_custom_right fragment = new F_custom_right();
Bundle bundle = new Bundle();
bundle.putInt("goodsId",goodsId);
// bundle.putInt("goodsId",6);
fragment.setArguments(bundle);
return fragment;
}
@Override
public void init() {
res=getResources();
tag=res.getString(R.string.topic_send);
if (getArguments()!=null){
goodsId=getArguments().getInt("goodsId");
}
manageOssUpload=new ManageOssUpload(mContext);
goodsErrImgs=new ArrayList<>();
goodsErrImgs.add("drawable://" + R.drawable.img_add);
adapterImgUpload=new AdapterImgUpload(mContext,goodsErrImgs);
photoSelectActivityResult=new PhotoSelectActivityResult<>((BaseActivity)getActivity(),manageOssUpload,this);
}
@Override
public void loadViewLayout() {
setContentView(R.layout.layout_custom_right);
}
@Override
public void findViewById() {
editCustom=(EditText) findViewById(R.id.edit_custom);
gridImgs=(MyGridView) findViewById(R.id.grid_img_upload);
txtPost=(TextView) findViewById(R.id.txt_post_name);
txtPostSelect=(TextView) findViewById(R.id.txt_post_select);
txtRefer=(TextView) findViewById(R.id.txt_refer);
gridImgs.setAdapter(adapterImgUpload);
adapterImgUpload.setUploadGridListener(new AdapterImgUpload.UploadGridListener() {
@Override
public void uploadImgAdd() {
new SelectPicPopupWindow(mContext, new SelectPicPopupWindow.PicPopupListener() {
@Override
public void takePhone(Button v) {
selectTakePhone();
}
@Override
public void pickPhone(Button v) {
selectPickPhone();
}
}).showPopupWindow(gridImgs);
}
@Override
public void uploadImgDel(int position) {
L.MyLog(TAG,goodsErrImgs.get(position)+"");
new AsyncTask<Integer,Integer,Boolean>(){
@Override
protected Boolean doInBackground(Integer... params) {
int position=params[0];
boolean result=manageOssUpload.uploadFile_del(goodsErrImgs.get(position));
if (result)
goodsErrImgs.remove(position);
return result;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
if (aBoolean)
adapterImgUpload.refreshData(goodsErrImgs);
}
}.execute(position);
//
}
});
txtPost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent toIntent=new Intent(getActivity(), Activity_list_post.class);
getActivity().startActivityForResult(toIntent,Common.requestCode_post);
}
});
txtPostSelect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent toIntent=new Intent(getActivity(), Activity_list_post.class);
getActivity().startActivityForResult(toIntent,Common.requestCode_post);
}
});
txtRefer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
refer();
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==Common.requestCode_post
&&resultCode==Common.resultCode_post){//选择圈子
postId=data.getIntExtra(Common.KEY_id,0);
String name=data.getStringExtra("name");
txtPost.setText(name+"");
}else {
photoSelectActivityResult.photoSelectActivityResult(uploadImgFile,requestCode, resultCode, data);
}
}
@Override
public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
requestServerData();
}
@Override
public void requestServerData() {
}
File uploadImgFile;
/**相册*/
private void selectPickPhone(){
String uploadImgName = getImgName();
File dir;
try {
dir= SDCardUtils.getDirFile(Enum_Dir.DIR_img);
} catch (CustomExce customExce) {
customExce.printStackTrace();
StaticMethod.showInfo(mContext,res.getString(R.string.err_sd));
return;
}
uploadImgFile= new File(dir, uploadImgName);
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
Common.IMAGE_UNSPECIFIED);
((BaseActivity)getActivity()).startActivityForResult(intent, Common.PHOTO_PICK);
}
/**拍照*/
private void selectTakePhone(){
String uploadImgName = getImgName();
File dir;
try {
dir= SDCardUtils.getDirFile(Enum_Dir.DIR_img);
} catch (CustomExce customExce) {
customExce.printStackTrace();
StaticMethod.showInfo(mContext,res.getString(R.string.err_sd));
return;
}
uploadImgFile = new File(dir, uploadImgName);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(uploadImgFile));
((BaseActivity)getActivity()).startActivityForResult(intent, Common.PHOTO_GRAPH);
}
private String getImgName(){
return System.currentTimeMillis()+".png";
}
private void refer(){
String explain = editCustom.getText().toString();
L.MyLog("",explain);
if (TextUtils.isEmpty(explain)){
StaticMethod.showInfo(mContext,res.getString(R.string.topic_send_hint));
return;
}
if (postId==0){
StaticMethod.showInfo(mContext,res.getString(R.string.topic_send_post_select));
return;
}
RequestParams requestParams=new RequestParams(NetData.ACTION_topic_send);
requestParams.setPost(true);
requestParams.addParam("uid", MyApplication.getInstance().getUid());
requestParams.addParam("cid",postId);
requestParams.addParam("title",explain);
requestParams.addParam("type",goodsErrImgs.size()>1?2:1);
int count=0;
for (String picUrl:goodsErrImgs){
if (picUrl.startsWith("drawable"))
continue;
requestParams.addParam("file["+count+"]", picUrl);
count++;
}
requestParams.setBaseParser(new ParserJson());
getDataFromServer(requestParams, new DataCallBack<JSONObject>() {
@Override
public void onPre() {
txtRefer.setEnabled(false);
startProgressDialog();
}
@Override
public void processData(JSONObject parserData) {
parserInfo(parserData);
}
@Override
public void onComplete() {
txtRefer.setEnabled(true);
stopProgressDialog();
}
});
}
private void parserInfo(JSONObject result) {
L.MyLog(TAG,result.toString());
txtRefer.setEnabled(true);
stopProgressDialog();
if (result!=null){
try {
StaticMethod.showInfo(mContext,result.getString("info"));
if (result.getInt("status")==1){
}
} catch (JSONException e) {
e.printStackTrace();
}
}else{
StaticMethod.showInfo(mContext,"提交失败");
}
}
@Override
public void setOnBarLeft() {
super.setOnBarLeft();
getActivity().finish();
}
@Override
public void uploadImgResult(String urlImg) {
L.MyLog(TAG,"uploadImgAdd:"+urlImg);
goodsErrImgs.add(0,urlImg);
adapterImgUpload.refreshData(goodsErrImgs);
}
}
| true |
30a4bd1eed075881ec0d471551356083a8c6234d | Java | alexanderyu1/digitalLogicLab | /src/inputClass.java | UTF-8 | 3,367 | 3.59375 | 4 | [] | no_license | import java.util.Scanner;
public class inputClass {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("First input: ");
int inputA = in.nextInt();
System.out.print("Second input: ");
int inputB = in.nextInt();
in.close();
//AND GATE OUTPUT
andGate andGateObj = new andGate();
andGateObj.setInputA(inputA);
andGateObj.setInputB(inputB);
System.out.println("\nAND gate output: " + andGateObj.and());
//NAND GATE OUTPUT
nandGate nandGateObj = new nandGate();
nandGateObj.setInputA(inputA);
nandGateObj.setInputB(inputB);
System.out.println("NAND gate output: " + nandGateObj.nand());
//OR GATE OUTPUT
orGate orGateObj = new orGate();
orGateObj.setInputA(inputA);
orGateObj.setInputB(inputB);
System.out.println("OR gate output: " + orGateObj.or());
//NOR GATE OUTPUT
norGate norGateObj = new norGate();
norGateObj.setInputA(inputA);
norGateObj.setInputB(inputB);
System.out.println("NOR gate output: " + norGateObj.nor());
//XOR GATE OUTPUT
xorGate xorGateObj = new xorGate();
xorGateObj.setInputA(inputA);
xorGateObj.setInputB(inputB);
System.out.println("XOR gate output: " + xorGateObj.xor());
//XNOR GATE OUTPUT
xnorGate xnorGateObj = new xnorGate();
xnorGateObj.setInputA(inputA);
xnorGateObj.setInputB(inputB);
System.out.println("XNOR gate output: " + xnorGateObj.xnor());
//NOT GATE OUTPUT
notGate notGateObj = new notGate();
notGateObj.setInput(inputA);
System.out.println("NOT gate output (uses first input): " + notGateObj.not());
//FIRST IMAGE CODE
notGate notGateAFirstImage = new notGate();
notGate notGateBFirstImage = new notGate();
andGate andGateTopFirstImage = new andGate();
andGate andGateBottomFirstImage = new andGate();
orGate orGateFirstImage = new orGate();
//first layer
notGateAFirstImage.setInput(inputA);
notGateBFirstImage.setInput(inputB);
//second layer
andGateTopFirstImage.setInputA(notGateAFirstImage.not());
andGateTopFirstImage.setInputB(inputB);
andGateBottomFirstImage.setInputA(inputA);
andGateBottomFirstImage.setInputB(notGateBFirstImage.not());
//third layer
orGateFirstImage.setInputA(andGateTopFirstImage.and());
orGateFirstImage.setInputB(andGateBottomFirstImage.and());
//output
System.out.println("\nFirst image output: " + orGateFirstImage.or());
//SECOND IMAGE CODE
xnorGate xnorGateSecondImage = new xnorGate();
nandGate nandGateSecondImage = new nandGate();
//only layer
xnorGateSecondImage.setInputA(inputA);
xnorGateSecondImage.setInputB(inputB);
nandGateSecondImage.setInputA(inputA);
nandGateSecondImage.setInputB(inputB);
//output
System.out.println("Second image S output: " + xnorGateSecondImage.xnor());
System.out.println("Second image C output: " + nandGateSecondImage.nand());
}
}
| true |
db728451b98d24c3231fee61fc31117b92aac466 | Java | ShadowAmbush/JavaProjectFinal | /SOS/src/view/IO.java | ISO-8859-1 | 1,256 | 3.375 | 3 | [] | no_license | package view;
import java.util.Scanner;
public class IO {
// =============== FUNES IO =========
// Ler do dispositivo sandard de entrada
// uma string que converte em interiro
// que retorna
public static int getInt() {
@SuppressWarnings("resource")
Scanner t = new Scanner(System.in);
try {
return Integer.parseInt(t.nextLine());
} catch (Exception e) {
return 0;
}
}
// Ler do dispositivo sandard de entrada
// uma string que converte em double
// que retorna
public static double getDouble() {
@SuppressWarnings("resource")
Scanner t = new Scanner(System.in);
try {
return Double.parseDouble(t.nextLine());
} catch (Exception e) {
return 0;
}
}
// Ler do dispositivo sandard de entrada
// uma string que converte em double
// que retorna
public static float getFloat() {
@SuppressWarnings("resource")
Scanner t = new Scanner(System.in);
try {
return Float.parseFloat(t.nextLine());
} catch (Exception e) {
return 0;
}
}
// Ler do dispositivo sandard de entrada
// uma string que retorna
public static String getString() {
@SuppressWarnings("resource")
Scanner t = new Scanner(System.in);
try {
return t.nextLine();
} catch (Exception e) {
return "";
}
}
}
| true |
a7a3a79fb7a218590cbd707e82c8e0c3d18904d3 | Java | Jackpot3/niukewangOnline | /src/main/java/com/niukewang/jianzhioffer/Q7.java | UTF-8 | 834 | 3.015625 | 3 | [] | no_license | /*
package com.niukewang.jianzhioffer;
*/
/**
* @author Jackpot
* 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
*//*
public class Q7 {
public static void main(String[] args) {
System.out.println(Power(2, 2));
}
public int NumberOf1(int n) {
if (n >= 0) {
}
return 0;
}
public static String change(int n, int system) {
return null;
}
public static double Power(double base, int exponent) {
if(exponent==0){
return 1;
}else if(exponent>0){
double i = base;
while(exponent>1){
base*= i;
}
return base;
}else{
exponent = -exponent;
return 1/Power(base,exponent);
}
}
}
*/
| true |
a5e96160687697f15b1a89f376619486eaeba5cf | Java | shitsurei/JavaSE | /ds/CollectionsDemo.java | UTF-8 | 1,739 | 3.96875 | 4 | [] | no_license | package ds;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsDemo {
public static void main(String[] args) {
/**
* Collection是集合体系的最顶层,包含了集合体系的共性,分为List和Set两大类
* Collections是一个工具类 ,方法用于操作Collection
*/
//二分查找查询指定元素在指定列表的索引位置,要求列表有序
List<String> ls = new ArrayList<>();
ls.add("aaa");
ls.add("bbb");
ls.add("ccc");
ls.add("ddd");
ls.add("eee");
ls.add("fff");
int index = Collections.binarySearch(ls, "ccc");
System.out.println(index);
/*
List<String> ls2 = new ArrayList<>();
ls2.add("");
ls2.add("");
ls2.add("");
ls2.add("");
ls2.add("");
ls2.add("");
ls2.add("");
ls2.add("");
//把源列表中的数据覆盖到目标列表中,要求目标列表的长度大于等于源列表
Collections.copy(ls2, ls);
for(String e : ls2){
System.out.println(e);
}
//使用指定元素填充列表的所有位置
Collections.fill(ls2, "7777");
for(String e : ls2){
System.out.println(e);
}
for(String e : ls2){
System.out.println(e);
}
//将列表中的元素顺序进行反转
Collections.reverse(ls);
for(String e : ls){
System.out.println(e);
}*/
//随机置换列表中的元素位置,每次执行都不同
Collections.shuffle(ls);
for(String e : ls){
System.out.println(e);
}
//按照列表中的自然顺序进行快排
Collections.sort(ls);
for(String e : ls){
System.out.println(e);
}
//将列表中两元素的位置进行互换
Collections.swap(ls, 0, 1);
for(String e : ls){
System.out.println(e);
}
}
}
| true |
9311ee6990411aa85645e9108839dd80f087f0e4 | Java | eyesniper2/NukeTankAI | /src/main/java/net/rayfall/TankAI/Region.java | UTF-8 | 1,011 | 2.9375 | 3 | [] | no_license | package net.rayfall.TankAI;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Region {
private Number cornerX;
private Number cornerY;
private Number sizeX;
private Number sizeY;
public Region(JSONObject box){
try{
JSONArray hold = box.getJSONArray("corner");
for(int i = 0; i < 2; i++){
if(i == 0){
this.cornerX = hold.getDouble(i);
}
else if(i == 1){
this.cornerY = hold.getDouble(i);
}
}
JSONArray hold2 = box.getJSONArray("size");
for(int i = 0; i < 2; i++){
if(i == 0){
this.sizeX = hold2.getDouble(i);
}
else if(i == 1){
this.sizeY = hold2.getDouble(i);
}
}
}
catch(JSONException e) {
System.err.println("[Building region] JSON Error " + e);
}
}
public Number getCornerX(){
return this.cornerX;
}
public Number getCornerY(){
return this.cornerY;
}
public Number getSizeX(){
return this.sizeX;
}
public Number getSizeY(){
return this.sizeY;
}
}
| true |
47fd31d2e64396100713b302320ca866b6671610 | Java | cha63506/CompSecurity | /Photography/picarts_studio_source/src/myobfuscated/cp/b.java | UTF-8 | 11,338 | 1.679688 | 2 | [] | no_license | // Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package myobfuscated.cp;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.socialin.android.d;
import com.socialin.android.util.an;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import myobfuscated.cb.c;
// Referenced classes of package myobfuscated.cp:
// a, d, c
public class b extends an
{
private static final Object d = myobfuscated/cp/b.getSimpleName();
WeakReference a;
String b;
WeakReference c;
private WeakReference e;
private b(c c1, String s, a a1)
{
a = new WeakReference(c1);
b = s;
e = new WeakReference(a1);
}
public b(c c1, String s, a a1, myobfuscated.cp.c c2)
{
this(c1, s, a1);
if (c2 != null)
{
c = new WeakReference(c2);
}
}
private transient String a(String as[])
{
Object obj;
Object obj1;
String s;
Object obj2;
if (a.a)
{
(new StringBuilder("doInBackground, url: ")).append(b);
}
obj2 = as[0];
s = as[1];
obj = null;
obj1 = null;
as = (HttpURLConnection)(new URL(b)).openConnection();
long l1;
as.setReadTimeout(20000);
as.setConnectTimeout(20000);
as.setDefaultUseCaches(false);
as.setUseCaches(false);
as.setRequestMethod("GET");
as.setRequestProperty("Content-Type", "application/octet-stream");
as.setRequestProperty("Pragma", "no-cache");
as.setRequestProperty("Cache-Control", "no-cache");
as.setRequestProperty("Expires", "-1");
as.setRequestProperty("Accept-Encoding", "identity");
as.connect();
l1 = as.getContentLength();
if (!a.a);
obj1 = Environment.getExternalStorageDirectory();
obj = new BufferedInputStream(as.getInputStream());
if (!((File) (obj1)).exists() || !((File) (obj1)).canWrite()) goto _L2; else goto _L1
_L1:
obj1 = new File(((String) (obj2)));
((File) (obj1)).mkdirs();
if (!a.a);
obj2 = new File(((File) (obj1)), (new StringBuilder()).append(s).append(".part").toString());
((File) (obj2)).createNewFile();
_L7:
Object obj3;
byte abyte0[];
obj3 = new FileOutputStream(((File) (obj2)));
abyte0 = new byte[4096];
long l = 0L;
_L6:
int i = ((InputStream) (obj)).read(abyte0);
if (i == -1) goto _L4; else goto _L3
_L3:
l += i;
publishProgress(new Integer[] {
Integer.valueOf((int)((100L * l) / l1))
});
((OutputStream) (obj3)).write(abyte0, 0, i);
if (!isCancelled()) goto _L6; else goto _L5
_L5:
((File) (obj2)).delete();
try
{
as.disconnect();
}
// Misplaced declaration of an exception variable
catch (String as[])
{
com.socialin.android.d.a(new Object[] {
d, (new StringBuilder("Got unexpected exception: ")).append(as.getMessage()).toString()
});
}
return null;
obj3;
com.socialin.android.d.a(new Object[] {
d, (new StringBuilder("Got unexpected exception: ")).append(((Exception) (obj3)).getMessage()).toString()
});
goto _L7
obj;
_L14:
if (a.a)
{
com.socialin.android.d.b("MalformedURLException in packFileDownloader");
}
com.socialin.android.d.a(new Object[] {
d, (new StringBuilder("Got unexpected exception: ")).append(((MalformedURLException) (obj)).getMessage()).toString()
});
try
{
as.disconnect();
}
// Misplaced declaration of an exception variable
catch (String as[])
{
com.socialin.android.d.a(new Object[] {
d, (new StringBuilder("Got unexpected exception: ")).append(as.getMessage()).toString()
});
}
_L8:
return null;
_L4:
((OutputStream) (obj3)).flush();
((OutputStream) (obj3)).close();
((InputStream) (obj)).close();
((File) (obj2)).renameTo(new File(((File) (obj1)), s));
try
{
as.disconnect();
}
// Misplaced declaration of an exception variable
catch (String as[])
{
com.socialin.android.d.a(new Object[] {
d, (new StringBuilder("Got unexpected exception: ")).append(as.getMessage()).toString()
});
}
return s;
_L2:
if (a.a)
{
com.socialin.android.d.b("can't create pack File");
}
try
{
as.disconnect();
}
// Misplaced declaration of an exception variable
catch (String as[])
{
com.socialin.android.d.a(new Object[] {
d, (new StringBuilder("Got unexpected exception: ")).append(as.getMessage()).toString()
});
}
break MISSING_BLOCK_LABEL_420;
obj;
as = ((String []) (obj1));
obj1 = obj;
_L12:
i = -1;
obj = as;
int j = as.getResponseCode();
i = j;
_L9:
obj = as;
if (!a.a)
{
break MISSING_BLOCK_LABEL_689;
}
obj = as;
com.socialin.android.d.b((new StringBuilder("IOException in packFileDownloader, statuscode: ")).append(i).toString());
obj = as;
com.socialin.android.d.a(new Object[] {
d, (new StringBuilder("Got unexpected exception: ")).append(((IOException) (obj1)).getMessage()).toString()
});
try
{
as.disconnect();
}
// Misplaced declaration of an exception variable
catch (String as[])
{
com.socialin.android.d.a(new Object[] {
d, (new StringBuilder("Got unexpected exception: ")).append(as.getMessage()).toString()
});
}
goto _L8
Exception exception;
exception;
obj = as;
com.socialin.android.d.a(new Object[] {
d, (new StringBuilder("Got unexpected exception: ")).append(exception.getMessage()).toString()
});
goto _L9
as;
_L11:
try
{
((HttpURLConnection) (obj)).disconnect();
}
// Misplaced declaration of an exception variable
catch (Object obj)
{
com.socialin.android.d.a(new Object[] {
d, (new StringBuilder("Got unexpected exception: ")).append(((Exception) (obj)).getMessage()).toString()
});
}
throw as;
obj1;
obj = as;
as = ((String []) (obj1));
continue; /* Loop/switch isn't completed */
obj1;
obj = as;
as = ((String []) (obj1));
if (true) goto _L11; else goto _L10
_L10:
obj1;
goto _L12
obj;
as = null;
if (true) goto _L14; else goto _L13
_L13:
}
protected Object doInBackground(Object aobj[])
{
return a((String[])aobj);
}
protected void onCancelled()
{
super.onCancelled();
}
protected volatile void onCancelled(Object obj)
{
super.onCancelled((String)obj);
}
protected void onPostExecute(Object obj)
{
Object obj1 = (String)obj;
if (!isCancelled() && obj1 != null)
{
obj = (a)e.get();
if (a.a)
{
(new StringBuilder("onPostExecute, result:")).append(((String) (obj1))).append(" downloader: ").append(obj);
}
if (obj != null)
{
((a) (obj)).c.remove(this);
c c1 = (c)a.get();
if (c1 != null)
{
View view = c1.a();
if (obj1 != null)
{
if (c1.a(((String) (obj1))))
{
if (view != null)
{
c1.n = "";
((TextView)view.findViewById(0x7f10027c)).setText("");
((TextView)view.findViewById(0x7f10027b)).setText(c1.e);
((ImageView)view.findViewById(0x7f100279)).setBackgroundDrawable(c1.f);
}
c1.a(0);
} else
if (view != null)
{
((TextView)view.findViewById(0x7f10027c)).setText(0x7f0802c9);
}
} else
{
if (view != null)
{
((TextView)view.findViewById(0x7f10027c)).setText(0x7f0802c9);
}
c1.a(1);
}
c1.b();
}
if (((a) (obj)).b.size() > 0)
{
obj1 = (myobfuscated.cp.d)((a) (obj)).b.remove(0);
((a) (obj)).a(((myobfuscated.cp.d) (obj1)).a, ((myobfuscated.cp.d) (obj1)).b, (c)((myobfuscated.cp.d) (obj1)).d.get(), ((myobfuscated.cp.d) (obj1)).c);
}
if (c != null)
{
obj = (myobfuscated.cp.c)c.get();
if (a.a)
{
(new StringBuilder("onPostExecute, listener:")).append(obj);
}
if (obj != null)
{
((myobfuscated.cp.c) (obj)).a();
return;
}
}
}
}
}
protected void onProgressUpdate(Object aobj[])
{
int i = ((Integer[])aobj)[0].intValue();
aobj = (c)a.get();
if (aobj != null)
{
View view = ((c) (aobj)).a();
if (view != null)
{
if (i > 0)
{
aobj.n = (new StringBuilder()).append(String.valueOf(i)).append("%").toString();
((TextView)view.findViewById(0x7f10027c)).setText(((c) (aobj)).n);
} else
{
((TextView)view.findViewById(0x7f10027c)).setText(0x7f08041c);
}
}
((c) (aobj)).b();
}
if (c != null)
{
aobj = (myobfuscated.cp.c)c.get();
if (aobj != null)
{
if (i < 0)
{
i = 0;
}
((myobfuscated.cp.c) (aobj)).a(i);
}
}
}
}
| true |
da5599a2f51388b0ef8158a3c4bcb5658b9aaafe | Java | CaiHong9225/LP | /app/src/main/java/com/ccc/locationprovider/utils/LpDebugUtils.java | UTF-8 | 2,734 | 2.09375 | 2 | [] | no_license | package com.ccc.locationprovider.utils;
import android.app.AlertDialog;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.EditText;
import com.ccc.locationprovider.R;
import com.ccc.locationprovider.widget.X5WebView;
/**
* @ProjectName: LocationProvider
* @Package: com.ccc.locationprovider.utils
* @ClassName: LpDebugUtils
* @Description: java类作用描述
* @Author: admin
* @CreateDate: 2019/12/26 11:51
* @UpdateUser: admin
* @UpdateDate: 2019/12/26 11:51
* @UpdateRemark:
* @Version: 1.0
*/
public class LpDebugUtils {
private static final LpDebugUtils ourInstance = new LpDebugUtils();
public static LpDebugUtils getInstance() {
return ourInstance;
}
private LpDebugUtils() {
}
/**
* 弹窗进入调试模式
*/
public void showInputDialog(final Context context, final X5WebView webView) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
View view = LayoutInflater.from(context).inflate(R.layout.layout_edit_alert_dialog, null);
final EditText mEditUrl = (EditText) view.findViewById(R.id.et_input_url);
View mBtCancel = view.findViewById(R.id.bt_cancel);
View mBtDefine = view.findViewById(R.id.bt_define);
builder.setView(view);
final AlertDialog alertDialog = builder.create();
mBtCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
YstenUtils.hideKeyBoard(context, mEditUrl);
}
});
mBtDefine.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
YstenUtils.hideKeyBoard(context, mEditUrl);
String htmlUrl = mEditUrl.getText().toString();
if (!TextUtils.isEmpty(htmlUrl) && !(htmlUrl.startsWith("http://") || htmlUrl.startsWith("https://"))) {
ToastUtil.showMessage(context, "url格式不正确");
return;
}
webView.loadUrl(htmlUrl);
}
});
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.setCancelable(false);
alertDialog.show();
Window dialogWindow = alertDialog.getWindow();
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
lp.height = YstenDensityUtils.dp2px(context, 300);
dialogWindow.setAttributes(lp);
}
}
| true |
3761dd5e623b89e1090880db3fad102f8bdf46dd | Java | imamsulthon/Movie-Check | /app/src/main/java/com/tassioauad/moviecheck/view/fragment/PersonWorkFragment.java | UTF-8 | 8,981 | 1.882813 | 2 | [
"Apache-2.0"
] | permissive | package com.tassioauad.moviecheck.view.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.tassioauad.moviecheck.MovieCheckApplication;
import com.tassioauad.moviecheck.R;
import com.tassioauad.moviecheck.dagger.PersonWorkViewModule;
import com.tassioauad.moviecheck.model.entity.Movie;
import com.tassioauad.moviecheck.model.entity.Person;
import com.tassioauad.moviecheck.presenter.PersonWorkPresenter;
import com.tassioauad.moviecheck.view.PersonWorkView;
import com.tassioauad.moviecheck.view.activity.MovieProfileActivity;
import com.tassioauad.moviecheck.view.adapter.MovieListAdapter;
import com.tassioauad.moviecheck.view.adapter.OnItemClickListener;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import butterknife.Bind;
import butterknife.ButterKnife;
public class PersonWorkFragment extends Fragment implements PersonWorkView {
@Inject
PersonWorkPresenter presenter;
private List<Movie> workAsCastList;
private List<Movie> workAsCrewList;
private Person person;
private static final String KEY_WORKASCREWLIST = "WORKASCREWLIST";
private static final String KEY_WORKASCASTLIST = "WORKASCASTLIST";
private static final String KEY_PERSON = "PERSON";
@Bind(R.id.recyclerview_cast)
RecyclerView recyclerViewCast;
@Bind(R.id.recyclerview_crew)
RecyclerView recyclerViewCrew;
@Bind(R.id.linearlayout_cast_anyfounded)
LinearLayout linearLayoutAnyCastFounded;
@Bind(R.id.linearlayout_cast_loadfailed)
LinearLayout linearLayoutCastLoadFailed;
@Bind(R.id.progressbar_cast)
ProgressBar progressBarCast;
@Bind(R.id.linearlayout_crew_anyfounded)
LinearLayout linearLayoutAnyCrewFounded;
@Bind(R.id.linearlayout_crew_loadfailed)
LinearLayout linearLayoutCrewLoadFailed;
@Bind(R.id.progressbar_crew)
ProgressBar progressBarCrew;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
((MovieCheckApplication) getActivity().getApplication())
.getObjectGraph().plus(new PersonWorkViewModule(this)).inject(this);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_personwork, container, false);
ButterKnife.bind(this, view);
person = getArguments().getParcelable(KEY_PERSON);
if (workAsCastList == null && savedInstanceState != null) {
workAsCastList = savedInstanceState.getParcelableArrayList(KEY_WORKASCASTLIST);
}
if (workAsCrewList == null && savedInstanceState != null){
workAsCrewList = savedInstanceState.getParcelableArrayList(KEY_WORKASCREWLIST);
}
if (workAsCastList == null) {
presenter.loadCastWorks(person);
} else if (workAsCastList.size() == 0) {
warnAnyWorkAsCastFounded();
} else {
showWorksAsCast(workAsCastList);
}
if (workAsCrewList == null) {
presenter.loadCrewWorks(person);
} else if (workAsCrewList.size() == 0) {
warnAnyWorkAsCrewFounded();
} else {
showWorksAsCrew(workAsCrewList);
}
return view;
}
@Override
public void onResume() {
super.onResume();
Tracker defaultTracker = ((MovieCheckApplication) getActivity().getApplication()).getDefaultTracker();
defaultTracker.setScreenName("Person Work Screen");
defaultTracker.send(new HitBuilders.ScreenViewBuilder().build());
}
@Override
public void onStop() {
presenter.stop();
super.onStop();
}
@Override
public void onSaveInstanceState(Bundle outState) {
if (workAsCrewList != null) {
outState.putParcelableArrayList(KEY_WORKASCREWLIST, new ArrayList<>(workAsCrewList));
}
if (workAsCastList != null) {
outState.putParcelableArrayList(KEY_WORKASCASTLIST, new ArrayList<>(workAsCastList));
}
}
public static PersonWorkFragment newInstance(Person person) {
Bundle args = new Bundle();
args.putParcelable(KEY_PERSON, person);
PersonWorkFragment fragment = new PersonWorkFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public void hideLoadingWorkAsCrew() {
progressBarCrew.setVisibility(View.GONE);
}
@Override
public void showLoadingWorkAsCrew() {
progressBarCrew.setVisibility(View.VISIBLE);
linearLayoutCrewLoadFailed.setVisibility(View.GONE);
linearLayoutAnyCrewFounded.setVisibility(View.GONE);
}
@Override
public void showWorksAsCrew(List<Movie> movieList) {
this.workAsCrewList = movieList;
linearLayoutCrewLoadFailed.setVisibility(View.GONE);
linearLayoutAnyCrewFounded.setVisibility(View.GONE);
recyclerViewCrew.setVisibility(View.VISIBLE);
recyclerViewCrew.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
recyclerViewCrew.setAdapter(new MovieListAdapter(movieList, new OnItemClickListener<Movie>() {
@Override
public void onClick(Movie movie, View view) {
startActivity(MovieProfileActivity.newIntent(getActivity(), movie), ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(), view.findViewById(R.id.imageview_poster), "moviePoster").toBundle());
}
@Override
public void onLongClick(Movie movie, View view) {
}
}));
}
@Override
public void warnAnyWorkAsCrewFounded() {
workAsCrewList = new ArrayList<>();
linearLayoutCrewLoadFailed.setVisibility(View.GONE);
linearLayoutAnyCrewFounded.setVisibility(View.VISIBLE);
recyclerViewCrew.setVisibility(View.GONE);
}
@Override
public void warnFailedToLoadWorkAsCrew() {
linearLayoutCrewLoadFailed.setVisibility(View.VISIBLE);
linearLayoutCrewLoadFailed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
presenter.loadCrewWorks(person);
}
});
linearLayoutAnyCrewFounded.setVisibility(View.GONE);
recyclerViewCrew.setVisibility(View.GONE);
}
@Override
public void hideLoadingWorkAsCast() {
progressBarCast.setVisibility(View.GONE);
}
@Override
public void showLoadingWorkAsCast() {
progressBarCast.setVisibility(View.VISIBLE);
linearLayoutCastLoadFailed.setVisibility(View.GONE);
linearLayoutAnyCastFounded.setVisibility(View.GONE);
}
@Override
public void showWorksAsCast(List<Movie> movieList) {
this.workAsCastList = movieList;
linearLayoutCastLoadFailed.setVisibility(View.GONE);
linearLayoutAnyCastFounded.setVisibility(View.GONE);
recyclerViewCast.setVisibility(View.VISIBLE);
recyclerViewCast.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.HORIZONTAL));
recyclerViewCast.setAdapter(new MovieListAdapter(movieList, new OnItemClickListener<Movie>() {
@Override
public void onClick(Movie movie, View view) {
startActivity(MovieProfileActivity.newIntent(getActivity(), movie), ActivityOptionsCompat.makeSceneTransitionAnimation(getActivity(), view.findViewById(R.id.imageview_poster), "moviePoster").toBundle());
}
@Override
public void onLongClick(Movie movie, View view) {
}
}));
}
@Override
public void warnAnyWorkAsCastFounded() {
workAsCastList = new ArrayList<>();
linearLayoutCastLoadFailed.setVisibility(View.GONE);
linearLayoutAnyCastFounded.setVisibility(View.VISIBLE);
recyclerViewCast.setVisibility(View.GONE);
}
@Override
public void warnFailedToLoadWorkAsCast() {
linearLayoutCastLoadFailed.setVisibility(View.VISIBLE);
linearLayoutCastLoadFailed.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
presenter.loadCastWorks(person);
}
});
linearLayoutAnyCastFounded.setVisibility(View.GONE);
recyclerViewCast.setVisibility(View.GONE);
}
}
| true |
a3b60fb762c07505ec231eea3da57b81005b6d32 | Java | d-tree-org/opensrp-client-chw-referral | /opensrp-chw-referral/src/test/java/org/smartregister/chw/referral/domain/ReferralServiceObjectTest.java | UTF-8 | 1,495 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | package org.smartregister.chw.referral.domain;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.smartregister.commonregistry.CommonPersonObjectClient;
/**
* Created by cozej4 on 2019-10-25.
*
* @cozej4 https://github.com/cozej4
*/
public class ReferralServiceObjectTest {
@Mock
private CommonPersonObjectClient service = Mockito.mock(CommonPersonObjectClient.class);
private ReferralServiceObject serviceMemberObject = new ReferralServiceObject(service);
@Test
public void getId() {
serviceMemberObject.setId("1");
Assert.assertEquals("1", serviceMemberObject.getId());
}
@Test
public void setId() {
serviceMemberObject.setId("2");
Assert.assertEquals("2", serviceMemberObject.getId());
}
@Test
public void getNameEn() {
serviceMemberObject.setNameEn("ANC");
Assert.assertEquals("ANC", serviceMemberObject.getNameEn());
}
@Test
public void getNameSw() {
serviceMemberObject.setNameSw("Wajawazito");
Assert.assertEquals("Wajawazito", serviceMemberObject.getNameSw());
}
@Test
public void isActive() {
serviceMemberObject.setActive(true);
Assert.assertTrue(serviceMemberObject.isActive());
}
@Test
public void getIdentifier() {
serviceMemberObject.setIdentifier("hiv");
Assert.assertEquals("hiv", serviceMemberObject.getIdentifier());
}
} | true |
494538d99829aa0a9710778d9c3892a55b1b9098 | Java | emilsbee/uni-code | /src/ss/week3/hotel/PricedSafe.java | UTF-8 | 1,296 | 3.03125 | 3 | [] | no_license | package ss.week3.hotel;
import ss.week3.bill.Bill;
import ss.week3.password.Password;
public class PricedSafe extends Safe implements Bill.Item {
private double price;
private Password password;
public PricedSafe(double price) {
this.price = price;
this.password = new Password();
}
public boolean activate(String testPassword) {
assert testPassword != null;
// assert password.testWord(testPassword) : "Bad password";
if (password.testWord(testPassword)) { // If password is valid
super.activate();
return true;
}
return false;
}
public Password getPassword() {
return this.password;
}
@Override
public void activate() {
System.out.println("You must provide a password to activate the safe.");
}
@Override
public double getAmount() {
return this.price;
}
public void open(String testPassword) {
assert testPassword != null;
if (password.testWord(testPassword) && super.active) { // If password is valid and safe is active
super.open();
}
}
@Override
public void open() {
}
@Override
public String toString() {
return String.valueOf(this.price);
}
}
| true |
a501dfc001b9b358d3ac1ac0cb4e06b9581f5b94 | Java | hys-github/huasan | /online_education_project/service/service_edu/src/main/java/com/hys/eduService/service/impl/EduVideoServiceImpl.java | UTF-8 | 2,049 | 2.171875 | 2 | [] | no_license | package com.hys.eduService.service.impl;
import com.hys.eduService.entity.PO.EduVideo;
import com.hys.eduService.mapper.EduVideoMapper;
import com.hys.eduService.remoteServer.VideoRemoteService;
import com.hys.eduService.service.EduVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hys.utils.ResultJsonToHtmlUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
/**
* <p>
* 课程视频 服务实现类
* </p>
*
* @author hys
* @since 2020-04-16
*/
@Service
@Slf4j
public class EduVideoServiceImpl extends ServiceImpl<EduVideoMapper, EduVideo> implements EduVideoService {
@Autowired
VideoRemoteService videoRemoteService;
/**
* @param videoId 节的主键id
*
* 删除节的操作,并通过节的id得到该节下的上传到阿里云上的唯一视频id
* 通过视频凭证id调用远端服务器删除阿里云上的视频
*/
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW,rollbackFor = Exception.class)
public ResultJsonToHtmlUtil<String> deleteVideoByVideoId(String videoId) {
EduVideo eduVideo = this.getById(videoId);
// 得到上传到阿里云上的唯一视频凭证id
String videoSourceId = eduVideo.getVideoSourceId();
// 调用远端服务器删除视频
if(videoSourceId!=null){
// 调用远端服务器接口
ResultJsonToHtmlUtil<String> resultUtil = videoRemoteService.deleteVideoToAliyunByVideoId(videoSourceId);
if(!resultUtil.isResult()){
log.info(resultUtil.getErrorMessage());
return resultUtil;
}
}
// 删除节信息
this.removeById(videoId);
return ResultJsonToHtmlUtil.successWithOutOfData();
}
}
| true |
8e79e074a3f40bd1f1fdb0f1701e59a304bbf560 | Java | kyro1214/Card-Game | /src/CardGame.java | UTF-8 | 1,561 | 3.484375 | 3 | [] | no_license | import java.util.Arrays;
import java.util.Scanner;
class CardGame {
int[] points, value, win;
int temp, index = 0;
void printDeck(){
Deck myDeck = new Deck();
Card c;
for(int x=0;x<56;x++){
c=myDeck.drawCard(x);
System.out.println(c.toString());
}
}
void Game(int numPlayers) {
String input;
Deck myDeck = new Deck();
Scanner myScanner = new Scanner(System.in);
Card c;
int x = 0;
int max, winner = 0;
win = new int[numPlayers];
points = new int[numPlayers];
while (winner == 0) {
temp = 0;
myDeck.shuffle();
value = new int[numPlayers];
for (x = 0; x < numPlayers; x++) {
System.out.print("Player " + (x + 1)
+ " press 'Enter' to draw a card");
input = myScanner.nextLine();
c = myDeck.drawCard(x);
System.out.println("You drew a: " + c.toString());
System.out.println("");
value[x] = c.getValue();
if (value[x] == 0)
points[x] = points[x] - 1;
if (value[x] > temp) {
temp = value[x];
index = x;
}
}
points[index] = points[index] + 2;
for (x = 0; x < numPlayers; x++) {
System.out.println("Player " + (x + 1) + " currrent score is "
+ points[x]);
}
win = points.clone();
Arrays.sort(win);
max = win[numPlayers - 1];
if ((win[numPlayers - 1] >= 5)
&& win[numPlayers - 1] >= (win[numPlayers - 2] + 2))
for (x = 0; x < numPlayers; x++) {
if (max == points[x])
winner = x + 1;
}
System.out.println("");
}
System.out.println("Player " + winner + " is the winner! Congrats!");
}
} | true |
3270ed07962896470aa74f1ebf25c82ffc011975 | Java | yattias/scy | /sources/modules/client/desktop/scy-desktop/src/main/java/eu/scy/client/desktop/scydesktop/elofactory/ScyToolCreatorRegistry.java | UTF-8 | 309 | 1.554688 | 2 | [] | no_license | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eu.scy.client.desktop.scydesktop.elofactory;
/**
*
* @author sikken
*/
public interface ScyToolCreatorRegistry
{
public void registerScyToolCreator(ScyToolCreator scyToolCreator, String id);
}
| true |
5367747f826c2e97f5fe1cce586d527aa4b0bb15 | Java | aartisoft/FortinDoctors | /app/src/main/java/com/doctor/app/NearByHospital.java | UTF-8 | 2,218 | 2.125 | 2 | [] | no_license | package com.doctor.app;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.doctor.app.adapter.DoctorAdapter;
import com.doctor.app.adapter.HospitalAdapter;
import com.doctor.app.helper.AppConst;
import com.doctor.app.model.DoctorPojo;
import com.doctor.app.model.HospitalPojo;
import java.util.ArrayList;
public class NearByHospital extends AppCompatActivity {
RecyclerView rv;
TextView tv;
Context context;
String TAG="NearByHospital";
// HospitalAdapter adapter;
DoctorAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_near_by_hospital);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
context=NearByHospital.this;
tv=(TextView)findViewById(R.id.tvnodata);
tv.setVisibility(View.GONE);
rv=(RecyclerView)findViewById(R.id.rvlist);
rv.setLayoutManager(new LinearLayoutManager(context));
rv.setHasFixedSize(true);
if (AppConst.hospitalPojoArrayList!=null){
ArrayList<DoctorPojo> list=AppConst.hospitalPojoArrayList;
if(list.size()>0){
tv.setVisibility(View.GONE);
rv.setVisibility(View.VISIBLE);
adapter=new DoctorAdapter(list,context,"doctor");
rv.setAdapter(adapter);
}else{
tv.setVisibility(View.VISIBLE);
rv.setVisibility(View.GONE);
}
}else{
tv.setVisibility(View.VISIBLE);
rv.setVisibility(View.GONE);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==android.R.id.home)
onBackPressed();
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
}
| true |
c28ccaa003694aec17fddcc580b4df527757cccd | Java | SudilHasitha/AutoMobileAssist | /app/src/main/java/com/example/automobileassist/Registaion_or_Login.java | UTF-8 | 1,548 | 1.921875 | 2 | [] | no_license | package com.example.automobileassist;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Registaion_or_Login extends AppCompatActivity {
Button btn1;
Button btn2;
Button btn3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_registaion_or__login);
btn1 = findViewById(R.id.button);
btn2 = findViewById(R.id.button2);
btn3 = findViewById(R.id.button8);
}
protected void onResume() {
super.onResume();
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Registaion_or_Login.this, Regtaion_form.class);
startActivity(intent);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Registaion_or_Login.this, Profile_ui.class);
startActivity(intent);
}
});
btn3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Registaion_or_Login.this,Login_Form.class);
startActivity(intent);
}
});
}
}
| true |
a850f5b8d74720568399354770c0e23500d71595 | Java | ypcthenry/platform | /business/business-user/src/main/java/org/whut/platform/business/user/mapper/AuthorityMapper.java | UTF-8 | 816 | 1.742188 | 2 | [] | no_license | package org.whut.platform.business.user.mapper;
import org.whut.platform.business.user.entity.Authority;
import org.whut.platform.fundamental.orm.mapper.AbstractMapper;
<<<<<<< HEAD
import java.util.List;
import java.util.Map;
=======
import java.util.Map;
import java.util.List;
>>>>>>> 23dd51744e660700d6196a2d52cb2394d49b9f1c
/**
* Created with IntelliJ IDEA.
* User: xiaozhujun
* Date: 14-3-16
* Time: 下午8:14
* To change this template use File | Settings | File Templates.
*/
public interface AuthorityMapper extends AbstractMapper<Authority> {
<<<<<<< HEAD
public List<Authority> findByCondition(Map<String,Object> map);
=======
public List<Authority> findByCondition(Map<String,Object> map);
public long getIdByName(String name);
>>>>>>> 23dd51744e660700d6196a2d52cb2394d49b9f1c
}
| true |
97c11e764c9d0c79297fa37add3e3173f32f2ab6 | Java | kromarong/SimpleNetworkChat | /SimpleChat/src/main/java/ru/kromarong/chatServer/auth/AuthServiceImpl.java | UTF-8 | 374 | 1.96875 | 2 | [] | no_license | package ru.kromarong.chatServer.auth;
import ru.kromarong.chatServer.ConnectToDB;
import java.sql.SQLException;
public class AuthServiceImpl implements AuthService {
public AuthServiceImpl() {
}
@Override
public boolean authUser(String username, String password) throws SQLException {
return ConnectToDB.findUser(username, password);
}
}
| true |
e0f326fe5c498e31b9385127ec6a3bb240387545 | Java | teamJnj/project | /jnj/src/main/java/com/icia/jnj/service/MarketService.java | UTF-8 | 15,862 | 2.203125 | 2 | [] | no_license | package com.icia.jnj.service;
import java.util.*;
import org.springframework.beans.factory.annotation.*;
import org.springframework.stereotype.*;
import com.icia.jnj.dao.*;
import com.icia.jnj.domain.*;
import com.icia.jnj.util.*;
import com.icia.jnj.vo.*;
@Service
public class MarketService {
@Autowired
private RecruitDao dao;
// 마켓 글 리스트
public Map<String, Object> listMarket(int pageno) {
int articleCnt = dao.getMarketCount();
Pagination pagination = PagingUtil.setPageMaker(pageno, articleCnt, 10);
Map<String, Object> map = new HashMap<String, Object>();
map.put("pagination", pagination);
map.put("list", dao.getAllPageMarket(pagination.getStartArticleNum(), pagination.getEndArticleNum()));
List<Market> list = dao.getAllPageMarket(pagination.getStartArticleNum(), pagination.getEndArticleNum());
for( int i=0; i<list.size(); i++) {
list.get(i).getMarketNo();
}
return map;
}
// @Transactional(rollbackFor=Exception.class)
// @PreAuthorize("isAuthenticated()")
public void insertMarket(Market market) {
dao.insertMarket(market);
}
// 마켓 글 뷰 화면
public Map<String, Object> viewMarket(int marketNo) {
List<MarketComment> MarketComment = dao.getMarketComment(marketNo);
List<MarketApply> MarketApply = dao.getMarketApplyList(marketNo);
dao.increasehits(marketNo);
Map<String, Object> map = new HashMap<String, Object>();
map.put("market", dao.getMarket(marketNo));
map.put("marketComment", MarketComment);
map.put("marketApply", MarketApply);
return map;
}
// 댓글 리스트
public Map<String, Object> listMarketComment(int pageno) {
int articleCnt = dao.getMarketCommentCount();
Pagination pagination = PagingUtil.setPageMaker(pageno, articleCnt, 10);
Map<String, Object> map = new HashMap<String, Object>();
map.put("pagination", pagination);
map.put("list", dao.getAllPageMarketComment(pagination.getStartArticleNum(), pagination.getEndArticleNum()));
return map;
}
// 마켓 글 뷰
public List<MarketComment> viewMarketComment(int marketNo) {
return dao.getMarketComment(marketNo);
}
// 마켓 글 댓글 작성
public List<MarketComment> insertMarketComment(MarketComment marketComment) {
dao.insertMarketComment(marketComment);
return dao.readReply(marketComment.getMarketNo());
}
// 마켓 글 댓글 리스트
public List<MarketComment> listMarketCommentReply(int marketNo) {
return dao.listRecentReply(marketNo);
}
// 마켓 신청
public void insertMarketApply(MarketApply marketApply) {
marketApply.setApplyTel(marketApply.getTel1()+marketApply.getTel2());
dao.insertMarketApply(marketApply);
dao.increaseApplyPeople(marketApply);
MarketComment marketcomment = new MarketComment();
marketcomment.setMarketNo(marketApply.getMarketNo());
marketcomment.setWriteId("-----");
marketcomment.setCommentContent(marketApply.getMemberId() + "님이 " + marketApply.getBoothNum() + "개의 부스를 신청하셨습니다.");
dao.insertMarketComment(marketcomment);
}
// 마켓 글 수정
public void updateMarket(Market market) {
dao.updateMarket(market);
}
// 마켓 글 마켓번호 불러오기
public Market getMarket(int marketNo) {
Market market = dao.getMarket(marketNo);
return market;
}
// 마켓 글 삭제 ( 프리마켓을 신청 한 회원이 있으면 신청 삭제하고 글 삭제)
public void deleteMarket(Market market) {
List<MarketApply> marketApplyList = dao.getMarketApplyList(market.getMarketNo());
// 쪽지 추가
// 신청 삭제
dao.deleteAllMarketApply(market.getMarketNo());
// 댓글 삭제
dao.deleteAllMarketComment(market.getMarketNo());
// 프리마켓 글 삭제
dao.deleteMarket(market.getMarketNo());
}
// 댓글 마켓번호 불러오기
public List<MarketComment> getMarketComment(int marketNo) {
List<MarketComment> marketComment = dao.getMarketComment(marketNo);
return marketComment;
}
// 댓글 수정
public boolean updateMarketComment(MarketComment marketComment) {
return dao.updateMarketComment(marketComment)==1? true: false;
}
// 댓글 삭제
public boolean deleteMarketComment(MarketComment marketComment) {
return dao.deleteMarketComment(marketComment.getMarketNo(), marketComment.getMarketCommentNo())==1? true: false;
}
// 프리마켓 신청 취소
public boolean deleteMarketApply(MarketApply marketApply) {
int boothNum = dao.getBoothNum(marketApply.getMarketNo(), marketApply.getMemberId());
marketApply.setBoothNum(boothNum);
MarketComment marketcomment = new MarketComment();
marketcomment.setMarketNo(marketApply.getMarketNo());
marketcomment.setWriteId("-----");
marketcomment.setCommentContent(marketApply.getMemberId() + "님이 " + marketApply.getBoothNum() + "개의 부스를 취소하셨습니다.");
dao.insertMarketComment(marketcomment);
dao.decreaseApplyPeople(marketApply);
return dao.deleteMarketApply(marketApply.getMarketNo(), marketApply.getMemberId())==1? true: false;
}
// 수현
// 일반회원 프리마켓 리스트
public Map<String, Object> getMemberMarketList(String memberId, int pageNo) {
Pagination pagination = PagingUtil.setPageMaker(pageNo, dao.getgetMemberMarketCnt(memberId), 10);
Map<String, Object> map = new HashMap<String, Object>();
map.put("mMarketList", dao.getMemberMarketList(memberId, pagination.getStartArticleNum(), pagination.getEndArticleNum()));
map.put("pagination", pagination);
return map;
}
// 주리 ==============================================================================================
// 해당 회원 후원 내역 리스트 조회( 페이지네이션, 정렬, 후원 총금액 추가 )
public Map<String, Object> getMemberMarketAllList( AdMMarketInfo info ){
// 검색 내용이 있는지 판단하고 있다면 검색내용을 spl문에 쓸 수 있게 바꿔서 셋팅
// 없을때는 기본셋팅으로
info.setSqlText("");
if( !info.getSearchText().equals("%") ) {
if( info.getSearchColName().equals("marketTitle"))
info.setSqlText("where marketTitle like '%"+info.getSearchText()+"%'");
else if( info.getSearchColName().equals("boothNum") )
info.setSqlText("where boothNum like '%"+info.getSearchText()+"%'");
else if( info.getSearchColName().equals("marketApplyState"))
info.setSqlText("where marketApplyState like '%"+info.getSearchText()+"%'");
else if( info.getSearchColName().equals("petState") )
info.setSqlText("where petState like '%"+info.getSearchText()+"%'");
}
else {
if( info.getSearchColName().equals("payMoney"))
info.setSqlText( "where payMoney>="+ info.getStartMoney()+" and payMoney<= "+info.getEndMoney() );
else if( info.getSearchColName().equals("applyDate"))
info.setSqlText( "where to_date(applyDate, 'yyyyMMdd')>=to_date("+ info.getStartDate()+", 'yyyyMMdd') and to_date(applyDate, 'yyyyMMdd')<= to_date("+info.getEndDate()+", 'yyyyMMdd')" );
else if( info.getSearchColName().equals("marketDate"))
info.setSqlText( "where to_date(marketDate, 'yyyyMMdd')>=to_date("+ info.getStartDate()+", 'yyyyMMdd') and to_date(marketDate, 'yyyyMMdd')<= to_date("+info.getEndDate()+", 'yyyyMMdd')" );
}
int articleCnt = dao.getCountMemberMarketList(info);
Pagination pagination = PagingUtil.setPageMaker(info.getPageno(), articleCnt, 10);
info.setStartArticleNum(pagination.getStartArticleNum());
info.setEndArticleNum(pagination.getEndArticleNum());
Map<String, Object> map=new HashMap<String, Object>();
map.put("pagination", pagination);
map.put("memberMarketList", dao.getMemberMarketList( info ));
map.put("stateCount", dao.getMemberTotalMarketApplyState(info.getMemberId()) );
return map;
}
// 주리
// ==============================================================================================
// 해당 회원 후원 내역 리스트 조회( 페이지네이션, 정렬, 후원 총금액 추가 )
public Map<String, Object> getMemberMarketList(AdMMarketInfo info) {
// 검색 내용이 있는지 판단하고 있다면 검색내용을 spl문에 쓸 수 있게 바꿔서 셋팅
// 없을때는 기본셋팅으로
info.setSqlText("");
if (!info.getSearchText().equals("%")) {
if (info.getSearchColName().equals("marketTitle"))
info.setSqlText("where marketTitle like '%" + info.getSearchText() + "%'");
else if (info.getSearchColName().equals("boothNum"))
info.setSqlText("where boothNum like '%" + info.getSearchText() + "%'");
else if (info.getSearchColName().equals("marketState"))
info.setSqlText("where marketApplyState like '%" + info.getSearchText() + "%'");
else if (info.getSearchColName().equals("petState"))
info.setSqlText("where petState like '%" + info.getSearchText() + "%'");
} else {
if (info.getSearchColName().equals("payMoney"))
info.setSqlText("where payMoney>=" + info.getStartMoney() + " and payMoney<= " + info.getEndMoney());
else if (info.getSearchColName().equals("applyDate"))
info.setSqlText("where to_date(applyDate, 'yyyyMMdd')>=to_date(" + info.getStartDate()
+ ", 'yyyyMMdd') and to_date(applyDate, 'yyyyMMdd')<= to_date(" + info.getEndDate()
+ ", 'yyyyMMdd')");
else if (info.getSearchColName().equals("marketDate"))
info.setSqlText("where to_date(marketDate, 'yyyyMMdd')>=to_date(" + info.getStartDate()
+ ", 'yyyyMMdd') and to_date(marketDate, 'yyyyMMdd')<= to_date(" + info.getEndDate()
+ ", 'yyyyMMdd')");
}
int articleCnt = dao.getCountMemberMarketList(info);
Pagination pagination = PagingUtil.setPageMaker(info.getPageno(), articleCnt, 10);
info.setStartArticleNum(pagination.getStartArticleNum());
info.setEndArticleNum(pagination.getEndArticleNum());
Map<String, Object> map = new HashMap<String, Object>();
map.put("pagination", pagination);
map.put("memberMarketList", dao.getMemberMarketList(info));
return map;
}
public void updateMarketApplyState(int marketNo, String memberId, int marketApplyState, String num) {
// 프리마켓 글에 신청 인원수를 줄인다.
dao.updateMarketApplyPeople(marketNo, num);
// 프리마켓 신청 상태를 취소로 만든다.
dao.updateMarketApply(marketNo, memberId, marketApplyState);
}
// 마켓 댓글 리스트 보기
public Map<String, Object> getMemberMarketCommentList(AdMMarketCommentInfo info) {
info.setSqlText("");
if (!info.getSearchText().equals("%")) {
if (info.getSearchColName().equals("marketTitle"))
info.setSqlText("where marketTitle like '%" + info.getSearchText() + "%'");
else if (info.getSearchColName().equals("commentContent"))
info.setSqlText("where commentContent like '%" + info.getSearchText() + "%'");
} else {
if (info.getSearchColName().equals("writeDate"))
info.setSqlText("where to_date(writeDate, 'yyyyMMdd')>=to_date(" + info.getStartDate()
+ ", 'yyyyMMdd') and to_date(writeDate, 'yyyyMMdd')<= to_date(" + info.getEndDate()
+ ", 'yyyyMMdd')");
}
int articleCnt = dao.getCountMemberMarketCommentList(info);
Pagination pagination = PagingUtil.setPageMaker(info.getPageno(), articleCnt, 10);
info.setStartArticleNum(pagination.getStartArticleNum());
info.setEndArticleNum(pagination.getEndArticleNum());
Map<String, Object> map = new HashMap<String, Object>();
map.put("pagination", pagination);
map.put("memberMarketCommentList", dao.getMemberMarketCommentList(info));
return map;
}
public Map<String, Object> marketPay(String memberId, int marketNo) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("market", dao.getMarket(marketNo));
map.put("marketApply", dao.marketPay(memberId, marketNo));
return map;
}
public Map<String, Object> getTotalMarketList(AdMarketInfo info) {
// 검색 내용이 있는지 판단하고 있다면 검색내용을 spl문에 쓸 수 있게 바꿔서 셋팅
// 없을때는 기본셋팅으로
info.setSqlText("");
if (!info.getSearchText().equals("%")) {
if (info.getSearchColName().equals("marketTitle"))
info.setSqlText("where marketTitle like '%" + info.getSearchText() + "%'");
else if (info.getSearchColName().equals("marketState"))
info.setSqlText("where marketState like '%" + info.getSearchText() + "%'");
} else {
if (info.getSearchColName().equals("marketDate"))
info.setSqlText("where to_date(marketDate, 'yyyyMMdd')>=to_date(" + info.getStartDate()
+ ", 'yyyyMMdd') and to_date(marketDate, 'yyyyMMdd')<= to_date(" + info.getEndDate()
+ ", 'yyyyMMdd')");
}
int articleCnt = dao.getCountTotalMarketList(info);
Pagination pagination = PagingUtil.setPageMaker(info.getPageno(), articleCnt, 10);
info.setStartArticleNum(pagination.getStartArticleNum());
info.setEndArticleNum(pagination.getEndArticleNum());
Map<String, Object> map = new HashMap<String, Object>();
map.put("pagination", pagination);
map.put("memberMarketList", dao.getTotalMarketList(info));
map.put("stateCount", dao.getTotalMarketApplyState());
return map;
}
public Map<String, Object> getTotalMarketApplyList(AdMarketApplyInfo info) {
// 검색 내용이 있는지 판단하고 있다면 검색내용을 spl문에 쓸 수 있게 바꿔서 셋팅
// 없을때는 기본셋팅으로
info.setSqlText("");
if (!info.getSearchText().equals("%")) {
if (info.getSearchColName().equals("marketTitle"))
info.setSqlText("where marketTitle like '%" + info.getSearchText() + "%'");
if (info.getSearchColName().equals("marketNo"))
info.setSqlText("where marketNo like '%" + info.getSearchText() + "%'");
else if (info.getSearchColName().equals("memberId"))
info.setSqlText("where memberId like '%" + info.getSearchText() + "%'");
else if (info.getSearchColName().equals("applyTel"))
info.setSqlText("where applyTel like '%" + info.getSearchText() + "%'");
else if (info.getSearchColName().equals("boothNum"))
info.setSqlText("where boothNum like '%" + info.getSearchText() + "%'");
else if (info.getSearchColName().equals("marketApplyState"))
info.setSqlText("where marketApplyState like '%" + info.getSearchText() + "%'");
} else {
if (info.getSearchColName().equals("payMoney"))
info.setSqlText("where payMoney>=" + info.getStartMoney() + " and payMoney<= " + info.getEndMoney());
else if (info.getSearchColName().equals("applyDate"))
info.setSqlText("where to_date(applyDate, 'yyyyMMdd')>=to_date(" + info.getStartDate()
+ ", 'yyyyMMdd') and to_date(applyDate, 'yyyyMMdd')<= to_date(" + info.getEndDate()
+ ", 'yyyyMMdd')");
else if (info.getSearchColName().equals("marketDate"))
info.setSqlText("where to_date(marketDate, 'yyyyMMdd')>=to_date(" + info.getStartDate()
+ ", 'yyyyMMdd') and to_date(marketDate, 'yyyyMMdd')<= to_date(" + info.getEndDate()
+ ", 'yyyyMMdd')");
}
int articleCnt = dao.getCountTotalMarketApplyList(info);
Pagination pagination = PagingUtil.setPageMaker(info.getPageno(), articleCnt, 10);
info.setStartArticleNum(pagination.getStartArticleNum());
info.setEndArticleNum(pagination.getEndArticleNum());
Map<String, Object> map = new HashMap<String, Object>();
map.put("pagination", pagination);
map.put("memberMarketApplyList", dao.getTotalMarketApplyList(info));
map.put("stateCount", dao.getMarketApplyState());
return map;
}
} | true |
67ea9d862c1720295750ce1e7b82522ddba2fe4c | Java | Qilowa/Pokemon | /src/dut/fr/pokemon/Capacitylist.java | UTF-8 | 1,940 | 3.171875 | 3 | [] | no_license | package dut.fr.pokemon;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import dut.fr.type.Type;
/**
*
* Class containing the Capacity
*/
public class Capacitylist {
private static final String CSV ="./RessourcesPokemon-20191205/Capacity.csv";
private static ArrayList<Capacity> capacity;
private static Capacitylist onlyInstance;
private Capacitylist() {
capacity = new ArrayList<Capacity>();
}
private static void createCapacitylist() {
String line;
boolean nameField = false;
try {
BufferedReader reader = new BufferedReader(new FileReader(CSV));
while ((line = reader.readLine()) != null) {
if (nameField == false) {
nameField = true;
continue;
}
Capacity c = Capacity.createCapacity(line);
capacity.add(c);
}
}catch (IOException e) {
e.printStackTrace();
}
}
/**
* Return the capacities that has the same type as types
* @param types Array of type
* @return ArrayList
*/
public static ArrayList<Capacity> capacitychoice(Type[] types) {
ArrayList<Capacity> capacityFinal = new ArrayList<Capacity>();
for(int i = 0; i < capacity.size(); i++){
if (capacity.get(i).getType()==types[0] || capacity.get(i).getType()==types[1] || capacity.get(i).getType()==Type.NORMAL) {
Capacity cap=capacity.get(i);
capacityFinal.add(cap);
}
}
return capacityFinal;
}
public static Capacitylist getInstance() {
if (capacity == null) {
onlyInstance = new Capacitylist();
Capacitylist.createCapacitylist();
}
return onlyInstance;
}
/**
* Return a capacity according to the id
* @param id Integer representing the id of a capacity
* @return Capacity
*/
public Capacity getCapacity(int id) {
Capacity c = capacity.get(id);
return c;
}
@Override
public String toString() {
return capacity.toString();
}
}
| true |
4ca9b171ffeeeb232d9e15a3e62809907ca26518 | Java | pentasoft/s3-static-uploader | /s3-static-uploader-plugin/src/main/java/io/pst/mojo/s3/sta/uploader/config/IncludedFilesListBuilder.java | UTF-8 | 1,670 | 2.28125 | 2 | [
"BSD-2-Clause"
] | permissive | package io.pst.mojo.s3.sta.uploader.config;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class IncludedFilesListBuilder extends AbstractFilesListBuilder {
private final List<Include> includes;
private final ConstrainedFilesListBuilder constrainedFilesListBuilder;
public IncludedFilesListBuilder(File inputDirectory, List<Include> includes, List<String> excludes, List<Metadata> metadatas) {
super(inputDirectory, excludes, metadatas);
this.includes = includes;
this.constrainedFilesListBuilder = new ConstrainedFilesListBuilder(inputDirectory, excludes, metadatas);
}
public List<ManagedFile> build() throws IOException {
for (Include include : includes) {
collectIncludedFiles(include);
replaceConstrainedFiles(include);
}
return new ArrayList<ManagedFile>(fileMap.values());
}
private void collectIncludedFiles(Include include) throws IOException {
List<String> includedFileNames = getMatchingFilesNames(include.getBind().getPattern());
for (String fileName : includedFileNames) {
ManagedFile managedFile = new ManagedFile(fileName, getMetadata(include.getBind()));
fileMap.put(fileName, managedFile);
}
}
private void replaceConstrainedFiles(Include include) throws IOException {
List<ManagedFile> constrainedFiles = constrainedFilesListBuilder.build(include);
for (ManagedFile managedFile : constrainedFiles) {
fileMap.put(managedFile.getFilename(), managedFile);
}
}
}
| true |
fbf9c45247c906bac669a9a1037d4330edba4d3d | Java | yilin6867/CMPT220-Lin | /labs/8/Problem11_3.java | UTF-8 | 381 | 2.953125 | 3 | [] | no_license | // JA: This class does not compile
public class Problem11_3 {
public static void main(String[] args) {
Account acc = new Account(123456789, 1000);
CheckingAccount chAcc = new CheckingAccount(987654321, 10000);
SavingsAccount savAcc = new SavingsAccount(147258369, 100000);
System.out.println(acc.toString() + "\n\n" + chAcc.toString() + "\n\n" + savAcc.toString());
}
}
| true |
907b5c77adbc1a16475658d6e28766c8c11f7e9f | Java | thomashuang2017/TetrisWorking | /Piece.java | BIG5 | 7,091 | 2.765625 | 3 | [] | no_license | import java.awt.*;
import javax.swing.*;
class Piece {
// 0 1 2 3
// 4 5 6 7
// 8 9 10 11
// 12 13 14 15
//
// i%4 --> x, i/4 --> y
// x+y*4 --> i
private static int[] shapeI_0= new int[] {
0, 0, 0, 0,
1, 1, 1, 1,
0, 0, 0, 0,
0, 0, 0, 0,
}; //16O] ܧγ|b16椤ܤ
private static int[] shapeI_1= new int[] {
0, 1, 0, 0,
0, 1, 0, 0,
0, 1, 0, 0,
0, 1, 0, 0,
};
private static int[] shapeS_0= new int[] {
0, 1, 1, 0,
1, 1, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0,
};
private static int[] shapeS_1= new int[] {
1, 0, 0, 0,
1, 1, 0, 0,
0, 1, 0, 0,
0, 0, 0, 0,
};
private static int[] shapeZ_0= new int[] {
1, 1, 0, 0,
0, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
private static int[] shapeZ_1= new int[] {
0, 1, 0, 0,
1, 1, 0, 0,
1, 0, 0, 0,
0, 0, 0, 0
};
private static int[] shapeG_0= new int[] { // Gamma , L
0, 1, 0, 0,
0, 1, 0, 0,
1, 1, 0, 0,
0, 0, 0, 0
};
private static int[] shapeG_1= new int[] {
1, 0, 0, 0,
1, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
private static int[] shapeG_2= new int[] {
1, 1, 0, 0,
1, 0, 0, 0,
1, 0, 0, 0,
0, 0, 0, 0
};
private static int[] shapeG_3= new int[] {
1, 1, 1, 0,
0, 0, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
private static int[] shapeO_0= new int[] {
1, 1, 0, 0,
1, 1, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
private static int[] shapeL_0= new int[] {
1, 0, 0, 0,
1, 0, 0, 0,
1, 1, 0, 0,
0, 0, 0, 0
};
private static int[] shapeL_1= new int[] {
1, 1, 1, 0,
1, 0, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
private static int[] shapeL_2= new int[] {
1, 1, 0, 0,
0, 1, 0, 0,
0, 1, 0, 0,
0, 0, 0, 0
};
private static int[] shapeL_3= new int[] {
0, 0, 1, 0,
1, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
private static int[] shapeT_0= new int[] {
0, 1, 0, 0,
1, 1, 1, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
private static int[] shapeT_1= new int[] {
0, 1, 0, 0,
1, 1, 0, 0,
0, 1, 0, 0,
0, 0, 0, 0
};
private static int[] shapeT_2= new int[] {
1, 1, 1, 0,
0, 1, 0, 0,
0, 0, 0, 0,
0, 0, 0, 0
};
private static int[] shapeT_3= new int[] {
0, 1, 0, 0,
0, 1, 1, 0,
0, 1, 0, 0,
0, 0, 0, 0
};
private static int[][][] shapes= new int[][][] {
{ shapeI_0, shapeI_1, shapeI_0, shapeI_1 },
{ shapeS_0, shapeS_1, shapeS_0, shapeS_1 },
{ shapeZ_0, shapeZ_1, shapeZ_0, shapeZ_1 },
{ shapeG_0, shapeG_1, shapeG_2, shapeG_3 },
{ shapeO_0, shapeO_0, shapeO_0, shapeO_0 },
{ shapeL_0, shapeL_1, shapeL_2, shapeL_3 },
{ shapeT_0, shapeT_1, shapeT_2, shapeT_3 }
};
//static int blockType, turnState; //: b4 A6.004.D
private int blockType, turnState;
private int posX, posY;
Piece(int bt) {
this.blockType=bt; this.turnState=0;
this.posX=0; this.posY=0;
}
void setPos00() {
this.posX=0; this.posY=0;
}
void setPos40() {
this.posX=4; this.posY=0;
}
static void paintCell(
Graphics g, int blockType, int winX, int winY
) {
g.drawImage(Map.color[blockType], winX, winY, null);
}
// static void paintPiece(
// Graphics g, int baseX, int baseY,
// int blockType, int turnState, int posX, int posY) {
void paintPiece(
Graphics g, int baseX, int baseY
//int posX, int posY
) {
// for(int i = 0; i < 16; i++) {
// if(Piece.shapes[this.blockType][this.turnState][i] == 1) {
// Piece.paintCell(
// g, this.blockType,
// (i%4+posX)*33+3+baseX, (i/4+posY)*33+3+baseY
// );
// }
// }
for(int x= 0; x<4; x++) {
for(int y= 0; y<4; y++) {
if(Piece.shapes[this.blockType][this.turnState][y*4+x] == 1) {
Piece.paintCell(
g, this.blockType,
(x+posX)*33+3+baseX, (y+posY)*33+3+baseY
);
}
}
}
}
// this.posX, this.posY,
// this.blockType, this.turnState
// // public boolean blow(int x, int y, int type, int state) {
// public boolean blow() {
public boolean free() { //: not collision
for(int x= 0; x<4; x++) {
for(int y= 0; y<4; y++) {
//for(int i = 0; i < 16; i++) {
if(Piece.shapes[this.blockType][this.turnState][y*4+x] == 1) {
//if(this.posX+i%4 >= 10 || this.posY+i/4 >= 20
// || this.posX+i%4 < 0 || this.posY+i/4 < 0)
if(TetrisPanel.map.indexOutside(this.posX+x,this.posY+y))
return false;
//if(Map.map[this.posX+i%4][this.posY+i/4] != 0)
if(TetrisPanel.map.cellEmpty(this.posX+x,this.posY+y))
return false;
}
}
}
return true;
}
public void rotate() {
int oldState = this.turnState;
this.turnState = (oldState+1)%4;
if(this.free()) {
;
}
else {
this.turnState = oldState;
}
//repaint();
}
public boolean r_shift() {
boolean canShift = false;
int oldPosX= this.posX;
this.posX++;
if(this.free()) {
//this.movingPiece.posX++;
canShift = true;
}
else {
this.posX= oldPosX;
}
//repaint();
return canShift;
}
public boolean l_shift() {
boolean canShift = false;
int oldPosX= this.posX;
this.posX--;
if(this.free()) {
canShift = true;
}
else{
this.posX= oldPosX;
}
//repaint();
return canShift;
}
public boolean down_shift() {
int oldY= this.posY;
this.posY++;
boolean canDown = this.free();
if(canDown) {
;
}
else {
this.posY= oldY;
//stopDown();
}
//repaint();
return canDown;
}
//void setBlock(int x, int y, int type, int state) {
void plugPiece() {
//this.notFalling = true;
for(int x= 0; x<4; x++) {
for(int y= 0; y<4; y++) {
//for(int i = 0; i < 16; i++) {
if(Piece.shapes[this.blockType][this.turnState][y*4+x] == 1) {
// TetrisPanel.map.array2D[this.posX+i%4][this.posY+i/4]
// = this.blockType+1;
TetrisPanel.map.setCell(this.posX+x,this.posY+y,this.blockType+1);
}
}
}
}
} | true |
c9fac9894c08d2321219542d001c6bc27a58cd3e | Java | googleapis/java-spanner | /samples/snippets/src/main/java/com/example/spanner/GetDatabaseDdlSample.java | UTF-8 | 1,768 | 2.328125 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright 2021 Google LLC
*
* 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.example.spanner;
//[START spanner_get_database_ddl]
import com.google.cloud.spanner.DatabaseAdminClient;
import com.google.cloud.spanner.Spanner;
import com.google.cloud.spanner.SpannerOptions;
import java.util.List;
public class GetDatabaseDdlSample {
static void getDatabaseDdl() {
// TODO(developer): Replace these variables before running the sample.
final String projectId = "my-project";
final String instanceId = "my-instance";
final String databaseId = "my-database";
getDatabaseDdl(projectId, instanceId, databaseId);
}
static void getDatabaseDdl(
String projectId, String instanceId, String databaseId) {
try (Spanner spanner = SpannerOptions
.newBuilder()
.setProjectId(projectId)
.build()
.getService()) {
final DatabaseAdminClient databaseAdminClient = spanner.getDatabaseAdminClient();
final List<String> ddls = databaseAdminClient.getDatabaseDdl(instanceId, databaseId);
System.out.println("Retrieved database DDL for " + databaseId);
for (String ddl : ddls) {
System.out.println(ddl);
}
}
}
}
//[END spanner_get_database_ddl]
| true |
6cbc5dc74493bdc8e788bed07a90862d8b645977 | Java | Grobbo/VSA_BSC | /src/Runner.java | UTF-8 | 617 | 2.359375 | 2 | [] | no_license | import java.io.IOException;
public class Runner {
public static void main(String Args[]) throws IOException{
AEM aem = new AEM(true);
EM em = new EM(true);
EB eb = new EB();
PU pu = new PU(aem,em);
Sign s1 = eb.createSignBasicEncoding(HDVECTOR.Cb, HDVECTOR.Sb, HDVECTOR.Tr, HDVECTOR.Cr);
Sign s2 = eb.createSignBasicEncoding(HDVECTOR.Sb, HDVECTOR.Tb, HDVECTOR.Cr, HDVECTOR.Cb);
pu.SaveEncodingAndDirectionToExp(s1, DIR.RIGHT);
//em.savePersistent();
//aem.savePersistent();
System.out.println(pu.checkForBestMatch(s1, s2));
System.out.println(pu.checkForBestMatch(s2, s1));
}
}
| true |
5b8a9350abfb946af078df0e221c4ccfa8d70271 | Java | hpx2206/metaworks3 | /SportIt/ProcessCodi_metaworks3/src/org/uengine/codi/mw3/admin/ClassMethod.java | UTF-8 | 4,739 | 2.328125 | 2 | [] | no_license |
package org.uengine.codi.mw3.admin;
import java.util.ArrayList;
import java.util.Date;
import org.metaworks.ContextAware;
import org.metaworks.MetaworksContext;
import org.metaworks.annotation.AutowiredFromClient;
import org.metaworks.annotation.Face;
import org.metaworks.annotation.Hidden;
import org.metaworks.annotation.Id;
import org.metaworks.annotation.Range;
import org.metaworks.annotation.ServiceMethod;
import org.metaworks.example.ide.SourceCode;
import org.metaworks.website.MetaworksFile;
public class ClassMethod implements Cloneable, ContextAware{
public ClassMethod(){
}
String methodName;
@Id // TODO: lesson 1 (object addressing and correlation)
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
String returnType;
public String getReturnType() {
return returnType;
}
public void setReturnType(String returnType) {
this.returnType = returnType;
}
@ServiceMethod(when=MetaworksContext.WHEN_EDIT, where="newEntry", callByContent=true)
public ClassModeler add() throws Exception{
if(classModeler.classMethods==null)
classModeler.classMethods = new ArrayList<ClassMethod>();//new FormField[]{};
//TODO: lesson 3 (validation with throwing exception)
if(classModeler.classFields.contains(this))
throw new Exception("There's already existing method named '" + getMethodName() + "'.");
ClassMethod clonedOne = (ClassMethod) this.clone(); //TODO: lesson 2 (cloning to avoid reflective problem)
clonedOne.setMetaworksContext(new MetaworksContext()); //TODO: lesson 4 (context injection)
clonedOne.getMetaworksContext().setWhere("in-container");
classModeler.classMethods.add(clonedOne);
//clear the entries for newFormField //TODO: lesson 6 (context clearing)
classModeler.init();
//
return classModeler;
}
@ServiceMethod(when=MetaworksContext.WHEN_EDIT, where="in-container", callByContent=true)
public ClassModeler save() throws Exception{
//TODO: lesson 3 (validation with throwing exception)
int index = classModeler.classFields.indexOf(this);
if(index==-1)
throw new Exception("There's no existing method named '" + getMethodName() + "'.");
classModeler.classMethods.remove(this);
ClassMethod clonedOne = (ClassMethod) this.clone(); //TODO: lesson 2 (cloning to avoid reflective problem)
classModeler.classMethods.add(index, clonedOne);
clonedOne.getMetaworksContext().setWhen(MetaworksContext.WHEN_VIEW);
return classModeler;
}
@ServiceMethod(when=MetaworksContext.WHEN_VIEW, where="in-container")
public ClassModeler remove(){
classModeler.classFields.remove(this);
return classModeler;
}
//TODO: quiz 2 (when the form field is first order, this button should be shown.
// Improve 'up' method and 'down' method not to be shown when it is in the first order and in the last order.
@ServiceMethod(when=MetaworksContext.WHEN_VIEW, where="in-container")
public ClassModeler up(){
int index = classModeler.classMethods.indexOf(this);
if(index>0){
classModeler.classMethods.remove(this);
//TODO: quiz 1 (below is not proper since it will clear the type information. Prove why and fix this)
classModeler.classMethods.add(index-1, this);
}
return classModeler;
}
@ServiceMethod(when=MetaworksContext.WHEN_VIEW, where="in-container")
public ClassModeler down(){
int index = classModeler.classMethods.indexOf(this);
if(index<classModeler.classFields.size()-1){
classModeler.classMethods.remove(this); //TODO: lesson 1 (object addressing and correlation)
//TODO: quiz 1 (below is not proper since it will clear the type information. Prove why and fix this)
classModeler.classMethods.add(index+1, this);
}
return classModeler;
}
@Override //TODO: lesson 1 (object addressing and correlation)
public boolean equals(Object obj) {
if(obj==null) return false;
String thisFieldName = this.getMethodName();
String comparatorFieldName = ((ClassMethod)obj).getMethodName();
return thisFieldName.equals(comparatorFieldName);
}
@Override
public Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
@AutowiredFromClient //TODO: lesson 0 (auto-wiring client-side objects)
transient public ClassModeler classModeler;
///// context ////// TODO: lesson 4 (context injection)
transient MetaworksContext metaworksContext;
public MetaworksContext getMetaworksContext() {
return metaworksContext;
}
public void setMetaworksContext(MetaworksContext metaworksContext) {
this.metaworksContext = metaworksContext;
}
}
| true |
3c0d1f4f542d0cdcc1b1997355487ac2b9ded91a | Java | SafiulHaque/TeacherManagement | /src/main/java/com/safi/TeacherManagement/Services/TeacherService.java | UTF-8 | 1,794 | 2.734375 | 3 | [] | no_license | package com.safi.TeacherManagement.Services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import com.safi.TeacherManagement.Models.Teacher;
import com.safi.TeacherManagement.Repositories.TeacherRepository;
@Component
public class TeacherService implements MethodContainer {
@Autowired
TeacherRepository repo;
@Override
public Teacher addNewTeacher(@RequestBody Teacher teacher) {
// TODO Auto-generated method stub
// return null;
Teacher current_teacher=repo.save(teacher);
int highest_id=current_teacher.gettId();
System.out.println("Highest Id => "+highest_id);
return teacher;
}
@Override
public Teacher showOneTeacherDetails(int tid) {
// TODO Auto-generated method stub
// return null;
Teacher teacher=repo.findById(tid).orElse(new Teacher());
return teacher;
}
@Override
public String remove(int tid) {
// TODO Auto-generated method stub
// return null;
try {
Teacher t=repo.getOne(tid);
repo.delete(t);
return "Teacher \n"+t+"\nDeleted Successfully";
}
catch(Exception e) {
return "Excception -> "+e.getMessage();
}
}
@Override
public String showAllTeachers() {
// TODO Auto-generated method stub
// return null;
List<Teacher> teachers=repo.findAll();
List<String> names=new ArrayList<>();
teachers.forEach((t)->names.add(t.getName()));
List<String> subjects=new ArrayList<>();
teachers.forEach((t)->subjects.add(t.getSubject()));
return names+"\n"+subjects;
}
@Override
public String totalCount() {
// TODO Auto-generated method stub
// return null;
long c=repo.count();
return "Total Number Of Teachers : "+c;
}
}
| true |
6100bdfa186926c1ce9e1df9052437fc25437a9a | Java | svensemilia/imagelink-android | /app/src/main/java/de/scit/imagelink/state/StateListener.java | UTF-8 | 2,316 | 2.25 | 2 | [] | no_license | package de.scit.imagelink.state;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.Switch;
import android.widget.TextView;
import de.scit.imagelink.R;
import de.scit.imagelink.rest.ImageRestApi;
public class StateListener {
private boolean isServerRunning;
private boolean isApiOnline;
private View serverButton;
private View apiButton;
private Switch switchView;
private TextView tv;
private Context ctx;
public StateListener(Context ctx, View serverButton, View apiButton, Switch switchV, TextView tv) {
this.serverButton = serverButton;
this.apiButton = apiButton;
this.switchView = switchV;
this.tv = tv;
this.ctx = ctx;
}
public void setServerRunning(boolean isServerRunning, String ip) {
if (this.isServerRunning != isServerRunning) {
refreshServerButton(isServerRunning);
}
this.isServerRunning = isServerRunning;
if (!switchView.isEnabled()) {
switchView.setEnabled(true);
}
if (isServerRunning != switchView.isChecked()) {
switchView.setChecked(!switchView.isChecked());
}
if (isServerRunning && ip != null) {
tv.setText(ip);
ImageRestApi.setServerIP(ip);
} else {
tv.setText("-");
ImageRestApi.setServerIP(null);
}
}
public void setApiOnline(boolean isApiOnline) {
if (this.isApiOnline != isApiOnline) {
refreshApiButton(isApiOnline);
}
this.isApiOnline = isApiOnline;
}
private void refreshServerButton(boolean isServerRunning) {
Drawable dr;
if (isServerRunning) {
dr = ctx.getResources().getDrawable(R.drawable.circle_green);
} else {
dr = ctx.getResources().getDrawable(R.drawable.circle_red);
}
serverButton.setBackground(dr);
}
private void refreshApiButton(boolean isApiOnline) {
Drawable dr;
if (isApiOnline) {
dr = ctx.getResources().getDrawable(R.drawable.circle_green);
} else {
dr = ctx.getResources().getDrawable(R.drawable.circle_red);
}
apiButton.setBackground(dr);
}
}
| true |
923fa99d0d5e3900d464043a51445e8fe64214c8 | Java | anhduc130/Yelp-Dataset | /Restaurant.java | UTF-8 | 5,181 | 2.25 | 2 | [] | no_license | package ca.ece.ubc.cpen221.mp5;
import java.io.FileReader;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import org.antlr.v4.parse.BlockSetTransformer.setAlt_return;
import org.antlr.v4.runtime.tree.ParseTree;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.omg.CosNaming.NamingContextPackage.CannotProceedHolder;
import com.sun.j3d.utils.behaviors.interpolators.KBKeyFrame;
import com.sun.javafx.event.EventHandlerManager;
import com.sun.xml.internal.ws.wsdl.writer.document.OpenAtts;
import apple.laf.JRSUIConstants.State;
import javafx.scene.shape.Line;
// TODO: Use this class to represent a restaurant.
// State the rep invariant and abs
/**
* This class represents all the features of restaurants
* @author anhduc130
*
*/
public class Restaurant {
private JSONObject jsonObject;
private String jasonString;
private Boolean open;
private String url;
private Double longitude;
private Set<String> neighborhoods;
private String business_id;
private String name;
private Set<String> categories;
private String state;
private String type;
private Double stars;
private String city;
private String full_address;
private Long review_count;
private String photo_url;
private Set<String> schools;
private Double latitude;
private Long price;
// Rep invariant:
// all the variables above should follow its types accordingly when being used
public Restaurant(String jasonString) throws ParseException {
this.jasonString = jasonString;
JSONParser parser = new JSONParser();
Object obj = parser
.parse(jasonString);
jsonObject = (JSONObject) obj;
jasonFormatString(jasonString);
Open();
Url();
Longitude();
Neighborhoods();
Business_id();
Name();
Categories();
State();
Type();
Rating();
City();
Full_address();
Review_count();
Photo_url();
Schools();
Latitude();
Price();
}
public void jasonFormatString(String jasonString){
this.jasonString = jasonString;
}
public void Open(){
this.open = (Boolean) jsonObject.get("open");
}
public void Url(){
this.url = (String) jsonObject.get("url");
}
public void Longitude(){
this.longitude = (Double) jsonObject.get("longitude");
}
public void Neighborhoods(){
this.neighborhoods = new HashSet<String>();
JSONArray neighborhoodsArray = (JSONArray) jsonObject.get("neighborhoods");
@SuppressWarnings("unchecked")
Iterator<String> iterator = neighborhoodsArray.iterator();
while(iterator.hasNext()){
neighborhoods.add(iterator.next());
}
}
public void Business_id(){
this.business_id = (String) jsonObject.get("business_id");
}
public void Name(){
this.name = (String) jsonObject.get("name");
}
public void Categories(){
this.categories = new HashSet<String>();
JSONArray categoriesArray = (JSONArray) jsonObject.get("categories");
@SuppressWarnings("unchecked")
Iterator<String> iterator = categoriesArray.iterator();
while(iterator.hasNext()){
categories.add(iterator.next());
}
}
public void State(){
this.state = (String) jsonObject.get("state");
}
public void Type(){
this.type = (String) jsonObject.get("type");
}
public void Rating(){
this.stars = (Double) jsonObject.get("stars");
}
public void City(){
this.city = (String) jsonObject.get("city");
}
public void Full_address(){
this.full_address = (String) jsonObject.get("full_address");
}
public void Review_count(){
this.review_count = (Long) jsonObject.get("review_count");
}
public void Photo_url(){
this.photo_url = (String) jsonObject.get("photo_url");
}
public void Schools(){
this.schools = new HashSet<String>();
JSONArray schoolsArray = (JSONArray) jsonObject.get("schools");
@SuppressWarnings("unchecked")
Iterator<String> iterator = schoolsArray.iterator();
while(iterator.hasNext()){
schools.add(iterator.next());
}
}
public void Latitude(){
this.latitude = (Double) jsonObject.get("latitude");
}
public void Price(){
this.price = (Long) jsonObject.get("price");
}
public String getJasonFormatString(){
return jasonString;
}
public Boolean getOpen(){
return open;
}
public String getUrl(){
return url;
}
public Double getLongitude(){
return longitude;
}
public Set<String> getNeighborhoods(){
return neighborhoods;
}
public String getBusiness_id(){
return business_id;
}
public String getName(){
return name;
}
public Set<String> getCategories(){
return categories;
}
public String getState(){
return state;
}
public String getType(){
return type;
}
public Double getRating(){
return stars;
}
public String getCity(){
return city;
}
public String getFull_address(){
return full_address;
}
public Long getReview_count(){
return review_count;
}
public String getPhoto_url(){
return photo_url;
}
public Set<String> getSchools(){
return schools;
}
public Double getLatitude(){
return latitude;
}
public Long getPrice(){
return price;
}
}
| true |
5add5d2852f43f235c309e2aadd68070c764897f | Java | csys-fresher-batch-2021/lmsapp-mohamedhalith | /src/main/java/in/mohamedhalith/servlet/ApproveRejectServlet.java | UTF-8 | 1,486 | 2.265625 | 2 | [] | no_license | package in.mohamedhalith.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import in.mohamedhalith.exception.ServiceException;
import in.mohamedhalith.exception.ValidationException;
import in.mohamedhalith.service.LeaveRequestService;
/**
* Servlet implementation class ApproveRejectServlet
*/
@WebServlet("/ApproveRejectServlet")
public class ApproveRejectServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String value = request.getParameter("action");
try {
int leaveId = Integer.parseInt(request.getParameter("leaveId"));
int employeeId = Integer.parseInt(request.getParameter("employeeId"));
boolean output =LeaveRequestService.updateLeaveRequest(value, leaveId, employeeId);
PrintWriter out = response.getWriter();
Gson gson = new Gson();
String json = gson.toJson(output);
out.print(json);
out.flush();
} catch (NumberFormatException | ServiceException | ValidationException | IOException e) {
e.printStackTrace();
}
}
}
| true |
abbfd13b2b8b6a0f7beac19e865a42c1da13bb4c | Java | P-A-N/commonsos-api | /src/commonsos/controller/community/CommunityListController.java | UTF-8 | 768 | 2.03125 | 2 | [] | no_license | package commonsos.controller.community;
import javax.inject.Inject;
import commonsos.annotation.ReadOnly;
import commonsos.service.CommunityService;
import commonsos.service.command.PaginationCommand;
import commonsos.util.PaginationUtil;
import commonsos.view.CommunityListView;
import spark.Request;
import spark.Response;
import spark.Route;
@ReadOnly
public class CommunityListController implements Route {
@Inject CommunityService service;
@Override
public CommunityListView handle(Request request, Response response) {
String filter = request.queryParams("filter");
PaginationCommand paginationCommand = PaginationUtil.getCommand(request);
CommunityListView view = service.list(filter, paginationCommand);
return view;
}
}
| true |
5b4c2560210fbdeebb6358ac662d816bc7c80ed5 | Java | marcosalpereira/apropriator | /src/test/java/br/com/marcosoft/apropriator/ApropriationFileParserTest.java | ISO-8859-1 | 1,996 | 2.5625 | 3 | [] | no_license | package br.com.marcosoft.apropriator;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import br.com.marcosoft.apropriator.model.ApropriationFile;
public class ApropriationFileParserTest {
@Test
public void testParseProjectsQtdParametrosInvalido() {
try {
parse("/parse/projects/qtdParametrosInvalido.csv");
} catch (final IOException e) {
assertEquals(
"Erro lendo os projetos: Quantidade de campos difere da esperada!",
e.getMessage());
}
}
@Test
public void testParseConfigQtdParametrosInvalido() {
try {
parse("/parse/config/qtdParametrosInvalido.csv");
} catch (final IOException e) {
assertEquals(
"Erro lendo as configuraes da planilha. Quantidade de campos difere da esperada!",
e.getMessage());
}
}
@Test
public void testParseConfigAppProperty() throws IOException {
final ApropriationFile apropriationFile = parse("/parse/config/appProperty.csv");
assertEquals("123", apropriationFile.getConfig().getCpf());
}
@Test
public void testParseConfigSysProperty() throws IOException {
final String sysProperty = "sys.property";
System.clearProperty(sysProperty);
assertNull(System.getProperty(sysProperty));
parse("/parse/config/sysProperty.csv");
assertEquals("valor", System.getProperty(sysProperty));
}
private ApropriationFile parse(String arquivoCsv) throws IOException {
final ApropriationFileParser fileParser =
new ApropriationFileParser(getFile(arquivoCsv));
return fileParser.parse();
}
private File getFile(String filename) {
final String fullname = this.getClass().getResource(filename).getFile();
return new File(fullname);
}
}
| true |
65f882e29a1474367706c0f0d6a89a2d977f7665 | Java | annabuczek/KrakowTourGuideApp | /app/src/main/java/com/example/android/krakowtourguideapp/TodoAdapter.java | UTF-8 | 1,249 | 2.5 | 2 | [] | no_license | package com.example.android.krakowtourguideapp;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
* Created by aania on 05.05.2018.
*/
public class TodoAdapter extends FragmentPagerAdapter {
private Context mContext;
public TodoAdapter(Context context, FragmentManager fm) {
super(fm);
mContext = context;
}
@Override
public Fragment getItem(int position) {
if (position == 0) {
return new ChildMuseumsFragment();
} else if (position == 1) {
return new ChildActivitiesFragment();
} else {
return new ChildAroundFragment();
}
}
@Override
public int getCount () {
return 3;
}
@Nullable
@Override
public CharSequence getPageTitle ( int position){
if (position == 0) {
return mContext.getString(R.string.tab_museums);
} else if (position == 1) {
return mContext.getString(R.string.tab_activities);
} else {
return mContext.getString(R.string.tab_around);
}
}
}
| true |
729c7491c7e6c788c3453da0a85e461603aa2439 | Java | myotive/fragments_codemash2017 | /codemash_common/src/main/java/com/example/myotive/codemash_common/network/models/Speaker.java | UTF-8 | 2,527 | 2.125 | 2 | [] | no_license | package com.example.myotive.codemash_common.network.models;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
import java.util.UUID;
/**
* Created by michaelyotive_hr on 12/3/16.
*/
public class Speaker implements Serializable {
@SerializedName("Id")
@Expose
private UUID id;
@SerializedName("FirstName")
@Expose
private String firstName;
@SerializedName("LastName")
@Expose
private String lastName;
@SerializedName("Biography")
@Expose
private String biography;
@SerializedName("GravatarUrl")
@Expose
private String gravatarUrl;
@SerializedName("TwitterLink")
@Expose
private String twitterLink;
@SerializedName("GitHubLink")
@Expose
private String gitHubLink;
@SerializedName("LinkedInProfile")
@Expose
private String linkedInProfile;
@SerializedName("BlogUrl")
@Expose
private String blogUrl;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFullName(){
return String.format("%s %s", firstName, lastName);
}
public String getBiography() {
return biography;
}
public void setBiography(String biography) {
this.biography = biography;
}
public String getGravatarUrl() {
return gravatarUrl;
}
public void setGravatarUrl(String gravatarUrl) {
this.gravatarUrl = gravatarUrl;
}
public String getTwitterLink() {
return twitterLink;
}
public void setTwitterLink(String twitterLink) {
this.twitterLink = twitterLink;
}
public String getGitHubLink() {
return gitHubLink;
}
public void setGitHubLink(String gitHubLink) {
this.gitHubLink = gitHubLink;
}
public String getLinkedInProfile() {
return linkedInProfile;
}
public void setLinkedInProfile(String linkedInProfile) {
this.linkedInProfile = linkedInProfile;
}
public String getBlogUrl() {
return blogUrl;
}
public void setBlogUrl(String blogUrl) {
this.blogUrl = blogUrl;
}
}
| true |
ca4e5d9e55e8e49202154989d5d6dfbc8c51d77a | Java | snailhu/Syslink | /gridCPProject/src/main/java/GridCP/core/controller/common/CommonController.java | UTF-8 | 3,416 | 2.09375 | 2 | [] | no_license | package GridCP.core.controller.common;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import GridCP.core.common.Config;
import GridCP.core.gogsDomain.User;
import GridCP.core.result.SubmitResultInfo;
import GridCP.core.service.userOperateService.UserService;
import GridCP.util.PBKDF2SHA256;
import GridCP.util.ResultUtil;
@Controller
@RequestMapping(value = "/common", produces = "application/json;charset=utf-8")
public class CommonController {
@Resource
private UserService userService;
@RequestMapping(value = "/goIndex", method = { RequestMethod.GET })
public String goIndex() {
System.out.println("test success goIndex");
return "showModel_new";
}
@RequestMapping(value = "/goIndex2", method = { RequestMethod.GET })
public String goIndex2() {
System.out.println("test success goIndex2");
return "redirect:/common/goIndex";
}
@RequestMapping(value = "/goShowModel", method = { RequestMethod.GET })
public String goShowModel() {
// System.out.println("test success goShowModel");
return "showPkg";
}
@RequestMapping(value = "/login", method = { RequestMethod.GET })
public String login() {
return "login";
}
@RequestMapping(value = "/login", method = { RequestMethod.POST })
public String loginPost(
HttpServletResponse response,
HttpServletRequest request,
@RequestParam(value="username",required = false) String username,
@RequestParam(value="password",required = false) String password
) throws InvalidKeyException, NoSuchAlgorithmException {
if(!("".equals(username))&& username!=null){
User user = userService.getUserByName(username);
String EncryptedPassword =PBKDF2SHA256.getEncryptedPassword(password, user.getSalt());
if(user != null && EncryptedPassword.equals(user.getPasswd())){
request.getSession().setAttribute("user", user);
request.getSession().setAttribute("base_path", request.getContextPath());
Cookie c = new Cookie("gogs_awesome",username);
c.setDomain(".syslink.cn");
c.setMaxAge(3600);
c.setPath("/");
response.addCookie(c);
return "showModel_new";
}else{
return "login";
}
}else{
return "login";
}
}
@RequestMapping(value = "/logout", method = { RequestMethod.GET })
@ResponseBody
public SubmitResultInfo logout(
HttpServletResponse response,
HttpServletRequest request
) {
HttpSession session = request.getSession();
session.invalidate();
Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
if(cookies != null&&cookies.length>0){
for(Cookie cookie : cookies){
Cookie new_cookie = new Cookie(cookie.getName(), null);
new_cookie.setDomain(".syslink.cn");
new_cookie.setPath("/");
new_cookie.setMaxAge(0);
response.addCookie(new_cookie);
}
}
return ResultUtil.createSubmitResult(ResultUtil.createSuccess(Config.MESSAGE, 100, null));
}
}
| true |
fb9a60f692005f28ee1a8ec52dbc368f830f4752 | Java | ossaw/jdk | /src/javax/naming/ldap/SortKey.java | UTF-8 | 2,964 | 2.640625 | 3 | [] | no_license | /*
* Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package javax.naming.ldap;
/**
* A sort key and its associated sort parameters. This class implements a sort
* key which is used by the LDAPv3 Control for server-side sorting of search
* results as defined in <a href="http://www.ietf.org/rfc/rfc2891.txt">RFC
* 2891</a>.
*
* @since 1.5
* @see SortControl
* @author Vincent Ryan
*/
public class SortKey {
/*
* The ID of the attribute to sort by.
*/
private String attrID;
/*
* The sort order. Ascending order, by default.
*/
private boolean reverseOrder = false;
/*
* The ID of the matching rule to use for ordering attribute values.
*/
private String matchingRuleID = null;
/**
* Creates the default sort key for an attribute. Entries will be sorted
* according to the specified attribute in ascending order using the
* ordering matching rule defined for use with that attribute.
*
* @param attrID
* The non-null ID of the attribute to be used as a sort key.
*/
public SortKey(String attrID) {
this.attrID = attrID;
}
/**
* Creates a sort key for an attribute. Entries will be sorted according to
* the specified attribute in the specified sort order and using the
* specified matching rule, if supplied.
*
* @param attrID
* The non-null ID of the attribute to be used as a
* sort key.
* @param ascendingOrder
* If true then entries are arranged in ascending
* order.
* Otherwise there are arranged in descending order.
* @param matchingRuleID
* The possibly null ID of the matching rule to use to
* order the
* attribute values. If not specified then the
* ordering matching
* rule defined for the sort key attribute is used.
*/
public SortKey(String attrID, boolean ascendingOrder, String matchingRuleID) {
this.attrID = attrID;
reverseOrder = (!ascendingOrder);
this.matchingRuleID = matchingRuleID;
}
/**
* Retrieves the attribute ID of the sort key.
*
* @return The non-null Attribute ID of the sort key.
*/
public String getAttributeID() {
return attrID;
}
/**
* Determines the sort order.
*
* @return true if the sort order is ascending, false if descending.
*/
public boolean isAscending() {
return (!reverseOrder);
}
/**
* Retrieves the matching rule ID used to order the attribute values.
*
* @return The possibly null matching rule ID. If null then the ordering
* matching rule defined for the sort key attribute is used.
*/
public String getMatchingRuleID() {
return matchingRuleID;
}
}
| true |
9eb83c42cd40c05cb27dacd498497f28ac6bb2ad | Java | lukdut/monitoring | /monitoring-test/monitoring-test-device/src/main/java/com/lukdut/monitoring/test/device/ShellService.java | UTF-8 | 2,148 | 2.421875 | 2 | [] | no_license | package com.lukdut.monitoring.test.device;
import com.lukdut.monitoring.gateway.dto.IncomingSensorMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.shell.standard.ShellComponent;
import org.springframework.shell.standard.ShellMethod;
import org.springframework.shell.standard.ShellOption;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;
@ShellComponent
public class ShellService {
private static final Logger LOG = LoggerFactory.getLogger(ShellService.class);
private final TaskManager taskManager;
public ShellService(TaskManager taskManager) {
this.taskManager = taskManager;
}
@ShellMethod("Load messages source file")
public void load(@ShellOption String fileName) throws IOException {
List<IncomingSensorMessage> messages = Files.lines(Paths.get(fileName))
.map(s -> {
LOG.debug("Found line: {}", s);
IncomingSensorMessage incomingSensorMessage = new IncomingSensorMessage();
incomingSensorMessage.setGpsData(s);
incomingSensorMessage.setImei(1);
return incomingSensorMessage;
}).collect(Collectors.toList());
taskManager.updateDataSet(messages);
}
@ShellMethod("Start data producing with the specified speed (in messages per second, default is 1)")
public void start(@ShellOption(defaultValue = "1") int speed) {
LOG.info("Starting data producing with speed {}", speed);
taskManager.start(speed);
}
@ShellMethod("Stop data producing")
public void stop() {
taskManager.stop();
}
@ShellMethod("Change data producing speed (in messages per second)")
public void speed(@ShellOption(defaultValue = "-1") Integer newSpeed) {
if (newSpeed < 0) {
System.out.println(taskManager.getActualSpeed());
} else if (newSpeed == 0) {
taskManager.stop();
} else {
taskManager.setSpeed(newSpeed);
}
}
}
| true |
4838bec2fced20b588414cbb675864a642a5a106 | Java | umarazhar/Chat-Program | /src/main/java/net/umar/chat/client/ClientWindow.java | UTF-8 | 11,088 | 2.453125 | 2 | [] | no_license | package net.umar.chat.client;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import net.umar.chat.data.DataHandler;
public class ClientWindow extends JFrame implements Runnable {
private final int WIDTH = 250;
private final int HEIGHT = 400;
private User user;
private HashMap<String, ChatWindow> windows = new HashMap<String, ChatWindow>();
private JPanel panel;
private JPanel friend_panel;
private JMenuBar menu_bar;
private Box main_box;
private Box friend_box;
private Box button_box;
public ClientWindow() throws ClassNotFoundException, UnsupportedLookAndFeelException, InstantiationException, IllegalAccessException {
this.setSize(WIDTH, HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
String name = JOptionPane.showInputDialog("Enter your desired name: ");
user = new User(name);
init();
this.setJMenuBar(menu_bar);
this.add(panel);
this.setVisible(true);
}
public ClientWindow(String name) {
this.setSize(WIDTH, HEIGHT);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
user = new User(name);
init();
this.setJMenuBar(menu_bar);
this.add(panel);
this.setVisible(true);
}
private void init() {
menu_bar = new JMenuBar();
JMenu file_menu = new JMenu("File");
JMenuItem connect_item = new JMenuItem("Connect");
connect_item.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
user.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
);
file_menu.add(connect_item);
menu_bar.add(file_menu);
panel = new JPanel();
main_box = new Box(BoxLayout.Y_AXIS);
friend_box = new Box(BoxLayout.Y_AXIS);
button_box = new Box(BoxLayout.X_AXIS);
Dimension friend_size = new Dimension(WIDTH - 20, HEIGHT - 100);
friend_box.setMaximumSize(friend_size);
friend_box.setPreferredSize(friend_size);
friend_box.setMinimumSize(friend_size);
friend_panel = new JPanel();
JScrollPane scroll_friend_pane = new JScrollPane(friend_panel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
friend_box.add(scroll_friend_pane);
JLabel upcoming = new JLabel("Coming soon!");
final JLabel warnings = new JLabel("");
friend_panel.add(upcoming);
friend_panel.add(warnings);
JButton chat_button = new JButton("Chat");
chat_button.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!user.isOnline()) {
warnings.setText("Please connect to online server first!");
return;
}
String friend = JOptionPane.showInputDialog("Who would you like to chat with?");
ChatWindow newChat = new ChatWindow(user, user.getName(), friend);
windows.put(friend, newChat);
}
}
);
button_box.add(chat_button);
main_box.add(friend_box);
main_box.add(button_box);
panel.add(main_box);
}
public void update() {
try {
String message = user.retrieveMessage();
if (message != null) {
String[] line = message.split(" ");
if (line[0].trim().equals("Receive")) {
if (line[1].trim().equals("Message")) {
String newMessage = new String(user.retrieveData(Integer.parseInt(message.split(" ")[3].trim())));
String tmpName = line[2].trim();
ChatWindow tmpWindow = windows.get(tmpName);
if (tmpWindow != null) {
if (tmpWindow.isVisible()) {
windows.get(tmpName).addMessage(tmpName + ": " + newMessage);
} else {
windows.remove(tmpName);
}
} else {
windows.put(tmpName, new ChatWindow(user, user.getName(), tmpName));
windows.get(tmpName).addMessage(tmpName + ": " + newMessage);
}
System.out.println("Message received from: " + message.split(" ")[2]);
System.out.println("Message: " + newMessage);
} else if (line[1].trim().equals("File")) {
System.out.println("Incoming File!");
// byte[] newFile = user.retrieveData(Integer.parseInt(message.split(" ")[3].trim()));
String tmpName = line[2].trim();
ChatWindow tmpWindow = windows.get(tmpName);
if (tmpWindow != null) {
if (tmpWindow.isVisible()) {
windows.get(tmpName).addMessage(tmpName + ": Received new file!");
JFileChooser fileChooser = new JFileChooser();
fileChooser.showSaveDialog(null);
if (fileChooser.getSelectedFile() != null) {
String filename = fileChooser.getSelectedFile().getAbsolutePath() + "." + line[4];
FileOutputStream fileOut = new FileOutputStream(filename);
DataHandler.readAndWriteToFile(user.getSocket().getInputStream(), fileOut, Integer.parseInt(message.split(" ")[3].trim()));
// fileOut.write(newFile);
fileOut.close();
}
} else {
windows.remove(tmpName);
}
} else {
windows.put(tmpName, new ChatWindow(user, user.getName(), tmpName));
windows.get(tmpName).addMessage(tmpName + ": Received new file!");
JFileChooser fileChooser = new JFileChooser();
fileChooser.showSaveDialog(null);
if (fileChooser.getSelectedFile() != null) {
String filename = fileChooser.getSelectedFile().getAbsolutePath() + "." + line[4];
FileOutputStream fileOut = new FileOutputStream(filename);
DataHandler.readAndWriteToFile(user.getSocket().getInputStream(), fileOut, Integer.parseInt(message.split(" ")[3].trim()));
// fileOut.write(newFile);
fileOut.close();
}
}
System.out.println("Message received from: " + message.split(" ")[2]);
System.out.println("Received file!");
} else if (line[1].trim().equals("FriendList")) {
String tmpName = line[2];
String filename = tmpName + "friendlist.txt";
FileOutputStream fileOut = new FileOutputStream(filename);
DataHandler.readAndWriteToFile(user.getSocket().getInputStream(), fileOut, Integer.parseInt(line[3]));
fileOut.close();
windows.get(tmpName).addMessage("Received friends list!");
}
} else if (line[0].trim().equals("Failure")) {
if (line[1].trim().equals("Send")) {
if (line[2].trim().equals("Offline")) {
String tmpName = line[3].trim();
ChatWindow tmpWindow = windows.get(tmpName);
if (tmpWindow != null && tmpWindow.isVisible()) {
windows.get(tmpName).addMessage(tmpName + " is not online! Message was not send.");
} else {
windows.remove(tmpName);
}
}
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ClientWindow window;
try {
window = new ClientWindow();
new Thread(window).start();
} catch (ClassNotFoundException ex) {
Logger.getLogger(ClientWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(ClientWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(ClientWindow.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(ClientWindow.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
public static void delay(long sec) {
try {
Thread.sleep(sec);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
while (true) {
// System.out.println("hello");
this.update();
delay(100);
}
}
}
| true |
ecf6e12e4125a5b3ff3f9c486382e580e060f73e | Java | googleapis/google-cloud-java | /java-aiplatform/proto-google-cloud-aiplatform-v1/src/main/java/com/google/cloud/aiplatform/v1/ModelDeploymentMonitoringJobProto.java | UTF-8 | 19,189 | 1.820313 | 2 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | /*
* Copyright 2023 Google LLC
*
* 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
*
* https://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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/aiplatform/v1/model_deployment_monitoring_job.proto
package com.google.cloud.aiplatform.v1;
public final class ModelDeploymentMonitoringJobProto {
private ModelDeploymentMonitoringJobProto() {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_LatestMonitoringPipelineMetadata_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_LatestMonitoringPipelineMetadata_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_LabelsEntry_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_LabelsEntry_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringBigQueryTable_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringBigQueryTable_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringObjectiveConfig_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringObjectiveConfig_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringScheduleConfig_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringScheduleConfig_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_ModelMonitoringStatsAnomalies_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_ModelMonitoringStatsAnomalies_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_google_cloud_aiplatform_v1_ModelMonitoringStatsAnomalies_FeatureHistoricStatsAnomalies_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_google_cloud_aiplatform_v1_ModelMonitoringStatsAnomalies_FeatureHistoricStatsAnomalies_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
java.lang.String[] descriptorData = {
"\n@google/cloud/aiplatform/v1/model_deplo"
+ "yment_monitoring_job.proto\022\032google.cloud"
+ ".aiplatform.v1\032\037google/api/field_behavio"
+ "r.proto\032\031google/api/resource.proto\0320goog"
+ "le/cloud/aiplatform/v1/encryption_spec.p"
+ "roto\0329google/cloud/aiplatform/v1/feature"
+ "_monitoring_stats.proto\032#google/cloud/ai"
+ "platform/v1/io.proto\032*google/cloud/aipla"
+ "tform/v1/job_state.proto\0321google/cloud/a"
+ "iplatform/v1/model_monitoring.proto\032\036goo"
+ "gle/protobuf/duration.proto\032\034google/prot"
+ "obuf/struct.proto\032\037google/protobuf/times"
+ "tamp.proto\032\027google/rpc/status.proto\"\273\020\n\034"
+ "ModelDeploymentMonitoringJob\022\022\n\004name\030\001 \001"
+ "(\tB\004\342A\001\003\022\032\n\014display_name\030\002 \001(\tB\004\342A\001\002\022=\n\010"
+ "endpoint\030\003 \001(\tB+\342A\001\002\372A$\n\"aiplatform.goog"
+ "leapis.com/Endpoint\0229\n\005state\030\004 \001(\0162$.goo"
+ "gle.cloud.aiplatform.v1.JobStateB\004\342A\001\003\022n"
+ "\n\016schedule_state\030\005 \001(\0162P.google.cloud.ai"
+ "platform.v1.ModelDeploymentMonitoringJob"
+ ".MonitoringScheduleStateB\004\342A\001\003\022\214\001\n#lates"
+ "t_monitoring_pipeline_metadata\030\031 \001(\0132Y.g"
+ "oogle.cloud.aiplatform.v1.ModelDeploymen"
+ "tMonitoringJob.LatestMonitoringPipelineM"
+ "etadataB\004\342A\001\003\022\201\001\n-model_deployment_monit"
+ "oring_objective_configs\030\006 \003(\0132D.google.c"
+ "loud.aiplatform.v1.ModelDeploymentMonito"
+ "ringObjectiveConfigB\004\342A\001\002\022~\n+model_deplo"
+ "yment_monitoring_schedule_config\030\007 \001(\0132C"
+ ".google.cloud.aiplatform.v1.ModelDeploym"
+ "entMonitoringScheduleConfigB\004\342A\001\002\022U\n\031log"
+ "ging_sampling_strategy\030\010 \001(\0132,.google.cl"
+ "oud.aiplatform.v1.SamplingStrategyB\004\342A\001\002"
+ "\022]\n\035model_monitoring_alert_config\030\017 \001(\0132"
+ "6.google.cloud.aiplatform.v1.ModelMonito"
+ "ringAlertConfig\022#\n\033predict_instance_sche"
+ "ma_uri\030\t \001(\t\0227\n\027sample_predict_instance\030"
+ "\023 \001(\0132\026.google.protobuf.Value\022$\n\034analysi"
+ "s_instance_schema_uri\030\020 \001(\t\022a\n\017bigquery_"
+ "tables\030\n \003(\0132B.google.cloud.aiplatform.v"
+ "1.ModelDeploymentMonitoringBigQueryTable"
+ "B\004\342A\001\003\022*\n\007log_ttl\030\021 \001(\0132\031.google.protobu"
+ "f.Duration\022T\n\006labels\030\013 \003(\0132D.google.clou"
+ "d.aiplatform.v1.ModelDeploymentMonitorin"
+ "gJob.LabelsEntry\0225\n\013create_time\030\014 \001(\0132\032."
+ "google.protobuf.TimestampB\004\342A\001\003\0225\n\013updat"
+ "e_time\030\r \001(\0132\032.google.protobuf.Timestamp"
+ "B\004\342A\001\003\022<\n\022next_schedule_time\030\016 \001(\0132\032.goo"
+ "gle.protobuf.TimestampB\004\342A\001\003\022R\n\036stats_an"
+ "omalies_base_directory\030\024 \001(\0132*.google.cl"
+ "oud.aiplatform.v1.GcsDestination\022C\n\017encr"
+ "yption_spec\030\025 \001(\0132*.google.cloud.aiplatf"
+ "orm.v1.EncryptionSpec\022\'\n\037enable_monitori"
+ "ng_pipeline_logs\030\026 \001(\010\022\'\n\005error\030\027 \001(\0132\022."
+ "google.rpc.StatusB\004\342A\001\003\032t\n LatestMonitor"
+ "ingPipelineMetadata\022,\n\010run_time\030\001 \001(\0132\032."
+ "google.protobuf.Timestamp\022\"\n\006status\030\002 \001("
+ "\0132\022.google.rpc.Status\032-\n\013LabelsEntry\022\013\n\003"
+ "key\030\001 \001(\t\022\r\n\005value\030\002 \001(\t:\0028\001\"k\n\027Monitori"
+ "ngScheduleState\022)\n%MONITORING_SCHEDULE_S"
+ "TATE_UNSPECIFIED\020\000\022\013\n\007PENDING\020\001\022\013\n\007OFFLI"
+ "NE\020\002\022\013\n\007RUNNING\020\003:\245\001\352A\241\001\n6aiplatform.goo"
+ "gleapis.com/ModelDeploymentMonitoringJob"
+ "\022gprojects/{project}/locations/{location"
+ "}/modelDeploymentMonitoringJobs/{model_d"
+ "eployment_monitoring_job}\"\210\003\n&ModelDeplo"
+ "ymentMonitoringBigQueryTable\022`\n\nlog_sour"
+ "ce\030\001 \001(\0162L.google.cloud.aiplatform.v1.Mo"
+ "delDeploymentMonitoringBigQueryTable.Log"
+ "Source\022\\\n\010log_type\030\002 \001(\0162J.google.cloud."
+ "aiplatform.v1.ModelDeploymentMonitoringB"
+ "igQueryTable.LogType\022\033\n\023bigquery_table_p"
+ "ath\030\003 \001(\t\"B\n\tLogSource\022\032\n\026LOG_SOURCE_UNS"
+ "PECIFIED\020\000\022\014\n\010TRAINING\020\001\022\013\n\007SERVING\020\002\"=\n"
+ "\007LogType\022\030\n\024LOG_TYPE_UNSPECIFIED\020\000\022\013\n\007PR"
+ "EDICT\020\001\022\013\n\007EXPLAIN\020\002\"\233\001\n(ModelDeployment"
+ "MonitoringObjectiveConfig\022\031\n\021deployed_mo"
+ "del_id\030\001 \001(\t\022T\n\020objective_config\030\002 \001(\0132:"
+ ".google.cloud.aiplatform.v1.ModelMonitor"
+ "ingObjectiveConfig\"\227\001\n\'ModelDeploymentMo"
+ "nitoringScheduleConfig\0229\n\020monitor_interv"
+ "al\030\001 \001(\0132\031.google.protobuf.DurationB\004\342A\001"
+ "\002\0221\n\016monitor_window\030\002 \001(\0132\031.google.proto"
+ "buf.Duration\"\254\004\n\035ModelMonitoringStatsAno"
+ "malies\022U\n\tobjective\030\001 \001(\0162B.google.cloud"
+ ".aiplatform.v1.ModelDeploymentMonitoring"
+ "ObjectiveType\022\031\n\021deployed_model_id\030\002 \001(\t"
+ "\022\025\n\ranomaly_count\030\003 \001(\005\022n\n\rfeature_stats"
+ "\030\004 \003(\0132W.google.cloud.aiplatform.v1.Mode"
+ "lMonitoringStatsAnomalies.FeatureHistori"
+ "cStatsAnomalies\032\221\002\n\035FeatureHistoricStats"
+ "Anomalies\022\034\n\024feature_display_name\030\001 \001(\t\022"
+ ">\n\tthreshold\030\003 \001(\0132+.google.cloud.aiplat"
+ "form.v1.ThresholdConfig\022G\n\016training_stat"
+ "s\030\004 \001(\0132/.google.cloud.aiplatform.v1.Fea"
+ "tureStatsAnomaly\022I\n\020prediction_stats\030\005 \003"
+ "(\0132/.google.cloud.aiplatform.v1.FeatureS"
+ "tatsAnomaly*\316\001\n&ModelDeploymentMonitorin"
+ "gObjectiveType\022:\n6MODEL_DEPLOYMENT_MONIT"
+ "ORING_OBJECTIVE_TYPE_UNSPECIFIED\020\000\022\024\n\020RA"
+ "W_FEATURE_SKEW\020\001\022\025\n\021RAW_FEATURE_DRIFT\020\002\022"
+ "\034\n\030FEATURE_ATTRIBUTION_SKEW\020\003\022\035\n\031FEATURE"
+ "_ATTRIBUTION_DRIFT\020\004B\337\001\n\036com.google.clou"
+ "d.aiplatform.v1B!ModelDeploymentMonitori"
+ "ngJobProtoP\001Z>cloud.google.com/go/aiplat"
+ "form/apiv1/aiplatformpb;aiplatformpb\252\002\032G"
+ "oogle.Cloud.AIPlatform.V1\312\002\032Google\\Cloud"
+ "\\AIPlatform\\V1\352\002\035Google::Cloud::AIPlatfo"
+ "rm::V1b\006proto3"
};
descriptor =
com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(
descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
com.google.api.FieldBehaviorProto.getDescriptor(),
com.google.api.ResourceProto.getDescriptor(),
com.google.cloud.aiplatform.v1.EncryptionSpecProto.getDescriptor(),
com.google.cloud.aiplatform.v1.FeatureMonitoringStatsProto.getDescriptor(),
com.google.cloud.aiplatform.v1.IoProto.getDescriptor(),
com.google.cloud.aiplatform.v1.JobStateProto.getDescriptor(),
com.google.cloud.aiplatform.v1.ModelMonitoringProto.getDescriptor(),
com.google.protobuf.DurationProto.getDescriptor(),
com.google.protobuf.StructProto.getDescriptor(),
com.google.protobuf.TimestampProto.getDescriptor(),
com.google.rpc.StatusProto.getDescriptor(),
});
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_descriptor,
new java.lang.String[] {
"Name",
"DisplayName",
"Endpoint",
"State",
"ScheduleState",
"LatestMonitoringPipelineMetadata",
"ModelDeploymentMonitoringObjectiveConfigs",
"ModelDeploymentMonitoringScheduleConfig",
"LoggingSamplingStrategy",
"ModelMonitoringAlertConfig",
"PredictInstanceSchemaUri",
"SamplePredictInstance",
"AnalysisInstanceSchemaUri",
"BigqueryTables",
"LogTtl",
"Labels",
"CreateTime",
"UpdateTime",
"NextScheduleTime",
"StatsAnomaliesBaseDirectory",
"EncryptionSpec",
"EnableMonitoringPipelineLogs",
"Error",
});
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_LatestMonitoringPipelineMetadata_descriptor =
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_LatestMonitoringPipelineMetadata_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_LatestMonitoringPipelineMetadata_descriptor,
new java.lang.String[] {
"RunTime", "Status",
});
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_LabelsEntry_descriptor =
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_descriptor
.getNestedTypes()
.get(1);
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_LabelsEntry_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringJob_LabelsEntry_descriptor,
new java.lang.String[] {
"Key", "Value",
});
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringBigQueryTable_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringBigQueryTable_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringBigQueryTable_descriptor,
new java.lang.String[] {
"LogSource", "LogType", "BigqueryTablePath",
});
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringObjectiveConfig_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringObjectiveConfig_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringObjectiveConfig_descriptor,
new java.lang.String[] {
"DeployedModelId", "ObjectiveConfig",
});
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringScheduleConfig_descriptor =
getDescriptor().getMessageTypes().get(3);
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringScheduleConfig_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_ModelDeploymentMonitoringScheduleConfig_descriptor,
new java.lang.String[] {
"MonitorInterval", "MonitorWindow",
});
internal_static_google_cloud_aiplatform_v1_ModelMonitoringStatsAnomalies_descriptor =
getDescriptor().getMessageTypes().get(4);
internal_static_google_cloud_aiplatform_v1_ModelMonitoringStatsAnomalies_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_ModelMonitoringStatsAnomalies_descriptor,
new java.lang.String[] {
"Objective", "DeployedModelId", "AnomalyCount", "FeatureStats",
});
internal_static_google_cloud_aiplatform_v1_ModelMonitoringStatsAnomalies_FeatureHistoricStatsAnomalies_descriptor =
internal_static_google_cloud_aiplatform_v1_ModelMonitoringStatsAnomalies_descriptor
.getNestedTypes()
.get(0);
internal_static_google_cloud_aiplatform_v1_ModelMonitoringStatsAnomalies_FeatureHistoricStatsAnomalies_fieldAccessorTable =
new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_google_cloud_aiplatform_v1_ModelMonitoringStatsAnomalies_FeatureHistoricStatsAnomalies_descriptor,
new java.lang.String[] {
"FeatureDisplayName", "Threshold", "TrainingStats", "PredictionStats",
});
com.google.protobuf.ExtensionRegistry registry =
com.google.protobuf.ExtensionRegistry.newInstance();
registry.add(com.google.api.FieldBehaviorProto.fieldBehavior);
registry.add(com.google.api.ResourceProto.resource);
registry.add(com.google.api.ResourceProto.resourceReference);
com.google.protobuf.Descriptors.FileDescriptor.internalUpdateFileDescriptor(
descriptor, registry);
com.google.api.FieldBehaviorProto.getDescriptor();
com.google.api.ResourceProto.getDescriptor();
com.google.cloud.aiplatform.v1.EncryptionSpecProto.getDescriptor();
com.google.cloud.aiplatform.v1.FeatureMonitoringStatsProto.getDescriptor();
com.google.cloud.aiplatform.v1.IoProto.getDescriptor();
com.google.cloud.aiplatform.v1.JobStateProto.getDescriptor();
com.google.cloud.aiplatform.v1.ModelMonitoringProto.getDescriptor();
com.google.protobuf.DurationProto.getDescriptor();
com.google.protobuf.StructProto.getDescriptor();
com.google.protobuf.TimestampProto.getDescriptor();
com.google.rpc.StatusProto.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| true |
ce8fff83b97fd097f5d7d37dac2867c2c3d2d346 | Java | grantfar/Workout-Tracker | /app/src/main/java/com/grant/workouttracker/MainActivity.java | UTF-8 | 2,363 | 1.84375 | 2 | [
"Apache-2.0"
] | permissive | package com.grant.workouttracker;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import androidx.core.content.ContextCompat;
import androidx.core.content.res.ResourcesCompat;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.material.tabs.TabLayout;
public class MainActivity extends AppCompatActivity implements Workout.OnFragmentInteractionListener,
Excercise.OnFragmentInteractionListener, Tracking.OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ViewPager viewPager = findViewById(R.id.pager);
TabLayout pagerTabs = findViewById(R.id.pageTabs);
FragmentPager fragmentPager = new FragmentPager(this, getSupportFragmentManager());
viewPager.setAdapter(fragmentPager);
pagerTabs.setupWithViewPager(viewPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onFragmentInteraction(Uri uri) {
}
}
| true |
090943cf2630e2fcfb7fc4232baa26a8ef6f324c | Java | Longi94/Phoebe | /src/view/CleaningRobotView.java | UTF-8 | 1,698 | 3.03125 | 3 | [] | no_license | package view;
import model.CleaningRobot;
import java.awt.*;
/**
* Takarító robot kinézet
*
* @author Gergely Reményi
* @since 2015.04.25.
*/
public class CleaningRobotView extends TrackObjectBaseView {
//Referencia az objhektumra amit ki kell rajzolni.
private CleaningRobot cleaningRobot;
/**
* Construktor
*
* @param cleaningRobot az objektum amihez a view tartozik
* @param tv a pálya nézet amire ki kell rajzolni
*/
public CleaningRobotView(CleaningRobot cleaningRobot, TrackView tv) {
super(cleaningRobot, tv);
this.cleaningRobot = cleaningRobot;
}
/**
* Takarító robot kirajzolása.
*
* @param graph amire rajzol
* @param xOffset x eltolás
* @param yOffset y eltolás
* @param zoom nagyítás
*/
public void draw(Graphics graph, double xOffset, double yOffset, double zoom) {
graph.setColor(new Color(255, 255, 255));
int radius = (int) (cleaningRobot.getRadius() * zoom * 2);
graph.fillOval(cleaningRobot.getPos().convertX(xOffset, zoom) - radius / 2, cleaningRobot.getPos().convertY(yOffset, zoom) - radius / 2,
radius, radius);
graph.setColor(new Color(255, 255, 0));
int size = (int) (cleaningRobot.getRadius() * 0.707 * zoom);
int x = cleaningRobot.getPos().convertX(xOffset - 0.06, zoom) - radius / 2;
int y = cleaningRobot.getPos().convertY(yOffset - 0.06, zoom) - radius / 2;
if (cleaningRobot.getActuallyCleaning() != null) {
graph.fillRect(x, y, 2 * size, 2 * size);
} else {
graph.drawRect(x, y, 2 * size, 2 * size);
}
}
}
| true |
a1f3217b95ea78617201a28ef58891bb3f8a55f8 | Java | LPinnow/Super-Sudoku-Solver | /Sudoku_CSP/src/UninformedSearch.java | UTF-8 | 3,031 | 3.890625 | 4 | [] | no_license |
public class UninformedSearch {
static SuperSudoku puzzle;
/**
* Uniformed agent that solves the puzzle through a brute force search
* Starts in the top left corner and assigns values to empty cells from left to right, top to bottom
* Constraints are the value must be unique in the cell's group, row, and column
* @param inputPuzzle
* @return
*/
public static SuperSudoku solvePuzzle (SuperSudoku inputPuzzle) {
puzzle = inputPuzzle;
try {
assignValue(0,0);
} catch (Exception e) {
}
return puzzle;
}
/**
* Backtracking search that assigns values to the cells
* Breaks out of backtracking search by throwing an exception
* Solution is complete when search reaches cell 15,15 on the grid
* @param x
* @param y
* @throws Exception
*/
public static void assignValue (int x, int y) throws Exception {
// Reached the end of the grid so the solution is complete
if (y > 15)
throw new Exception("");
// Skip cells that are already assigned values
else if (puzzle.sudokuGrid[x][y].getValue() != '-')
nextCell(x,y);
// Try each value and assign it if it is unique compared to other values in the cell's row, column, and group
else {
for(int i = 0; i < puzzle.domainOfValues.size(); i++){
char value = puzzle.domainOfValues.get(i);
if(checkRow(y, value) == true && checkColumn(x, value) == true && checkGroup(x, y, value) == true){
puzzle.setCount(puzzle.getCount()+1);
puzzle.sudokuGrid[x][y].setValue(value);
nextCell(x,y);
}
}
//resets cell back to unassigned if no valid value found
puzzle.sudokuGrid[x][y].setValue('-');
}
}
/**
* Returns the x,y grid coordinates of a cell
* @param x
* @param y
* @throws Exception
*/
public static void nextCell (int x, int y) throws Exception {
if (x < 15)
assignValue(x+1, y);
else
assignValue(0, y+1);
}
/**
* Constraint: Value must be unique to a cell's row
* @param y
* @param value
* @return
*/
private static boolean checkRow(int y, char value){
for(int x = 0; x < 16; x++){
if (puzzle.sudokuGrid[x][y].getValue() == value){
return false;
}
}
return true;
}
/**
* Constraint: Value must be unique to a cell's column
* @param x
* @param value
* @return
*/
private static boolean checkColumn(int x, char value){
for(int y = 0; y < 16; y++){
if (puzzle.sudokuGrid[x][y].getValue() == value){
return false;
}
}
return true;
}
/**
* Constraint: Value must be unique to a cell's group
* @param x
* @param y
* @param value
* @return
*/
private static boolean checkGroup(int x, int y, char value){
x = (x/4) * 4 ;
y = (y/4) * 4 ;
for(int r = 0; r < 4; r++ )
for(int c = 0; c < 4; c++ ){
if( puzzle.sudokuGrid[x+c][y+r].getValue() == value){
return false;
}
}
return true;
}
}
| true |
12975c942ba6b1609155a31a7bbbb0223be77eb5 | Java | emorynlp/character-identification-old | /src/main/java/edu/emory/mathcs/nlp/mining/character/structure/Utterance.java | UTF-8 | 1,652 | 1.960938 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2016, Emory University
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.emory.mathcs.nlp.mining.character.structure;
import java.io.Serializable;
import java.util.List;
/**
* @author Henry(Yu-Hsin) Chen ({@code yu-hsin.chen@emory.edu})
* @version 1.0
* @since Mar 8, 2016
*/
public class Utterance implements Serializable {
private static final long serialVersionUID = -7666651294661709214L;
/* Class fields ===================================================================== */
public int utterance_id;
public String speaker, utterance_raw, statment_raw;
public List<String> utterance_sentences, statement_sentences;
public List<List<String>>
tokenized_utterance_sentences, tokenized_statement_sentences,
utterance_sentence_annotations, statement_sentence_annotations,
utterance_sentence_pos_tags, statement_sentence_pos_tags,
utterance_sentence_dep_labels, statement_sentence_dep_labels,
utterance_sentence_dep_heads, statement_sentence_dep_heads,
utterance_sentence_ner_tags, statement_sentence_ner_tags;
public List<StatementNode[]> statement_trees;
}
| true |
b0f257c6093776ee193554029c5522a1dc588dd4 | Java | 1171-tlm/ZJKJCode | /ruoyi-system/src/main/java/com/ruoyi/zjkj/mapper/ZjkjProPlanMapper.java | UTF-8 | 1,382 | 1.875 | 2 | [
"MIT"
] | permissive | package com.ruoyi.zjkj.mapper;
import java.util.List;
import com.ruoyi.zjkj.domain.ZjkjProPlan;
/**
* 产品-方案关联Mapper接口
*
* @author taoliming
* @date 2019-09-28
*/
public interface ZjkjProPlanMapper
{
/**
* 查询产品-方案关联
*
* @param planId 产品-方案关联ID
* @return 产品-方案关联
*/
public ZjkjProPlan selectZjkjProPlanById(Long planId);
/**
* 查询产品-方案关联列表
*
* @param zjkjProPlan 产品-方案关联
* @return 产品-方案关联集合
*/
public List<ZjkjProPlan> selectZjkjProPlanList(ZjkjProPlan zjkjProPlan);
/**
* 新增产品-方案关联
*
* @param zjkjProPlan 产品-方案关联
* @return 结果
*/
public int insertZjkjProPlan(ZjkjProPlan zjkjProPlan);
/**
* 修改产品-方案关联
*
* @param zjkjProPlan 产品-方案关联
* @return 结果
*/
public int updateZjkjProPlan(ZjkjProPlan zjkjProPlan);
/**
* 删除产品-方案关联
*
* @param planId 产品-方案关联ID
* @return 结果
*/
public int deleteZjkjProPlanById(Long planId);
/**
* 批量删除产品-方案关联
*
* @param planIds 需要删除的数据ID
* @return 结果
*/
public int deleteZjkjProPlanByIds(String[] planIds);
}
| true |
b44add3df14bd3c27d28e4c77d04e2060cb219e2 | Java | berkson/sfg-pet-clinic | /pet-clinic-data/src/main/java/com/ximenes/sfgpetclinic/services/map/springdatajpa/SpecialtySDJpaService.java | UTF-8 | 1,437 | 2.265625 | 2 | [
"Apache-2.0"
] | permissive | package com.ximenes.sfgpetclinic.services.map.springdatajpa;
import com.ximenes.sfgpetclinic.models.Specialty;
import com.ximenes.sfgpetclinic.repositories.SpecialityRepository;
import com.ximenes.sfgpetclinic.services.SpecialityService;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Berkson Ximenes
* Date: 18/06/2021
* Time: 21:29
*/
@Service
@Profile("springdatajpa")
public class SpecialtySDJpaService implements SpecialityService {
private final SpecialityRepository specialityRepository;
public SpecialtySDJpaService(SpecialityRepository specialityRepository) {
this.specialityRepository = specialityRepository;
}
@Override
public Set<Specialty> findAll() {
Set<Specialty> specialties = new HashSet<>();
specialityRepository.findAll().forEach(specialties::add);
return specialties;
}
@Override
public Specialty findById(Long aLong) {
return specialityRepository.findById(aLong).orElse(null);
}
@Override
public Specialty save(Specialty object) {
return specialityRepository.save(object);
}
@Override
public void delete(Specialty object) {
specialityRepository.delete(object);
}
@Override
public void deleteById(Long aLong) {
specialityRepository.deleteById(aLong);
}
}
| true |
a159b372f15d62fa6b88474c68151f5280d5e1c6 | Java | Merry-00/blog | /src/com/gcl/blog/servlet/DeleteBlog.java | UTF-8 | 1,590 | 2.265625 | 2 | [] | no_license | package com.gcl.blog.servlet;
import com.gcl.blog.model.Blog;
import com.gcl.blog.service.BlogServiceImp;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@WebServlet("/deleteBlog")
public class DeleteBlog extends HttpServlet {
BlogServiceImp blogServiceImp=new BlogServiceImp();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String blogId=req.getParameter("blogId");
Blog blog=blogServiceImp.getBlogById(blogId);
String email=blog.getAuthor_email();
List<Blog> blogs=blogServiceImp.queryMyBlog(email);
if(blogServiceImp.delete(blogId)){
if(blogs==null ||blogs.size()==0){
String message="您还没有发布过文章!";
req.setAttribute("messege",message);
req.getRequestDispatcher("/title.jsp").forward(req,resp);
}
else if(blogs.size()!=0){
req.setAttribute("blogs",blogs);
req.getRequestDispatcher("/title.jsp").forward(req,resp);
}
}
else{
System.out.println("删除失败");
}
}
}
| true |
07f498889bd5ece5c853ba789d2fed7408160c55 | Java | tom200989/zygame | /icegame/src/main/java/com/zygame/icegame/utils/ActionVoiceUtils.java | UTF-8 | 1,985 | 2.65625 | 3 | [] | no_license | package com.zygame.icegame.utils;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.annotation.RawRes;
@SuppressWarnings(value = {"unchecked", "deprecation"})
public class ActionVoiceUtils {
public static MediaPlayer mp;
public static void play(final Context context, @RawRes int rawVoice) {
try {
new Thread(() -> {
// 如果之前有播放过 - 则先释放再重新创建
if (mp != null) {
releaseVoice();
}
// 指定音源
mp = MediaPlayer.create(context, rawVoice);
// 指定播放形式(MUSIC为外放,PHONE为耳机)
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
// 调节音量
mp.setVolume(1.0f, 1.0f);
// 设置播放完毕后的监听
mp.setOnCompletionListener(mps -> {
// 预先准备好一个音源--> 待有新的调用时能马上启动
// 会出现的BUG:如果不设置该监听,则每次有需求调用时候,音源会产生延迟并且有可能会丢失音源而没有正常播放声音
// ActionVoiceUtils.mp = mps;
// ActionVoiceUtils.mp = MediaPlayer.create(context, rawVoice);
});
mp.setOnErrorListener((mp1, what, extra) -> {
play(context, rawVoice);
return true;
});
// 开始播放
/* 注意:使用静态create的方式,不需要在prepare() */
mp.start();
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 释放音频
*/
public static void releaseVoice() {
if (mp != null) {
mp.release();
mp = null;
}
}
}
| true |
56e490721d9c70470dd16a1f93abe15123dbb471 | Java | shitianxianga/mystudy | /src/suanfa/最长上升子序列.java | UTF-8 | 604 | 2.703125 | 3 | [] | no_license | package suanfa;
import java.lang.reflect.Array;
import java.util.Arrays;
public class 最长上升子序列 {
public int lengthOfLIS(int[] nums) {
int[] dp=new int[nums.length+1];
Arrays.fill(dp,1);
int maxs=1;
for (int i=1;i<nums.length;i++)
{
int max=0;
for (int j=0;j<i;j++)
{
if (nums[i]>nums[j])
{
max=Math.max(dp[j]+1,max);
}
}
dp[i]=max;
maxs=Math.max(max,maxs);
}
return maxs;
}
}
| true |
2b5c3c7e373749d9cedf5957fec9e94d5453d907 | Java | xbb2yy/tutorials | /java/src/main/java/com/xubing/pdf/PdfSplit.java | UTF-8 | 2,099 | 2.828125 | 3 | [] | no_license | package com.xubing.pdf;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.*;
public class PdfSplit {
public static void main(String[] args) throws Exception{
InputStream inputStream =new FileInputStream("E:\\WordSpace\\tutorials\\java\\src\\main\\java\\com\\xubing\\pdf\\bb.pdf");
FileOutputStream outputStream = new FileOutputStream("E:/a.pdf");
splitPDF(inputStream, outputStream, 1, 1);
}
public static void splitPDF(InputStream inputStream,
OutputStream outputStream, int fromPage, int toPage) {
Rectangle rect = new Rectangle(PageSize.A4);
Document document = new Document(rect);
try {
PdfReader.unethicalreading = true;
PdfReader inputPDF = new PdfReader(inputStream);
int totalPages = inputPDF.getNumberOfPages();
System.out.println(totalPages);
// Create a writer for the outputstream
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
// Holds the PDF data
PdfImportedPage page = writer.getImportedPage(inputPDF, 1);
document.newPage();
cb.addTemplate(page, 0, 0);
document.newPage();
cb.addTemplate(page, -PageSize.A4.getWidth(), 0);
outputStream.flush();
document.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (document.isOpen())
document.close();
try {
if (outputStream != null)
outputStream.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
| true |
7c89e8abe71f823e05343c3a95de6ce8d97e189b | Java | andyyinggh/hbase | /src/main/java/cn/edu/cuit/quartz/Test.java | UTF-8 | 1,369 | 2.46875 | 2 | [] | no_license | package cn.edu.cuit.quartz;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;
/**
* 调度
* @author guanghua.ying
* @date 2017年7月10日 下午5:40:43
*/
public class Test {
public static void main(String[] args) throws SchedulerException {
SchedulerFactory schedulerFactory = new StdSchedulerFactory();
Scheduler scheduler = schedulerFactory.getScheduler();
JobDetail jobDetail = JobBuilder.newJob(TestJob.class)
.withIdentity("job1", "group1")
.build();
jobDetail.getJobDataMap().put("task", "1234");
Trigger trigger1 = TriggerBuilder.newTrigger()
.withIdentity("trigger1", "group1")
.startNow()
.withSchedule(SimpleScheduleBuilder.simpleSchedule()
.withIntervalInSeconds(5)//每5秒触发一次
.repeatForever())
.build();
Trigger trigger2 = TriggerBuilder.newTrigger()
.withIdentity("simpleTrigger", "triggerGroup")
.withSchedule(CronScheduleBuilder.cronSchedule("0 42 10 * * ? *"))
.startNow().build();
scheduler.scheduleJob(jobDetail, trigger1);
scheduler.start();
}
}
| true |
8a95918d46656427158f3bc77c88db8a43d1d645 | Java | morningblu/HWFramework | /MATE-20_EMUI_11.0.0/src/main/java/com/android/server/rms/iaware/qos/AwareQosFeatureManager.java | UTF-8 | 7,062 | 1.570313 | 2 | [] | no_license | package com.android.server.rms.iaware.qos;
import android.os.IBinder;
import android.os.RemoteException;
import android.rms.iaware.AppTypeRecoManager;
import android.rms.iaware.AwareConfig;
import android.rms.iaware.AwareLog;
import android.rms.iaware.IAwareCMSManager;
import android.rms.iaware.IAwaredConnection;
import com.android.server.mtm.taskstatus.ProcessInfo;
import com.android.server.mtm.taskstatus.ProcessInfoCollector;
import com.android.server.mtm.utils.InnerUtils;
import com.android.server.rms.iaware.appmng.AwareAppAssociate;
import com.android.server.rms.iaware.appmng.AwareAppKeyBackgroup;
import com.android.server.rms.iaware.appmng.AwareIntelligentRecg;
import com.huawei.android.os.ProcessExt;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
public final class AwareQosFeatureManager {
private static final int BYTE_BUFFER_SIZE = 8;
private static final String CONFIG_SUB_SWITCH = "QosConfig";
private static final String FEATURE_ITEM = "featureName";
private static final String FEATURE_NAME = "Qos";
private static final String FEATURE_SUB_NAME = "QosSwitch";
private static final String LABEL_SWITCH = "switch";
private static final Object LOCAL_LOCK = new Object();
private static final int MSG_BASE_VALUE = 100;
private static final int MSG_QOS_SCHED_SWITCH = 181;
private static final int QOS_SCHED_SET_ENABLE_FLAG = 1;
private static final String TAG = "AwareQosFeatureManager";
private static AwareQosFeatureManager sInstance = null;
private int mSwitchOfFeature = 0;
private AwareQosFeatureManager() {
getAwareQosFeatureSwitch();
}
public static AwareQosFeatureManager getInstance() {
AwareQosFeatureManager awareQosFeatureManager;
synchronized (LOCAL_LOCK) {
if (sInstance == null) {
sInstance = new AwareQosFeatureManager();
}
awareQosFeatureManager = sInstance;
}
return awareQosFeatureManager;
}
private void getAwareQosFeatureSwitch() {
try {
IBinder awareService = IAwareCMSManager.getICMSManager();
if (awareService != null) {
AwareConfig switchConfig = IAwareCMSManager.getCustConfig(awareService, FEATURE_NAME, CONFIG_SUB_SWITCH);
if (switchConfig == null) {
switchConfig = IAwareCMSManager.getConfig(awareService, FEATURE_NAME, CONFIG_SUB_SWITCH);
}
getSwitchConfig(switchConfig);
return;
}
AwareLog.w(TAG, "getAwareConfig can not find service awareService.");
} catch (RemoteException e) {
AwareLog.e(TAG, "getAwareConfig RemoteException");
}
}
private void getSwitchConfig(AwareConfig awareConfig) {
Map<String, String> configProperties;
if (awareConfig == null) {
AwareLog.w(TAG, "get cust aware config failed!");
return;
}
List<AwareConfig.Item> itemList = awareConfig.getConfigList();
if (itemList != null) {
for (AwareConfig.Item item : itemList) {
if (!(item == null || (configProperties = item.getProperties()) == null)) {
String featureName = configProperties.get(FEATURE_ITEM);
if (featureName != null) {
parseSwitchValue(item, featureName);
} else {
return;
}
}
}
}
}
private void parseSwitchValue(AwareConfig.Item item, String featureName) {
List<AwareConfig.SubItem> subItemList = item.getSubItemList();
if (subItemList == null) {
AwareLog.w(TAG, "get sub switch config item failed!");
return;
}
for (AwareConfig.SubItem subItem : subItemList) {
if (subItem != null) {
String itemName = subItem.getName();
String itemValue = subItem.getValue();
if ("switch".equals(itemName)) {
parseAllSwitch(itemValue, featureName);
}
}
}
}
private void parseAllSwitch(String data, String featureName) {
if (data != null && FEATURE_SUB_NAME.equals(featureName)) {
try {
this.mSwitchOfFeature = Integer.parseInt(data);
} catch (NumberFormatException e) {
AwareLog.e(TAG, "parseAllSwitch parseInt QosSwitch failed!");
}
}
}
private void setQosSwitch(int value) {
AwareLog.i(TAG, "setQosSwitch, value=" + value);
if ((value & 1) != 0) {
ProcessExt.setQosSched(true);
} else {
ProcessExt.setQosSched(false);
}
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.putInt(MSG_QOS_SCHED_SWITCH);
buffer.putInt(value);
boolean isResCode = IAwaredConnection.getInstance().sendPacket(buffer.array(), 0, buffer.position());
if (!isResCode) {
AwareLog.e(TAG, "setQosSwitch: sendPacket failed, switch: " + value + ", send error code: " + isResCode);
}
}
public void enable() {
setQosSwitch(this.mSwitchOfFeature);
AwareBinderSchedManager.getInstance().enable(this.mSwitchOfFeature);
}
public void disable() {
setQosSwitch(0);
AwareBinderSchedManager.getInstance().disable();
}
public boolean doCheckPreceptible(int pid) {
ProcessInfo procInfo;
String pkgName;
int type;
if (!AwareNetQosSchedManager.getAwareNetQosSchedSwitch() || (procInfo = ProcessInfoCollector.getInstance().getProcessInfo(pid)) == null || !AwareAppKeyBackgroup.getInstance().checkKeyBackgroupByState(5, procInfo.mPid, procInfo.mUid, procInfo.mPackageName) || AwareAppAssociate.getInstance().isVisibleWindow(pid) || AwareIntelligentRecg.getInstance().isScreenRecordEx(procInfo) || AwareAppKeyBackgroup.getInstance().checkKeyBackgroupByState(2, procInfo.mPid, procInfo.mUid, procInfo.mPackageName) || AwareAppKeyBackgroup.getInstance().checkKeyBackgroupByState(3, procInfo.mPid, procInfo.mUid, procInfo.mPackageName) || (pkgName = getAppPkgName(pid, procInfo.mUid)) == null || (type = AppTypeRecoManager.getInstance().getAppType(pkgName)) == 0 || type == -1) {
return true;
}
AwareLog.d(TAG, "doCheckPreceptible " + pkgName + " pid=" + pid + " is unpreceptible");
return false;
}
private String getAppPkgName(int pid, int uid) {
if (pid > 0) {
return InnerUtils.getAwarePkgName(pid);
}
return InnerUtils.getPackageNameByUid(uid);
}
public void setAppVipThreadForQos(int pid, List<Integer> threads) {
if (!((this.mSwitchOfFeature & 1) == 0 || threads == null || pid <= 0)) {
for (int i = 0; i < threads.size(); i++) {
ProcessExt.setThreadQosPolicy(threads.get(i).intValue(), 10);
}
}
}
}
| true |
2f2fdddeda0ffaff9203b454f2ef2c751ea5662a | Java | xavierdpt/braindump | /welcome/numbers/src/test/java/numbers/CastTest.java | UTF-8 | 1,527 | 2.734375 | 3 | [] | no_license | package numbers;
import org.junit.jupiter.api.Test;
class CastTest {
@Test
void test() {
byte b = 0;
short s = 0;
int i = 0;
long l = 0L;
float f = 0F;
double d = 0D;
giveMeAByte(b);
giveMeAByte((byte) s);
giveMeAByte((byte) i);
giveMeAByte((byte) l);
giveMeAByte((byte) f);
giveMeAByte((byte) d);
giveMeAShort(b);
giveMeAShort(s);
giveMeAShort((short) i);
giveMeAShort((short) l);
giveMeAShort((short) f);
giveMeAShort((short) d);
giveMeAnInt(b);
giveMeAnInt(s);
giveMeAnInt(i);
giveMeAnInt((int) l);
giveMeAnInt((int) f);
giveMeAnInt((int) d);
giveMeALong(b);
giveMeALong(s);
giveMeALong(i);
giveMeALong(l);
giveMeALong((long) f);
giveMeALong((long) d);
giveMeAFloat(b);
giveMeAFloat(s);
giveMeAFloat(i);
giveMeAFloat(l);
giveMeAFloat(f);
giveMeAFloat((float) d);
giveMeADouble(b);
giveMeADouble(s);
giveMeADouble(i);
giveMeADouble(l);
giveMeADouble(f);
giveMeADouble(d);
}
private void giveMeAByte(byte b) {
}
private void giveMeAShort(short s) {
}
private void giveMeALong(long l) {
}
private void giveMeAnInt(int i) {
}
private void giveMeAFloat(float f) {
}
private void giveMeADouble(double d) {
}
}
| true |
98c3269065c12bd82d4bb32797b7bcd5c11445cf | Java | captainbupt/Douxing | /app/src/main/java/com/badou/mworking/ChattingActivity.java | UTF-8 | 6,883 | 2.03125 | 2 | [] | no_license | /*
* 文件名: ChatInfoActivity.java
* 包路径: com.badou.mworking
* 创建描述
* 创建人:葛建锋
* 创建日期:2014年9月18日 下午3:47:22
* 内容描述:
* 修改描述
* 修改人:葛建锋
* 修改日期:2014年9月18日 下午3:47:22
* 修改内容:
* 版本: V1.0
*/
package com.badou.mworking;
import android.os.Bundle;
import android.widget.ListView;
import com.badou.mworking.adapter.ChatInfoAdapter;
import com.badou.mworking.base.AppApplication;
import com.badou.mworking.base.BaseBackActionBarActivity;
import com.badou.mworking.model.ChatInfo;
import com.badou.mworking.net.Net;
import com.badou.mworking.net.ServiceProvider;
import com.badou.mworking.net.volley.VolleyListener;
import com.badou.mworking.util.ToastUtil;
import com.badou.mworking.widget.BottomSendMessageView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* 功能描述: 聊天页面
*/
public class ChattingActivity extends BaseBackActionBarActivity {
private BottomSendMessageView mBottomView;
private PullToRefreshListView mContentListView;
private String whom = "";
private String img = "";
private String mHeadImgUrl = "";
private ChatInfoAdapter mAdapter;
public static final String KEY_WHOM = "whom";
public static final String KEY_OTHER_IMG = "img";
public static final String KEY_NAME = "name";
public static final String KEY_SELF_IMG = "myimg";
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_chatting);
whom = getIntent().getStringExtra(KEY_WHOM);
img = getIntent().getStringExtra(KEY_OTHER_IMG);
mHeadImgUrl = getIntent().getStringExtra(KEY_SELF_IMG);
initView();
initListener();
mContentListView.setRefreshing();
}
/**
* 功能描述: 控件初始化
*/
private void initView() {
mContentListView = (PullToRefreshListView) findViewById(R.id.ptrlv_activity_chatting);
mContentListView.setMode(Mode.PULL_FROM_START);
mBottomView = (BottomSendMessageView) findViewById(R.id.bsmv_activity_chatting);
mAdapter = new ChatInfoAdapter(mContext, whom, img,
mHeadImgUrl);
mContentListView.setAdapter(mAdapter);
}
protected void initListener() {
mContentListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
updateChatMsg();
}
});
mBottomView.setOnSubmitListener(new BottomSendMessageView.OnSubmitListener() {
@Override
public void onSubmit(String content) {
submitChatMsg(content);
}
});
}
private void submitChatMsg(final String content) {
ServiceProvider.doSendChat(mContext, content, whom, new VolleyListener(
mContext) {
@Override
public void onResponseSuccess(JSONObject response) {
ChatInfo chatInfo = new ChatInfo();
chatInfo.setContent(content);
chatInfo.setTs(System.currentTimeMillis() / 1000);
mAdapter.addItem(chatInfo);
/** 发送成功后滚动到底部 **/
ListView lv = mContentListView.getRefreshableView();
lv.setSelection(lv.getBottom());
}
});
}
private void updateChatMsg() {
ServiceProvider.dogetChatInfo(mContext, whom,
new VolleyListener(mContext) {
@Override
public void onResponse(Object responseObject) {
if (mContentListView != null) {
mContentListView.onRefreshComplete();
}
JSONObject responseJson = (JSONObject) responseObject;
int code = responseJson.optInt(Net.CODE);
if (code == Net.LOGOUT) {
AppApplication.logoutShow(mContext);
return;
}
if (Net.SUCCESS != code) {
ToastUtil.showNetExc(mContext);
return;
}
JSONArray arrJson = responseJson
.optJSONArray(Net.DATA);
List<Object> chatInfoList = new ArrayList<>();
try {
for (int i = 0; i < arrJson.length(); i++) {
String jo = (String) arrJson.get(i);
JSONObject jsonObject = new JSONObject(
jo);
chatInfoList.add(new ChatInfo(
jsonObject));
}
} catch (JSONException e) {
e.printStackTrace();
}
mAdapter.setList(chatInfoList);
/** 发送成功后滚动到底部 **/
ListView lv = mContentListView.getRefreshableView();
lv.setSelection(lv.getBottom());
}
@Override
public void onCompleted() {
if (mContentListView != null) {
mContentListView.onRefreshComplete();
}
}
@Override
public void onResponseSuccess(JSONObject response) {
JSONArray arrJson = response.optJSONArray(Net.DATA);
List<Object> chatInfoList = new ArrayList<>();
for (int i = 0; i < arrJson.length(); i++) {
JSONObject jsonObject = arrJson.optJSONObject(i);
chatInfoList.add(new ChatInfo(
jsonObject));
}
mAdapter.setList(chatInfoList);
/** 发送成功后滚动到底部 **/
ListView lv = mContentListView.getRefreshableView();
lv.setSelection(lv.getBottom());
}
});
}
}
| true |
f70ec880ad5e604e5bbafcc6081de3f7f4a8c571 | Java | btgould/mistborn-game | /src/main/java/com/pisoft/mistborn_game/display/Board.java | UTF-8 | 3,059 | 2.5625 | 3 | [] | no_license | package com.pisoft.mistborn_game.display;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import com.pisoft.mistborn_game.Game;
import com.pisoft.mistborn_game.controllers.KeyBinder;
import com.pisoft.mistborn_game.player.Side;
import com.pisoft.mistborn_game.player.intents.AccelerateIntent;
import com.pisoft.mistborn_game.player.intents.CrouchIntent;
import com.pisoft.mistborn_game.player.intents.JumpIntent;
import com.pisoft.mistborn_game.player.intents.PrepRunIntent;
import com.pisoft.mistborn_game.player.intents.StopAccIntent;
import com.pisoft.mistborn_game.player.intents.StopCrouchIntent;
import com.pisoft.mistborn_game.player.intents.StopJumpIntent;
import com.pisoft.mistborn_game.player.intents.StopPrepRunIntent;
public class Board extends JPanel {
private static final long serialVersionUID = -3991296469087660042L;
private final int WIDTH = 500;
private final int HEIGHT = 500;
private Painter painter = new Painter();
private KeyBinder keyBinder;
public Board() {
initBoard();
initKeyBindings();
}
// initialization
// ---------------------------------------------------------------------------------------------------
private void initBoard() {
setKeyBinder(new KeyBinder(this));
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
}
private void initKeyBindings() {
keyBinder.getKeyBindings().put(KeyEvent.VK_RIGHT, new AccelerateIntent(Side.RIGHT));
keyBinder.getKeyBindings().put(KeyEvent.VK_LEFT, new AccelerateIntent(Side.LEFT));
keyBinder.getKeyBindings().put(KeyEvent.VK_UP, new JumpIntent());
keyBinder.getKeyBindings().put(KeyEvent.VK_DOWN, new CrouchIntent());
keyBinder.getKeyBindings().put(KeyEvent.VK_SHIFT, new PrepRunIntent());
keyBinder.getKeyBindings().put(KeyEvent.VK_RIGHT + KeyBinder.RELEASED, new StopAccIntent(Side.RIGHT));
keyBinder.getKeyBindings().put(KeyEvent.VK_LEFT + KeyBinder.RELEASED, new StopAccIntent(Side.LEFT));
keyBinder.getKeyBindings().put(KeyEvent.VK_UP + KeyBinder.RELEASED, new StopJumpIntent());
keyBinder.getKeyBindings().put(KeyEvent.VK_DOWN + KeyBinder.RELEASED, new StopCrouchIntent());
keyBinder.getKeyBindings().put(KeyEvent.VK_SHIFT + KeyBinder.RELEASED, new StopPrepRunIntent());
}
// drawing
// ---------------------------------------------------------------------------------------------------
@Override
protected void paintComponent(Graphics g) {
// paint background
super.paintComponent(g);
// paint active level
if (Game.getActiveLevel() != null) {
painter.paintLevel(g, Game.getActiveLevel());
}
// prevent excessive buffering of graphics events
Toolkit.getDefaultToolkit().sync();
}
// getters and setters
// ---------------------------------------------------------------------------------------------------
public int getOne() {
return 1;
}
public KeyBinder getKeyBinder() {
return keyBinder;
}
public void setKeyBinder(KeyBinder keyBinder) {
this.keyBinder = keyBinder;
}
}
| true |
b6d653542ce0bd47fa3fa9cbf1f994f559eeeaba | Java | abhiruppradhan/zomatotest | /zomatotest1/src/main/java/com/abhirup/pradhan/model/Product.java | UTF-8 | 1,427 | 2.203125 | 2 | [] | no_license | package com.abhirup.pradhan.model;
import javax.persistence.*;
@Entity
public class Product {
@Id
private long product_Id;
private String product_Name;
private String product_Description;
private double product_Price;
private double product_Offer;
private int product_Count;
private int active;
public int getActive() {
return active;
}
public void setActive(int active) {
this.active = active;
}
public long getProduct_Id() {
return product_Id;
}
public void setProduct_Id(long product_Id) {
this.product_Id = product_Id;
}
public String getProduct_Name() {
return product_Name;
}
public void setProduct_Name(String product_Name) {
this.product_Name = product_Name;
}
public String getProduct_Description() {
return product_Description;
}
public void setProduct_Description(String product_Description) {
this.product_Description = product_Description;
}
public double getProduct_Price() {
return product_Price;
}
public void setProduct_Price(double product_Price) {
this.product_Price = product_Price;
}
public double getProduct_Offer() {
return product_Offer;
}
public void setProduct_Offer(double product_Offer) {
this.product_Offer = product_Offer;
}
public int getProduct_Count() {
return product_Count;
}
public void setProduct_Count(int product_Count) {
this.product_Count = product_Count;
}
}
| true |
95427a002c27403bbaed56f1ffae0ce35b578001 | Java | ApolloPonos/workplace | /Ornek/edu/java/nnp/soru13.java | UTF-8 | 280 | 2.578125 | 3 | [] | no_license | //DIZININ SONUNCU ELEMANINI YAZDIRAN PROGRAM
package edu.java.nnp;
public class soru13 {
public static void main(String[] args) {
String kahvalti[] = { "Kasar", "Yumurta", "Domates", "Salatalik" };
int i;
for (i = 0; i < 1; i++)
System.out.println(kahvalti[3]);
}
}
| true |
1fbb00f07cfedb8839a646fa0baa683e73faa4fd | Java | edgarlopez85/restMathOperations | /src/main/java/com/example/rest/service/MathOperations.java | UTF-8 | 575 | 2.265625 | 2 | [] | no_license | package com.example.rest.service;
import com.example.rest.model.Response;
import com.example.rest.utils.AppUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
public class MathOperations {
private final AppUtils appUtils;
public Response buildResponse(int num){
return Response.builder()
.primeNumber(appUtils.isPrime(num))
.evenNumber(appUtils.isEven(num))
.factorial(appUtils.getFactorial(num))
.build();
}
}
| true |
f5acc2aaef7c5af5f48019475fd0fa4858a71729 | Java | mivola/hwd-ng | /src/com/voigt/hwd/client/admin/ds/IDataSourceManager.java | UTF-8 | 397 | 1.734375 | 2 | [] | no_license | package com.voigt.hwd.client.admin.ds;
import com.smartgwt.client.data.DataSource;
import com.smartgwt.client.widgets.form.fields.FormItem;
public interface IDataSourceManager {
final static String ID_FIELD = "id";
public DataSource getDataSource();
public boolean updateExisting(int pk, FormItem[] fields);
public boolean saveNew(FormItem[] fields);
public boolean delete(int pk);
}
| true |
fc893b887d4e206f6b105f0f1a13b80f1c5526a2 | Java | birhanuh/RSSISimilarityWeb | /src/net/obsearch/ambient/bdb/AmbientBDBJe.java | UTF-8 | 2,847 | 2.140625 | 2 | [] | no_license | package net.obsearch.ambient.bdb;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import net.obsearch.Index;
import net.obsearch.OB;
import net.obsearch.ambient.AbstractAmbient;
import net.obsearch.exception.AlreadyFrozenException;
import net.obsearch.exception.NotFrozenException;
import net.obsearch.exception.OBException;
import net.obsearch.exception.OBStorageException;
import net.obsearch.storage.OBStoreFactory;
import net.obsearch.storage.bdb.BDBFactoryJe;
/*
OBSearch: a distributed similarity search engine This project is to
similarity search what 'bit-torrent' is to downloads.
Copyright (C) 2008 Arnoldo Jose Muller Molina
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/>.
*/
/**
* AmbientBDB creates an ambient based on the Berkeley DB storage sub-system.
* @author Arnoldo Jose Muller Molina
*/
public class AmbientBDBJe<O extends OB, I extends Index<O>> extends AbstractAmbient<O, I>{
/**
* @see net.obsearch.result.ambient.AbstractAmbient#AbstractAmbient(I index, File directory)
*/
public AmbientBDBJe(I index, File directory) throws FileNotFoundException, OBStorageException,
NotFrozenException, IllegalAccessException, InstantiationException,
OBException, IOException{
super(index,directory);
}
/**
* @see net.obsearch.result.ambient.AbstractAmbient#AbstractAmbient(File directory)
*/
public AmbientBDBJe(File directory) throws FileNotFoundException, OBStorageException,
NotFrozenException, IllegalAccessException, InstantiationException,
OBException, IOException{
super(directory);
}
/* (non-Javadoc)
* @see net.obsearch.ambient.AbstractAmbient#createFactory(java.io.File)
*/
@Override
protected BDBFactoryJe createFactory(File factoryDirectory) throws OBStorageException{
BDBFactoryJe fact = null;
try{
fact = new BDBFactoryJe(factoryDirectory);
}catch(Exception e){
throw new OBStorageException(e);
}
return fact;
}
}
| true |
0877faf5a74389462934409bd59322ccf3b803f7 | Java | heduiandroid/HDLinLiC | /java/com/linli/consumer/net/NetUtil.java | UTF-8 | 5,983 | 2.28125 | 2 | [] | no_license | package com.linli.consumer.net;
import com.linli.consumer.common.Common;
import com.linli.consumer.common.FastJsonConverterFactory;
import com.linli.consumer.iface.HandleError;
import java.util.HashMap;
import java.util.Map;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by tomoyo on 2016/11/4.
*/
public class NetUtil {
public static final String BASE_URL_V2 = Common.myUrl; //线上域名地址
@Deprecated
private static Converter.Factory fastJsonConverter = FastJsonConverterFactory.create(); //converter转换器
private static OkHttpClient okHttpClient = null;
private static Map<String, Object> serviceCache = new HashMap<>(); //api缓存
private static IFoodsApi iFoodsApi ; //美食api
private static IShopApi iShopApi; //商城api
private static OkHttpClient httpLog() {
if (okHttpClient == null) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient = new OkHttpClient.Builder()
//.readTimeout(30, TimeUnit.SECONDS)
//.writeTimeout(30,TimeUnit.SECONDS)
//.connectTimeout(30,TimeUnit.SECONDS)
.addInterceptor(interceptor)
.build();
}
return okHttpClient;
}
private static NetUtil mInstance; //单例
public static synchronized NetUtil getInstance() {
if (mInstance == null) {
mInstance = new NetUtil();
}
return mInstance;
}
/**
* 捕获全局网络异常
* */
public HandleError handleGlobeResponseError() {
return new HandleError() {
@Override
public void error(Throwable t) {
// Toast.makeText(AppContext.getInstance(),"无网络或网络环境较差",Toast.LENGTH_SHORT).show();
//Log.i("WATER",t.getMessage());
}
};
}
public static IIntrestBuyApi createVoiceApi(String baseUrl){
IIntrestBuyApi iIntrestBuy = (IIntrestBuyApi)serviceCache.get(baseUrl);
if (iIntrestBuy == null){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(NetUtil.httpLog())
.build();
iIntrestBuy = retrofit.create(IIntrestBuyApi.class);
serviceCache.put(baseUrl, iIntrestBuy);
}
return iIntrestBuy;
}
/**
* 邻里api
* @param baseUrl 根地址
* */
public static CafeNetApi createCnApi(String baseUrl){
CafeNetApi cafeNetApi = (CafeNetApi)serviceCache.get(baseUrl);
if(cafeNetApi == null){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(NetUtil.httpLog())
.build();
cafeNetApi = retrofit.create(CafeNetApi.class);
serviceCache.put(baseUrl, cafeNetApi);
}
return cafeNetApi;
}
/**
* 趣购api
* @param baseUrl 根地址
* */
public static IIntrestBuyApi createMcApi(String baseUrl){
IIntrestBuyApi iIntrestBuy = (IIntrestBuyApi)serviceCache.get(baseUrl);
if(iIntrestBuy == null){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(NetUtil.httpLog())
.build();
iIntrestBuy = retrofit.create(IIntrestBuyApi.class);
serviceCache.put(baseUrl, iIntrestBuy);
}
return iIntrestBuy;
}
/**
* 返回美食的接口
* @param baseUrl 地址是IFoodApi中的
* */
public static IFoodsApi createFoodApi(String baseUrl){
//IFoodsApi api = (IFoodsApi)serviceCache.get(baseUrl);
IFoodsApi api = iFoodsApi;
if(api == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(fastJsonConverter)
.client(NetUtil.httpLog())
.build();
api = retrofit.create(IFoodsApi.class);
//serviceCache.put(baseUrl, api);
}
return api;
}
/**
* 返回美食的接口,为了使用restful风格的api,建了两个
*
* @param baseUrl 地址是IFoodsApiTenant中的
* */
public static IFoodsApiTenant createFoodTenantApi(String baseUrl){
IFoodsApiTenant api = (IFoodsApiTenant)serviceCache.get(baseUrl);
if(api == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(fastJsonConverter)
.client(NetUtil.httpLog())
.build();
api = retrofit.create(IFoodsApiTenant.class);
serviceCache.put(baseUrl, api);
}
return api;
}
/**
* 返回商城的接口
* @param baseUrl 地址是IFoodApi中的
* */
public static IShopApi createShopApi(String baseUrl){
IShopApi api = iShopApi;
//IShopApi api = (IShopApi)serviceCache.get(baseUrl);
if(api == null) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(fastJsonConverter)
.client(NetUtil.httpLog())
.build();
api = retrofit.create(IShopApi.class);
//serviceCache.put(baseUrl, api);
}
return api;
}
}
| true |
29c7de88bb269d8405631ce76aeabe65d66173c1 | Java | wujialing1988/jx_kny | /JX_KNY/src/com/yunda/twt/webservice/service/ITrainStatusManageService.java | UTF-8 | 1,529 | 2.359375 | 2 | [] | no_license | package com.yunda.twt.webservice.service;
/**
* <li>标题: 机车整备管理信息系统
* <li>说明: 此接口管理机车状态信息
* <li>创建人:程锐
* <li>创建日期:2015-2-6
* <li>修改人:
* <li>修改日期:
* <li>修改内容:
* <li>版权: Copyright (c) 2008 运达科技公司
* @author 信息系统事业部整备系统项目组
* @version 1.0
*/
public interface ITrainStatusManageService {
/**
* <li>说明:在没有股道自动化时,如果手工将机车拖放到台位图上时,台位图通过此服务获取机车当前状态
* <li>创建人:程锐
* <li>创建日期:2015-2-6
* <li>修改人:
* <li>修改日期:
* <li>修改内容:
* @param trainInfo 机车信息JSON字符串
* @return 机车状态中文名
*/
public String getTrainStatus(String trainInfo);
/**
* <li>说明:台位图服务端手工修改机车状态后,需要调用此服务通知web服务子系统,web服务子系统调用设置接车状态通知台位图服务端,由台位图服务端通知各个台位图客户端
* <li>创建人:程锐
* <li>创建日期:2015-2-6
* <li>修改人:
* <li>修改日期:
* <li>修改内容:
* @param trainInfo 机车信息JSON字符串
* @param status 机车状态
* @return 操作是否成功的字符串
*/
public String updateTrainStatus(String trainInfo, String status);
}
| true |
41e8620331120a4c0fd21657ddf9e55e63dcee66 | Java | tcf1207239873/Logi-KafkaManager | /kafka-manager-common/src/main/java/com/xiaojukeji/kafka/manager/common/entity/pojo/HeartbeatDO.java | UTF-8 | 1,486 | 2.1875 | 2 | [
"Apache-2.0"
] | permissive | package com.xiaojukeji.kafka.manager.common.entity.pojo;
import java.util.Date;
/**
* 心跳
* @author zengqiao
* @date 20/8/10
*/
public class HeartbeatDO implements Comparable<HeartbeatDO> {
private Long id;
private String ip;
private String hostname;
private Date createTime;
private Date modifyTime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getModifyTime() {
return modifyTime;
}
public void setModifyTime(Date modifyTime) {
this.modifyTime = modifyTime;
}
@Override
public String toString() {
return "HeartbeatDO{" +
"id=" + id +
", ip='" + ip + '\'' +
", hostname='" + hostname + '\'' +
", createTime=" + createTime +
", modifyTime=" + modifyTime +
'}';
}
@Override
public int compareTo(HeartbeatDO heartbeatDO) {
return this.id.compareTo(heartbeatDO.id);
}
} | true |
b22875c1f06deeb926bd9123488dedd77ac75c69 | Java | ruimoliveira/SDIS | /src/peer/RandomGenerator.java | UTF-8 | 321 | 2.578125 | 3 | [] | no_license | package peer;
import java.util.Random;
class RandomGenerator {
private static Random rng = new Random();
public static void waitUpTo(int miliseconds){
try {
Thread.sleep(rng.nextInt(miliseconds + 1));
} catch (InterruptedException e) {}
}
public static double newFraction(){
return Math.random();
}
}
| true |
8dc751787f6d6eb22e5eaa53ec8195f8e447d219 | Java | slhenryy/CMS-ANDROID-TV | /app/src/main/java/com/example/androidcamera/fragments/chooseStorage.java | UTF-8 | 3,819 | 2.09375 | 2 | [] | no_license | package com.example.androidcamera.fragments;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.androidcamera.R;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import static android.content.Context.USB_SERVICE;
public class chooseStorage extends Fragment {
boolean isAvailable= false;
boolean isWritable= false;
boolean isReadable= false;
Spinner spinner;
Button button;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_choose_storage, container, false);
File[] externalStorageFiles= ContextCompat.getExternalFilesDirs(getContext(),null);
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
// Read and write operation possible
isAvailable= true;
isWritable= true;
isReadable= true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
// Read operation possible
isAvailable= true;
isWritable= false;
isReadable= true;
} else {
// SD card not mounted
isAvailable = false;
isWritable= false;
isReadable= false; }
spinner=view.findViewById(R.id.storageType);
button=view.findViewById(R.id.button2);
List<String> list = new ArrayList<String>();
list.add("Cam 1");
list.add("Cam 2");
list.add("Cam 3");
list.add("Cam 4");
list.add("Cam 5");
list.add("Cam 6");
list.add("Cam 7");
list.add("Cam 8");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*
String storage= spinner.getSelectedItem().toString();
Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory()+"");
if (storage.equals("Internal Storage"))
selectedUri = Uri.parse("/storage/emulated/0/");
else
selectedUri = Uri.parse("/storage/");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");
if (intent.resolveActivityInfo(getContext().getPackageManager(), 0) != null) {
startActivity(intent);
} else {
Toast.makeText(getContext(), "File Manager Not Available", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(Settings.ACTION_INTERNAL_STORAGE_SETTINGS);
startActivityForResult(intent, 0); */
getFragmentManager().beginTransaction().replace(R.id.mainframe,new BlankFragment()).commit();}
});
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getContext(),android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
return view;
}
} | true |
66d673fdf532d3f9977e6d7bf065880b6952f017 | Java | vermeer-1977-blog/annotation-processor | /src/test/resources/packagetest/EnumBaseSubPackageName.java | UTF-8 | 456 | 1.820313 | 2 | [
"Apache-2.0"
] | permissive | package packagetest;
import org.vermeer1977.infrastructure.annotation.processor.resource.GenerateResourceEnum;
import org.vermeer1977.infrastructure.annotation.processor.resource.TargetResource;
/**
*
* @author Yamashita,Takahiro
*/
@GenerateResourceEnum(basePackageName = "BasePackage", subPackageName = "SubPackage2")
public class EnumBaseSubPackageName {
@TargetResource
final String resourceName = "resource.message9";
}
| true |
563d0e60eca9219980d245316e8a73fd026fac1b | Java | fengao/SIM | /src/com/maxwit/witim/DBManager.java | UTF-8 | 5,525 | 2.53125 | 3 | [] | no_license | package com.maxwit.witim;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class DBManager {
private DBHelper helper;
private SQLiteDatabase database;
public DBManager(Context context) {
helper = new DBHelper(context);
}
public boolean updateBySQL(String sql, Object[] bindArgs) {
boolean flag = false;
try {
database.execSQL(sql, bindArgs);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
public Map<String, String> queryBySQL(String sql, String[] selectionArgs) {
Map<String, String> map = new HashMap<String, String>();
Cursor cursor = database.rawQuery(sql, selectionArgs);
int cols_len = cursor.getColumnCount();
while (cursor.moveToNext()) {
for (int i = 0; i < cols_len; i++) {
String cols_name = cursor.getColumnName(i);
String cols_value = cursor.getString(cursor
.getColumnIndex(cols_name));
if (cols_value == null) {
cols_value = "";
}
map.put(cols_name, cols_value);
}
}
return map;
}
public void getDataBaseConn() {
database = helper.getWritableDatabase();
}
public void releaseConn() {
if (database != null) {
database.close();
}
}
public List<Map<String, String>> queryMultiMaps(String sql,
String[] selectionArgs) {
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Cursor cursor = database.rawQuery(sql, selectionArgs);
int cols_len = cursor.getColumnCount();
while (cursor.moveToNext()) {
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < cols_len; i++) {
String cols_name = cursor.getColumnName(i);
String cols_value = cursor.getString(cursor
.getColumnIndex(cols_name));
if (cols_value == null) {
cols_value = "";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
return list;
}
public <T> T querySingleCursor(String sql, String[] selectionArgs,
Class<T> cls) {
T t = null;
Cursor cursor = database.rawQuery(sql, selectionArgs);
int cols_len = cursor.getColumnCount();
while (cursor.moveToNext()) {
try {
t = cls.newInstance();
for (int i = 0; i < cols_len; i++) {
String cols_name = cursor.getColumnName(i);
String cols_value = cursor.getString(cursor
.getColumnIndex(cols_name));
if (cols_value == null) {
cols_value = "";
}
Field field = cls.getDeclaredField(cols_name);
field.setAccessible(true);
field.set(t, cols_value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return t;
}
public <T> List<T> queryMultiCursor(String sql, String[] selectionArgs,
Class<T> cls) {
List<T> list = new ArrayList<T>();
Cursor cursor = database.rawQuery(sql, selectionArgs);
int cols_len = cursor.getColumnCount();
while (cursor.moveToNext()) {
try {
T t = cls.newInstance();
for (int i = 0; i < cols_len; i++) {
String cols_name = cursor.getColumnName(i);
String cols_value = cursor.getString(cursor
.getColumnIndex(cols_name));
if (cols_value == null) {
cols_value = "";
}
Field field = cls.getDeclaredField(cols_name);
field.setAccessible(true);
field.set(t, cols_value);
list.add(t);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
/**
*
* @param table
* @param nullColumnHack
* @param values
* @return
*/
public boolean insert(String table, String nullColumnHack,
ContentValues values) {
boolean flag = false;
// insert into tableName(a,b,c) values(?,?,?);
long id = database.insert(table, nullColumnHack, values);
flag = (id > 0 ? true : false);
return flag;
}
/**
* update tableName set name = ? ,address = ?, age = ? where pid = ?
*
* @param table
* @param values
* @param whereClause
* @param whereArgs
* @return
*/
public boolean update(String table, ContentValues values,
String whereClause, String[] whereArgs) {
boolean flag = false;
int count = database.update(table, values, whereClause, whereArgs);
flag = (count > 0 ? true : false);
return flag;
}
/**
* delete from tableName where pid = ?
*
* @param table
* @param whereClause
* @param whereArgs
* @return
*/
public boolean delete(String table, String whereClause, String[] whereArgs) {
boolean flag = false;
int count = database.delete(table, whereClause, whereArgs);
flag = (count > 0 ? true : false);
return flag;
}
/**
* select [distinct][columnName]... from tableName
* [where][selection][selectionArgs] [groupBy][having][order by][limit];
*
* @param distinct
* @param table
* @param columns
* @param selection
* @param selectionArgs
* @param groupBy
* @param having
* @param orderBy
* @param limit
* @return
*/
public Cursor query(String table, String[] columns, String selection,
String[] selectionArgs, String groupBy, String having,
String orderBy, String limit) {
Cursor cursor = null;
cursor = database.query(table, columns, selection, selectionArgs,
groupBy, having, orderBy, limit);
return cursor;
}
/**
* @param sql
* @param selectionArgs
* @return
*/
public Cursor queryMultiCursor(String sql, String[] selectionArgs) {
Cursor cursor = database.rawQuery(sql, selectionArgs);
return cursor;
}
} | true |
73ba77ea86a233dfeade058b748fd7755db4bfce | Java | lanmolsz/wms | /java/Dddml.Wms.JavaCommon/src/generated/java/org/dddml/wms/domain/organizationstructure/OrganizationStructureStateEventDtoConverter.java | UTF-8 | 3,483 | 2.453125 | 2 | [] | no_license | package org.dddml.wms.domain.organizationstructure;
import java.util.*;
import java.util.Date;
import org.dddml.wms.domain.*;
import org.dddml.wms.specialization.*;
public class OrganizationStructureStateEventDtoConverter {
public OrganizationStructureStateEventDto toOrganizationStructureStateEventDto(AbstractOrganizationStructureEvent stateEvent) {
if (stateEvent instanceof AbstractOrganizationStructureEvent.AbstractOrganizationStructureStateCreated) {
OrganizationStructureEvent.OrganizationStructureStateCreated e = (OrganizationStructureEvent.OrganizationStructureStateCreated) stateEvent;
return toOrganizationStructureStateCreatedDto(e);
} else if (stateEvent instanceof AbstractOrganizationStructureEvent.AbstractOrganizationStructureStateMergePatched) {
OrganizationStructureEvent.OrganizationStructureStateMergePatched e = (OrganizationStructureEvent.OrganizationStructureStateMergePatched) stateEvent;
return toOrganizationStructureStateMergePatchedDto(e);
} else if (stateEvent instanceof AbstractOrganizationStructureEvent.AbstractOrganizationStructureStateDeleted) {
OrganizationStructureEvent.OrganizationStructureStateDeleted e = (OrganizationStructureEvent.OrganizationStructureStateDeleted) stateEvent;
return toOrganizationStructureStateDeletedDto(e);
}
throw DomainError.named("invalidEventType", String.format("Invalid state event type: %1$s", stateEvent.getEventType()));
}
public OrganizationStructureStateEventDto.OrganizationStructureStateCreatedDto toOrganizationStructureStateCreatedDto(OrganizationStructureEvent.OrganizationStructureStateCreated e) {
OrganizationStructureStateEventDto.OrganizationStructureStateCreatedDto dto = new OrganizationStructureStateEventDto.OrganizationStructureStateCreatedDto();
dto.setOrganizationStructureEventId(e.getOrganizationStructureEventId());
dto.setCreatedAt(e.getCreatedAt());
dto.setCreatedBy(e.getCreatedBy());
dto.setCommandId(e.getCommandId());
dto.setActive(e.getActive());
return dto;
}
public OrganizationStructureStateEventDto.OrganizationStructureStateMergePatchedDto toOrganizationStructureStateMergePatchedDto(OrganizationStructureEvent.OrganizationStructureStateMergePatched e) {
OrganizationStructureStateEventDto.OrganizationStructureStateMergePatchedDto dto = new OrganizationStructureStateEventDto.OrganizationStructureStateMergePatchedDto();
dto.setOrganizationStructureEventId(e.getOrganizationStructureEventId());
dto.setCreatedAt(e.getCreatedAt());
dto.setCreatedBy(e.getCreatedBy());
dto.setCommandId(e.getCommandId());
dto.setActive(e.getActive());
dto.setIsPropertyActiveRemoved(e.getIsPropertyActiveRemoved());
return dto;
}
public OrganizationStructureStateEventDto.OrganizationStructureStateDeletedDto toOrganizationStructureStateDeletedDto(OrganizationStructureEvent.OrganizationStructureStateDeleted e) {
OrganizationStructureStateEventDto.OrganizationStructureStateDeletedDto dto = new OrganizationStructureStateEventDto.OrganizationStructureStateDeletedDto();
dto.setOrganizationStructureEventId(e.getOrganizationStructureEventId());
dto.setCreatedAt(e.getCreatedAt());
dto.setCreatedBy(e.getCreatedBy());
dto.setCommandId(e.getCommandId());
return dto;
}
}
| true |
586f24d80b7ad46e7e8ed6bd2c38065a3e3726e0 | Java | ddvoron/web_store_hibernate | /services/src/test/java/com/voronovich/serviceImpl/CatalogServiceImplTest.java | UTF-8 | 1,817 | 2.40625 | 2 | [] | no_license | package com.voronovich.serviceImpl;
import com.voronovich.entity.CatalogEntity;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import java.util.List;
import java.util.ResourceBundle;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class CatalogServiceImplTest {
private ResourceBundle myResources = ResourceBundle.getBundle("dataTest");
private final int idCatalog = Integer.parseInt(myResources.getString("idCatalog"));
private final String department = myResources.getString("department");
private CatalogServiceImpl dao = CatalogServiceImpl.getInstance();
@Test
public void aSaveCatalog() {
CatalogEntity roleEntity = new CatalogEntity(idCatalog,department);
List<CatalogEntity> list_before = dao.getAllDepartments();
int size_before = list_before.size();
dao.saveOrUpdate(roleEntity);
List<CatalogEntity> list_after = dao.getAllDepartments();
int size_after = list_after.size();
Assert.assertEquals("Not created", size_before + 1, size_after);
}
@Test
public void bGetCatalogById() {
CatalogEntity catalogEntity = dao.get(idCatalog);
Assert.assertEquals("Not got", department, catalogEntity.getDepartment());
}
@Test
public void cDeleteCatalog() {
List<CatalogEntity> list_before = dao.getAllDepartments();
int size_before = list_before.size();
CatalogEntity catalogEntity = dao.get(idCatalog);
dao.delete(catalogEntity);
List<CatalogEntity> list_after = dao.getAllDepartments();
int size_after = list_after.size();
Assert.assertEquals("Not deleted", size_before - 1, size_after);
}
}
| true |
355a5449c2de6b7ece1bcab06cfaf5b0c2cf9342 | Java | hanlin16/personTest | /src/main/java/com/callBack/CallBckTest.java | UTF-8 | 939 | 2.96875 | 3 | [] | no_license | package com.callBack;
/**
* @author liuxd
* @version 1.0
* @date 2020-04-02 8:48
*/
public class CallBckTest {
public static void main(String[] args) {
MainBusiness mainBusiness = new MainBusiness();
System.out.println("主线程:"+Thread.currentThread().getId());
System.out.println("*********具体实现类实现的回调方法_固定*********");
mainBusiness.execute(new CallbackServiceImpl());
System.out.println("*********匿名内部类实现的回调方法_灵活*********");
mainBusiness.execute(new CallbackService() {
public void callBackFunc() {
System.out.println("匿名内部类回到函数线程:"+Thread.currentThread().getId());
System.out.println("匿名内部类回调函数开始执行...");
System.out.println("匿名内部类回调函数结束执行...\n");
}
});
}
}
| true |
606d881d2496f4a3efb2ff7bfbcfee06875c6921 | Java | midooHjr/CQELS-MQTT-Intrusion-detection-system | /src/main/java/cqelsplus/launch/StreamElementHandler.java | UTF-8 | 2,413 | 2.453125 | 2 | [] | no_license | package cqelsplus.launch;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.n3.turtle.TurtleEventHandler;
import cqelsplus.engine.RDFStream;
public class StreamElementHandler implements TurtleEventHandler {
RDFStream stream;
long streamSize;
static String expOutput;
static long noOfQueries;
static long windowSize;
/**Starting count point*/
long startCount;
static long timeStart;
static long timeEnd;
static long tripleNum = 0;
static long consumedMem;
static boolean doneStream = false;
int mb = 1024 * 1024;
static long startTime = 0;
static long finishTime = 0;
public StreamElementHandler(long streamSize, long startCount, RDFStream stream){
this.startCount = startCount;
this.streamSize = streamSize;
this.stream=stream;
}
public static void setGlobalParams(String to, long nq, long ws) {
expOutput = to;
noOfQueries = nq;
windowSize = ws;
}
public void triple(int line, int col, Triple triple) {
if (!doneStream && tripleNum >= streamSize ) {
try {
File file =new File(expOutput);
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file, false)));
finishTime = System.nanoTime();
NumberFormat formatter = new DecimalFormat("#0.00");
pw.println(noOfQueries + " " + windowSize + " " + formatter.format((streamSize - startCount) * 1E9 / ((finishTime - startTime) * 1.0)));
pw.close();
System.out.println("Done stream");
doneStream = true;
stream.stop();
} catch (Exception e) {
e.printStackTrace();
}
}
tripleNum++;
if (tripleNum == startCount) {
startTime = System.nanoTime();
}
// if (tripleNum % 10000 == 0) {
// System.out.println("streamed: " + tripleNum + "triples");
// System.out.flush();
// }
stream.stream(triple);
}
public void prefix(int line, int col, String prefix, String iri) {
// TODO Auto-generated method stub
}
public void startFormula(int line, int col) {
// TODO Auto-generated method stub
}
public void endFormula(int line, int col) {
// TODO Auto-generated method stub
}
}
| true |