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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
0b20faac251e7ce8a64674b7a81bab4a5288b131
|
Java
|
xutongle/jwhwxt
|
/src/main/java/com/muran/aop/annotation/BussAnnotation.java
|
UTF-8
| 702
| 2.25
| 2
|
[] |
no_license
|
package com.muran.aop.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface BussAnnotation {
/**
*
* @return 业务逻辑名称
*/
String bussName() default "未命名业务";
/**
*
* @return 是否需要登陆
*/
boolean login() default true;
/**
*
* @return 业务逻辑需要的权限
*/
String role() default "";
/**
* 权限组
* @return
*/
String group() default "";
/**
* 是否公开的,默认非公开
*/
boolean opened() default false;
}
| true
|
5f645553a71297859c161cd11b4bafb3cf29ea43
|
Java
|
nandan-pai/Abdul-Bari-Java-Course-Udemy-Challenges
|
/Practice Problems/GCD/GCD.java
|
UTF-8
| 248
| 3.09375
| 3
|
[] |
no_license
|
class GCD {
public static int getgreatestCommonDivisor(int a, int b) {
if(a < 10 || b < 10) return -1;
int gcd = 1;
for(int i = 2; i <= a && i <= b; i++) {
if(a % i == 0 && b % i == 0) {
gcd = i;
}
}
return gcd;
}
}
| true
|
b8675e3a189f8234bdef741ec5c4825f45be978a
|
Java
|
Diego-Varela-Silva/TATS-Respostas
|
/Atividade03/src/tdd01/Calculadora.java
|
UTF-8
| 1,080
| 3.0625
| 3
|
[] |
no_license
|
package tdd01;
import java.util.ArrayList;
import java.util.List;
public class Calculadora {
public List<Proposta> calcular(float salario, float valorEmprestimo) {
ArrayList<Proposta> propostas = new ArrayList<>();
if (salario <= 1000F) {
propostas.add(new Proposta(2 * valorEmprestimo, 2));
propostas.add(new Proposta(2 * valorEmprestimo, 3));
return propostas;
} else if (salario <= 5000F) {
propostas.add(new Proposta(1.3F * valorEmprestimo, 2));
propostas.add(new Proposta(1.5F * valorEmprestimo, 4));
propostas.add(new Proposta(1.5F * valorEmprestimo, 10));
return propostas;
} else {
propostas.add(new Proposta(1.1F * valorEmprestimo, 2));
propostas.add(new Proposta(1.3F * valorEmprestimo, 4));
propostas.add(new Proposta(1.3F * valorEmprestimo, 10));
propostas.add(new Proposta(1.4F * valorEmprestimo, 20));
return propostas;
}
}
}
| true
|
b442846b1e04f791174faf828ee9bb329d348247
|
Java
|
yizhuan/tradingapp
|
/src/main/java/mobi/qubits/tradingapp/query/QuoteEntityRepository.java
|
UTF-8
| 252
| 1.84375
| 2
|
[] |
no_license
|
package mobi.qubits.tradingapp.query;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface QuoteEntityRepository extends MongoRepository<QuoteEntity, String> {
public QuoteEntity findBySymbol(String symbol);
}
| true
|
e87b94d9cbcfa0e88bf6ab288931630dcee87a7b
|
Java
|
PRL-PRG/scala-implicits-analysis
|
/scripts/tools/sccpreprocessor/src/Helpers.java
|
UTF-8
| 844
| 2.765625
| 3
|
[
"MIT"
] |
permissive
|
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
/**
* Created by peta on 19.12.16.
*/
public class Helpers {
public static void writeRow(ArrayList<String> row, Writer writer) throws IOException {
writer.write(row.get(0));
for (int i = 1; i < row.size(); ++i) {
writer.write(",");
writer.write(row.get(i));
}
writer.write("\n");
}
public static void writeFilesRow(ArrayList<String> row, Writer writer) throws IOException {
writer.write(row.get(0)); // file id
writer.write(",");
writer.write(row.get(1)); // project id
writer.write(",");
writer.write(CSVReader.escape(row.get(2))); // relPath
writer.write(",");
writer.write(row.get(3)); // fileHash
writer.write("\n");
}
}
| true
|
f5f1996779116e3d784f0e546a0c05d1f5c23db6
|
Java
|
ClaudioFsan01/Projeto-Classes-e-Metodos-Abstratos
|
/GerenciarBonificacao.java
|
ISO-8859-1
| 434
| 2.609375
| 3
|
[] |
no_license
|
public class GerenciarBonificacao {
protected int totalBonificacoes =0;
public void setBonificacao(Funcionario funcionario) // a variavel funcionario pode fazer referencia a objetos de outros tipos e no somente da classe Funcionario
{
totalBonificacoes += funcionario.getBonificacao();
}
public double getTotalBonificacao()
{
return this.totalBonificacoes;
}
}
| true
|
834f634708aa99e04f70e2a84afedce342fe59a0
|
Java
|
xiaomingmuzi/SingleSina
|
/app/src/main/java/com/lixm/singlesina/bean/PicUrlsBean.java
|
UTF-8
| 500
| 1.90625
| 2
|
[] |
no_license
|
package com.lixm.singlesina.bean;
import java.io.Serializable;
/**
* @author Lixm
* @date 2018/1/30
* @detail
*/
public class PicUrlsBean implements Serializable {
/**
* thumbnail_pic : http://wx1.sinaimg.cn/thumbnail/006HMUtTly1fnslk6k47hj30by0by0tk.jpg
*/
private String thumbnail_pic;
public String getThumbnail_pic() {
return thumbnail_pic;
}
public void setThumbnail_pic(String thumbnail_pic) {
this.thumbnail_pic = thumbnail_pic;
}
}
| true
|
3d4de959d34193eee8bcfedabeb44d7ebad7fbcd
|
Java
|
hahagioi998/OnlineEdu-9
|
/edu-microservice-center/src/main/java/com/onlineEdu/sysuser/service/CourseService.java
|
UTF-8
| 883
| 1.789063
| 2
|
[] |
no_license
|
package com.onlineEdu.sysuser.service;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.onlineEdu.sysuser.dto.CourseInfoDto;
import com.onlineEdu.sysuser.dto.CoursePublishDto;
import com.onlineEdu.sysuser.dto.CourseSearchDto;
import com.onlineEdu.sysuser.entity.Course;
/**
* <p>
* 课程 服务类
* </p>
*
* @author Elaine
* @since 2019-11-29
*/
public interface CourseService extends IService<Course> {
String saveCourse(CourseInfoDto courseInfoDto);
CourseInfoDto getCourseInfoById(String id);
CoursePublishDto getCoursePublishInfoById(String id);
void pageQuery(Page<Course> pageParam, CourseSearchDto courseSearchDto);
void updateCourseInfoById(CourseInfoDto courseInfoDto);
void removeCourseById(String id);
void publishCourseById(String id);
}
| true
|
60c0743dfab3ea8d1d20a2962dc2bd03d9daa815
|
Java
|
GoSteven/9321-Assignment
|
/src/com/entities/RecommendMovie.java
|
UTF-8
| 468
| 2.140625
| 2
|
[] |
no_license
|
package com.entities;
/**
* RecommendMovie entity. @author MyEclipse Persistence Tools
*/
public class RecommendMovie extends AbstractRecommendMovie implements
java.io.Serializable {
// Constructors
/** default constructor */
public RecommendMovie() {
}
/** full constructor */
public RecommendMovie(String recommendId, String toUser, String fromUser,
String movieId, Short isReaded) {
super(recommendId, toUser, fromUser, movieId, isReaded);
}
}
| true
|
a950062a1c9dc56947afcfec06ed873d8204e0bd
|
Java
|
fabriciooc/MySales
|
/MySales/src/main/java/br/com/revisaotextual/logica/EditarServicosLogica.java
|
UTF-8
| 696
| 2.296875
| 2
|
[] |
no_license
|
package br.com.revisaotextual.logica;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EditarServicosLogica implements Logica {
@Override
public String executa(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
int id = Integer.parseInt(request.getParameter("id"));
ServicoDAO dao = new ServicoDAO();
Servico serv = dao.consultar(id);
request.setAttribute("serv", serv);
//envia a p�gina com o id do servi�o selecionado
return "edita-servico.jsp?id=" + serv.getId();
}
}
| true
|
898cc2859d9451a90fbc19bd9f882c847759ab90
|
Java
|
joelcn/MyApplication
|
/app/src/main/java/com/example/rafaelsinosaki/myapplication/MainActivity.java
|
UTF-8
| 1,744
| 2.015625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.example.rafaelsinosaki.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public Button btnServicos;
public Button btnPerfil;
public Button btnHistorico;
public void init3() {
btnHistorico=(Button)findViewById(R.id.btnHistorico);
btnHistorico.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent teste3 = new Intent(MainActivity.this,Historico.class);
startActivity(teste3);
}
});
}
public void init2() {
btnPerfil=(Button)findViewById(R.id.btnPerfil);
btnPerfil.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent teste2 = new Intent(MainActivity.this,Perfil.class);
startActivity(teste2);
}
});
}
public void init() {
btnServicos=(Button)findViewById(R.id.btnServicos);
btnServicos.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent teste = new Intent(MainActivity.this,Servicos.class);
startActivity(teste);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
init2();
init3();
}
}
| true
|
7fea7c9739421f30dc4f3f5835c06363ec88ab13
|
Java
|
hianzuo/android-dbaccess
|
/LibDBAccess/src/main/java/com/hianzuo/dbaccess/sql/SQLiteUpdateSQLHandler.java
|
UTF-8
| 1,032
| 2.46875
| 2
|
[] |
no_license
|
package com.hianzuo.dbaccess.sql;
import android.content.ContentValues;
import android.text.TextUtils;
import com.hianzuo.dbaccess.util.ContentValues2xUtil;
/**
* User: Ryan
* Date: 14-4-3
* Time: 上午10:41
*/
public class SQLiteUpdateSQLHandler {
public static String create(String table, ContentValues values,
String whereClause) {
if (values == null || values.size() == 0) {
throw new IllegalArgumentException("Empty values");
}
StringBuilder sql = new StringBuilder(120);
sql.append("UPDATE ");
sql.append(table);
sql.append(" SET ");
int i = 0;
for (String colName : ContentValues2xUtil.keySet(values)) {
sql.append((i > 0) ? "," : "");
sql.append(colName);
i++;
sql.append("=?");
}
if (!TextUtils.isEmpty(whereClause)) {
sql.append(" WHERE ");
sql.append(whereClause);
}
return sql.toString();
}
}
| true
|
7d6b88a981d47bf76a46784a5fcc4e2767867c06
|
Java
|
RenjithKI/deSignPatternJava
|
/src/FactoryPattern/FactoryPatternAnimalDemo.java
|
UTF-8
| 374
| 3.125
| 3
|
[] |
no_license
|
package FactoryPattern;
public class FactoryPatternAnimalDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
AnimalFactory af = new AnimalFactory();
Animal a1 = af.createAnimal("DOG");
Animal a2 = af.createAnimal("CAT");
Animal a3 = af.createAnimal("DUCK");
a3.eat();
a2.eat();
a1.eat();
}
}
| true
|
58aaa1f61123c53567fb133f23d189063f92592e
|
Java
|
shuixi2013/AmapCode
|
/app/src/main/java/com/alipay/mobile/inside/h5/insideh5adapter/IInsideH5Service.java
|
UTF-8
| 179
| 1.507813
| 2
|
[] |
no_license
|
package com.alipay.mobile.inside.h5.insideh5adapter;
import com.alipay.mobile.h5container.service.H5Service;
public interface IInsideH5Service {
H5Service getH5Service();
}
| true
|
2b8cbbc0efd36792e0a841a1e231ce343c3a085b
|
Java
|
p0po/user
|
/others/crawer/src/main/java/net/yongpo/crawer/Sql.java
|
UTF-8
| 3,372
| 2.734375
| 3
|
[] |
no_license
|
package net.yongpo.crawer;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by p0po on 15-3-2.
*/
public class Sql {
private static String connectStr = "jdbc:mysql://localhost:3306/fangger";
private static String username = "root";
private static String password = "root";
public static void batchInsert(List<Map<String, Object>> data) throws ClassNotFoundException, SQLException {
String insert_sql = makeInsertSql(data, "xiaoqu");
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(connectStr, username, password);
conn.setAutoCommit(false); // 设置手动提交
int count = 0;
PreparedStatement psts = conn.prepareStatement(insert_sql);
for (Map<String, Object> row : data) {
int index = 1;
for (String key : row.keySet()) {
if (row.get(key) instanceof String) {
psts.setString(index, (String) row.get(key));
}
if (row.get(key) instanceof Boolean) {
psts.setBoolean(index, (Boolean) row.get(key));
}
if (row.get(key) instanceof Byte) {
psts.setByte(index, (Byte) row.get(key));
}
if (row.get(key) instanceof Integer) {
psts.setInt(index, (Integer) row.get(key));
}
if (row.get(key) instanceof Long) {
psts.setLong(index, (Integer) row.get(key));
}
if (row.get(key) instanceof Float) {
psts.setFloat(index, (Float) row.get(key));
}
if (row.get(key) instanceof Double) {
psts.setDouble(index, (Double) row.get(key));
}
if (row.get(key) instanceof Date) {
psts.setDate(index, (Date) row.get(key));
}
index++;
}
psts.addBatch();
}
psts.executeBatch();
conn.commit();
}
private static String makeInsertSql(List<Map<String, Object>> data, String table) {
String insert_sql = "INSERT INTO " + table + " (";
Map<String, Object> row = data.get(0);
for (String key : row.keySet()) {
insert_sql += key + ",";
}
insert_sql = insert_sql.substring(0, insert_sql.length() - 1) + ") VALUES (";
for (String key : row.keySet()) {
insert_sql += "?,";
}
insert_sql = insert_sql.substring(0, insert_sql.length() - 1) + ")";
return insert_sql;
}
public static void main(String[] args) {
Map<String, Object> map = new HashMap<>();
//map.put("id",1);
map.put("name", "test----");
map.put("district_id", "id12324");
map.put("source", 1);
List<Map<String, Object>> list = new ArrayList<>();
list.add(map);
/*String sql = makeInsertSql(list, "xiaoqu");
System.out.println(sql);*/
try {
batchInsert(list);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| true
|
ba092bf3047f98667fc434cb7e86c8f003d330df
|
Java
|
DrRico/LeetCode
|
/src/com/rico/YueWen/fun.java
|
UTF-8
| 584
| 3.046875
| 3
|
[] |
no_license
|
package com.rico.YueWen;
/**
* @author Rico_dds
* @date 2020/11/24 14:53
*/
public class fun {
public static void main(String[] args) {
System.out.println(function(4));
}
private static int function(int n){
int[] dp = new int[n + 1];
dp[0] = 1;
dp[1] = 1;
for (int i = 2; i < n + 1; i ++){
dp[i] = dp[i-1] + dp[i-2];
}
return dp[n];
}
private static int func(int n){
if(n <= 2){
return n;
} else {
return func(n - 1) + func(n - 2);
}
}
}
| true
|
1e20778fc9d52a7c1ffc93c84aaa13f29b17ef5d
|
Java
|
crysehillmes/smoothnovelreader
|
/app/src/main/java/org/cryse/novelreader/view/ContentViewEx.java
|
UTF-8
| 216
| 1.648438
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.cryse.novelreader.view;
/**
* Created by cryse on 11/20/14.
*/
public interface ContentViewEx extends ContentView {
public boolean isLoadingMore();
public void setLoadingMore(boolean value);
}
| true
|
8efc0505b2d2c45355a6a9dd46386164a8d4e938
|
Java
|
SergioDiaz99/UTNPhonesDiazFtMurrie
|
/src/main/java/com/utnphones/UTNPhonesDiazFtMurrie/dao/LineTypeDao.java
|
UTF-8
| 315
| 1.679688
| 2
|
[] |
no_license
|
package com.utnphones.UTNPhonesDiazFtMurrie.dao;
import com.utnphones.UTNPhonesDiazFtMurrie.model.domain.LineType;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface LineTypeDao extends JpaRepository<LineType, Integer> { }
| true
|
349af610dd0796697f958f9867f9348ae3a56bf5
|
Java
|
Domiciano/FirestoreEjemplo
|
/app/src/main/java/edu/co/icesi/firestoreejemplo/MainActivity.java
|
UTF-8
| 2,744
| 2.4375
| 2
|
[] |
no_license
|
package edu.co.icesi.firestoreejemplo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.material.textfield.TextInputEditText;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.Query;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private TextInputEditText usernameET;
private TextInputEditText passET;
private Button loginBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameET = findViewById(R.id.usernameET);
passET = findViewById(R.id.passET);
loginBtn = findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(this::login);
}
private void login(View view) {
String username = usernameET.getText().toString();
String pass = passET.getText().toString();
User user = new User(UUID.randomUUID().toString(), username, pass);
Query query = FirebaseFirestore.getInstance().collection("users").whereEqualTo("username", username);
query.get().addOnCompleteListener(
task->{
//Si el usuario no existe crearlo e iniciar sesion con él
if(task.getResult().size() == 0){
FirebaseFirestore.getInstance().collection("users").document(user.getId()).set(user);
Intent intent = new Intent(this, HomeActivity.class);
intent.putExtra("user", user);
startActivity(intent);
}
//Si ya existe, descargar el usuario e iniciar sesion con el
else{
User existingUser = null;
for(DocumentSnapshot doc : task.getResult()){
existingUser = doc.toObject(User.class);
break;
}
if(existingUser.getPassword().equals(pass)){
Intent intent = new Intent(this, HomeActivity.class);
intent.putExtra("user",existingUser);
startActivity(intent);
}else{
Toast.makeText(this, "Contraseña incorrecta", Toast.LENGTH_LONG).show();
}
}
}
);
//
}
}
| true
|
49cf69aec8cd52282f4b38cb84bc6190dc87dfe7
|
Java
|
SindhuKarnic/ELF-06June19-Techchefs-SindhuKarnic
|
/CoreJava/src/com/techchefs/javaapp/conditions/Language.java
|
UTF-8
| 326
| 2.671875
| 3
|
[] |
no_license
|
package com.techchefs.javaapp.conditions;
public class Language {
public static void main(String[] args) {
int langOption = 3;
String msg;
switch (langOption) {
case 1: msg = "Kannade";
break;
case 2: msg = "English";
break;
case 3: msg ="Telugu";
break;
default : msg = "Invalid";
}
System.out.println(msg);
}
}
| true
|
ad547fad41c7340938569932cab1d94ba3915e6b
|
Java
|
MikeLang520/lang
|
/src/myservlet/control/PostMan.java
|
UTF-8
| 802
| 2.234375
| 2
|
[] |
no_license
|
package myservlet.control;
import java.io.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/ch5/postman")
public class PostMan extends HttpServlet{
private static final long serialVersionUID = 4557103380658377142L;
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
request.setCharacterEncoding("gb2312");
String name=request.getParameter("name");
RequestDispatcher dispatcher=
request.getRequestDispatcher("/ch5/showName.jsp");
if(name!=null&&name.length()>=1)
dispatcher.forward(request, response);
}
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException{
doPost(request,response);
}
}
| true
|
ba6df9e3a776a700cc20ea02712b9edb541463c2
|
Java
|
gurhann/radyodinlenir
|
/src/main/java/com/itaki/radyodinlenir/service/UserService.java
|
UTF-8
| 277
| 1.875
| 2
|
[] |
no_license
|
package com.itaki.radyodinlenir.service;
import com.itaki.radyodinlenir.exception.UserNotFoundException;
import com.itaki.radyodinlenir.persistence.model.User;
public interface UserService {
public User getUserByUserName(String userName) throws UserNotFoundException;
}
| true
|
410b1a45c30941fc4b562d9950d1d75858ecd4fb
|
Java
|
devoxx/WatsonSherlockProject
|
/src/main/java/com/devoxx/watson/service/AlchemyLanguageService.java
|
UTF-8
| 9,696
| 2.046875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.devoxx.watson.service;
import com.devoxx.watson.exception.ArticleTextExtractionException;
import com.devoxx.watson.model.AlchemyContent;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
/**
* @author Stephan Janssen
* @author James Weaver
*/
@Component
public class AlchemyLanguageService {
private static final Logger LOGGER = Logger.getLogger(AlchemyLanguageService.class.getName());
private static final String PUBLICATION_DATE = "publicationDate";
private static final String LANGUAGE = "language";
private static final String AUTHORS = "authors";
private static final String DOC_SENTIMENT = "docSentiment";
private static final String TITLE = "title";
private static final String DOC_EMOTIONS = "docEmotions";
// Alchemy Language REST endpoints
private static final String URLGET_RANKED_IMAGE_KEYWORDS = "https://gateway-a.watsonplatform.net/calls/url/URLGetRankedImageKeywords";
private static final String URLGET_TEXT = "https://gateway-a.watsonplatform.net/calls/url/URLGetText";
private static final String URLGET_COMBINED_DATA = "https://gateway-a.watsonplatform.net/calls/url/URLGetCombinedData";
private static final String TEXT_GET_RANKED_KEYWORDS = "https://gateway-a.watsonplatform.net/calls/text/TextGetRankedKeywords";
// Alchemy Language REST parameters
private static final String APIKEY = "apikey";
private static final String URL = "url";
private static final String TEXT = "text";
private static final String OUTPUT_MODE = "outputMode";
private static final String JSON = "json";
private static final String KEYWORDS = "keywords";
private static final String IMAGE_KEYWORDS = "imageKeywords";
private static final String PUB_DATE = "date";
private static final String DOC_SENTIMENT_TYPE = "type";
private static final int TIMEOUT_IN_MILLIS = 15000;
private String apikey;
@Autowired
public void setApikey(final String apikey) {
this.apikey = apikey;
}
public void process(final AlchemyContent content) {
final JsonObject json;
try {
// TODO execute alchemy on transcript instead of only article link
json = getAlchemyData(content.getLink()).getAsJsonObject();
if (content.getTitle() == null ||
content.getTitle().isEmpty()) {
content.setTitle(json.get(TITLE).getAsString());
}
if (content.getAuthors() == null ||
content.getAuthors().isEmpty()) {
content.setAuthors(json.get(AUTHORS).getAsJsonObject().get("names").getAsString());
}
if (json.has(PUBLICATION_DATE)) {
final JsonObject pubDate = json.get(PUBLICATION_DATE).getAsJsonObject();
if (pubDate.has(PUB_DATE)) {
content.setPublicationDate(pubDate.get(PUB_DATE).getAsString());
}
}
if (json.has(LANGUAGE)) {
content.setLanguage(json.get(LANGUAGE).getAsString());
}
if (json.has(DOC_SENTIMENT)) {
final JsonObject docSentiment = json.get(DOC_SENTIMENT).getAsJsonObject();
if (docSentiment.has(DOC_SENTIMENT_TYPE)) {
content.setSentiment(docSentiment.get(DOC_SENTIMENT_TYPE).getAsString());
}
}
if (json.has(DOC_EMOTIONS)) {
content.setEmotions(json.get(DOC_EMOTIONS).getAsJsonObject());
}
final String thumbnail = content.getThumbnail();
if (thumbnail != null) {
content.setThumbnailKeywords(getThumbnailKeywords(thumbnail));
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* curl -X POST \
* -d "apikey={API-KEY}" \
* -d "outputMode=json" \
* -d "extract=entities,keywords,authors, concepts, dates, doc-emotion, entities, feeds, keywords, pub-date, relations, doc-sentiment, taxonomy, title" \
* -d "sentiment=1" \
* -d "maxRetrieve=1" \
* -d "url=https://www.voxxed.com/blog/2016/01/microservices-versus-soa-practice/" \
* "https://gateway-a.watsonplatform.net/calls/url/URLGetCombinedData"
*/
private JsonElement getAlchemyData(final String link) throws IOException {
final Document doc =
Jsoup.connect(URLGET_COMBINED_DATA)
.timeout(TIMEOUT_IN_MILLIS)
.method(Connection.Method.POST)
.data(APIKEY, apikey)
.data(OUTPUT_MODE, JSON)
.data("extract", "authors, doc-emotion, pub-date, doc-sentiment, title")
.data(URL, link)
.ignoreContentType(true)
.execute()
.parse();
return new JsonParser().parse(doc.text());
}
/**
* Given the text of an abstract, identify keywords useful for recognizing
*
* @param text text of an abstract
*
* @return sorted list of unique keywords
*
* curl -X POST \
* -d "apikey={API-KEY}" \
* -d "outputMode=json" \
* -d "text=this is some abstract text" \
* "https://gateway-a.watsonplatform.net/calls/text/TextGetRankedKeywords"
*/
List<String> getKeywordsFromText(final String text) throws IOException {
String abstractText = (text == null || text.length() == 0) ? "keyword" : text;
final List<String> keywords = new ArrayList<>();
final Document doc =
Jsoup.connect(TEXT_GET_RANKED_KEYWORDS)
.timeout(TIMEOUT_IN_MILLIS)
.method(Connection.Method.POST)
.data(APIKEY, apikey)
.data(OUTPUT_MODE, JSON)
.data(TEXT, abstractText)
.ignoreContentType(true)
.execute()
.parse();
final JsonElement element = new JsonParser().parse(doc.text());
JsonArray array = element.getAsJsonObject().get(KEYWORDS).getAsJsonArray();
for (final JsonElement keywordElement : array) {
String label = keywordElement.getAsJsonObject().get("text").getAsString();
String[] tokens = label.split(" ");
for (String token : tokens) {
if (!keywords.contains(token)) {
keywords.add(token);
}
}
}
Collections.sort(keywords);
return keywords;
}
/**
* curl -X POST \
* -d "apikey=$API_KEY" \
* -d "outputMode=json" \
* -d "url=http://techcrunch.com/2016/01/29/ibm-watson-weather-company-sale/" \
* "https://gateway-a.watsonplatform.net/calls/url/URLGetText"
*
* @param articleURL the article link
* @return the cleaned articled text
*/
public String getArticleText(final String articleURL) throws ArticleTextExtractionException {
final Document doc;
try {
doc = Jsoup.connect(URLGET_TEXT)
.timeout(TIMEOUT_IN_MILLIS)
.method(Connection.Method.POST)
.data(APIKEY, apikey)
.data(OUTPUT_MODE, JSON)
.data(URL, articleURL)
.ignoreContentType(true)
.execute()
.parse();
} catch (IOException e) {
throw new ArticleTextExtractionException(e.toString());
}
final JsonElement parse = new JsonParser().parse(doc.text());
if (parse.getAsJsonObject().has("text")) {
return parse.getAsJsonObject().get("text").getAsString();
} else {
return null;
}
}
/**
*
* curl "https://gateway-a.watsonplatform.net/calls/url/URLGetRankedImageKeywords?url=http://www.edisonmuckers.org/fun-facts-about-tom&
* outputMode=json&apikey=key"
*
* @param thumbnailURL the thumbnail URL
* @return list of keyw
* ords
*/
public String getThumbnailKeywords(final String thumbnailURL) throws IOException {
final Document doc = Jsoup.connect(URLGET_RANKED_IMAGE_KEYWORDS)
.timeout(TIMEOUT_IN_MILLIS)
.method(Connection.Method.GET)
.data(APIKEY, apikey)
.data(URL, thumbnailURL)
.data(OUTPUT_MODE, JSON)
.ignoreContentType(true)
.execute()
.parse();
LOGGER.info(doc.text());
final JsonObject json = new JsonParser().parse(doc.text()).getAsJsonObject();
if (json.has(IMAGE_KEYWORDS)) {
final JsonArray imageKeywords = json.get(IMAGE_KEYWORDS).getAsJsonArray();
if (imageKeywords.size() > 0) {
return imageKeywords.get(0).getAsJsonObject().get("text").getAsString();
}
}
return "no results";
}
}
| true
|
ab00e17c2668fff284a0e1884f5acc08f637c122
|
Java
|
OlegChapurin/lesson18
|
/task/work/NewTables.java
|
UTF-8
| 1,279
| 2.5625
| 3
|
[] |
no_license
|
package lesson.task.work;
import lesson.task.dao.TableDdl;
import lesson.task.dao.TablePostgres;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* delete create tables
* @author Oleg_Chapurin
*/
public class NewTables {
private static final Logger logger = LogManager.getLogger();
/**
* delete create tables
*/
public void creatTables(){
TableDdl table = new TablePostgres(
"jdbc:postgresql://localhost:5432/mybd",
"postgres",
"postgres");
logger.info("Method creatTables Delete table user " + table.deleteTable("USER"));
logger.info("Method creatTables Delete table role " + table.deleteTable("ROLE"));
logger.info("Method creatTables Delete table user_role " + table.deleteTable("USER_ROLE"));
logger.info("Method creatTables Creat table user " + table.creatTable("USER"));
logger.info("Method creatTables Creat table role " + table.creatTable("ROLE"));
logger.info("Method creatTables Creat table user_role " + table.creatTable("USER_ROLE"));
table.closeConnection();
}
public static void main(String[] args) {
NewTables nt = new NewTables();
nt.creatTables();
}
}
| true
|
09d0ee0f116c258c6e3abe97f6a4f22e7ad82552
|
Java
|
zoltanaty/Common-Project-ubbse2016
|
/techinterview_backend/src/main/java/com/halcyonmobile/model/Privileges.java
|
UTF-8
| 649
| 2.171875
| 2
|
[] |
no_license
|
package com.halcyonmobile.model;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@Entity
@Table(name = "privileges")
public class Privileges {
@Id
@Column(name = "idprivileges")
private String idprivileges;
@Column(name = "nameprivileges")
private String nameprivileges;
public String getIdprivileges() {
return idprivileges;
}
public void setIdprivileges(String idprivileges) {
this.idprivileges = idprivileges;
}
public String getNameprivileges() {
return nameprivileges;
}
public void setNameprivileges(String nameprivileges) {
this.nameprivileges = nameprivileges;
}
}
| true
|
276b4473280809c7a4ee193ed9453cbefb33576c
|
Java
|
Softtanck/MultiTypeRecycleView
|
/Cheweishi/app/src/main/java/com/cheweishi/android/utils/mapUtils/MapSearchUtil.java
|
UTF-8
| 7,363
| 2.109375
| 2
|
[] |
no_license
|
package com.cheweishi.android.utils.mapUtils;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.share.LocationShareURLOption;
import com.baidu.mapapi.search.share.OnGetShareUrlResultListener;
import com.baidu.mapapi.search.share.PoiDetailShareURLOption;
import com.baidu.mapapi.search.share.ShareUrlSearch;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.cheweishi.android.utils.StringUtil;
public class MapSearchUtil {
/**
* 路线规划-开车
*/
public static final int ROUTEPLAN_DRIVE = 1001;
/**
* 路线规划-步行
*/
public static final int ROUTEPLAN_WALK = 1002;
/**
* 路线规划-公交
*/
public static final int ROUTEPLAN_TRANSIT = 1003;
/**
* 分享链接-位置
*/
public static final int SHAREURL_LOCATION = 1004;
/**
* 分享链接-兴趣点详情
*/
public static final int SHAREURL_POIDETAIL = 1005;
/* 路线规划 */
private RoutePlanSearch routePlanSearch;
/* 地理位置编译 */
private GeoCoder geoCoder;
/* 兴趣点搜索 */
private PoiSearch poiSearch;
/* 建议搜索 */
private SuggestionSearch suggestionSearch;
/* 链接分享搜索 */
private ShareUrlSearch shareUrlSearch;
/**
* 路线规划
*
* @param planStyle 规划方式
* @param sLatLon
* @param eLatLon
* @param onGetRoutePlanResultListener
*/
public void startRoutePlan(int planStyle, LatLng sLatLon, LatLng eLatLon,
OnGetRoutePlanResultListener onGetRoutePlanResultListener) {
if (routePlanSearch == null) {
routePlanSearch = RoutePlanSearch.newInstance();
}
routePlanSearch
.setOnGetRoutePlanResultListener(onGetRoutePlanResultListener);
PlanNode sNode = PlanNode.withLocation(sLatLon);
PlanNode eNode = PlanNode.withLocation(eLatLon);
switch (planStyle) {
case ROUTEPLAN_TRANSIT:
routePlanSearch.transitSearch(new TransitRoutePlanOption().from(
sNode).to(eNode));
break;
case ROUTEPLAN_DRIVE:
routePlanSearch.drivingSearch(new DrivingRoutePlanOption().from(
sNode).to(eNode));
break;
case ROUTEPLAN_WALK:
routePlanSearch.walkingSearch(new WalkingRoutePlanOption().from(
sNode).to(eNode));
break;
default:
}
}
/**
* 开始geocode编码
*
* @param city
* @param address
* @param onGetGeoCoderResultListener
*/
public void startGeoCode(String city, String address,
OnGetGeoCoderResultListener onGetGeoCoderResultListener) {
initGeoCoder(onGetGeoCoderResultListener);
geoCoder.geocode(new GeoCodeOption().city(city).address(address));
}
/**
* 开始geocoder反编译
*
* @param latLng
* @param onGetGeoCoderResultListener
*/
public void startReverseGeoCode(LatLng latLng, OnGetGeoCoderResultListener onGetGeoCoderResultListener) {
initGeoCoder(onGetGeoCoderResultListener);
geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(latLng));
}
/**
* 初始化geocoder并设置监听
*
* @param onGetGeoCoderResultListener
*/
private void initGeoCoder(OnGetGeoCoderResultListener onGetGeoCoderResultListener) {
if (geoCoder == null) {
geoCoder = GeoCoder.newInstance();
geoCoder.setOnGetGeoCodeResultListener(onGetGeoCoderResultListener);
}
}
/**
* 简单poi搜索
*
* @param city
* @param onGetPoiSearchResultListener
*/
public void startPoiSearch(String city,
OnGetPoiSearchResultListener onGetPoiSearchResultListener) {
if (poiSearch == null) {
poiSearch = PoiSearch.newInstance();
poiSearch
.setOnGetPoiSearchResultListener(onGetPoiSearchResultListener);
}
poiSearch
.searchInCity(new PoiCitySearchOption().city(city).keyword(""));
}
/**
* 建议点搜索
*
* @param city
* @param keyWord
* @param onGetSuggestionResultListener
*/
public void startSuggetSearch(String city, String keyWord,
OnGetSuggestionResultListener onGetSuggestionResultListener) {
if (suggestionSearch == null) {
suggestionSearch = SuggestionSearch.newInstance();
suggestionSearch
.setOnGetSuggestionResultListener(onGetSuggestionResultListener);
}
if (!StringUtil.isEmpty(keyWord) && !StringUtil.isEmpty(city)) {
suggestionSearch.requestSuggestion(new SuggestionSearchOption()
.keyword(keyWord).city(city));
}
}
/**
* @param type
* @param latLng
* @param poiUid
* @param onGetShareUrlResultListener
*/
public void startShareUrlSearch(int type, LatLng latLng, String poiUid,
OnGetShareUrlResultListener onGetShareUrlResultListener) {
if (shareUrlSearch == null) {
shareUrlSearch = ShareUrlSearch.newInstance();
shareUrlSearch
.setOnGetShareUrlResultListener(onGetShareUrlResultListener);
}
if (type == SHAREURL_LOCATION) {
shareUrlSearch.requestLocationShareUrl(new LocationShareURLOption()
.location(latLng));
return;
}
shareUrlSearch.requestPoiDetailShareUrl(new PoiDetailShareURLOption()
.poiUid(poiUid));
}
/**
* 释放变量
*/
public void onDestory() {
if (routePlanSearch != null) {
routePlanSearch.destroy();
routePlanSearch = null;
}
if (geoCoder != null) {
geoCoder.destroy();
geoCoder = null;
}
if (poiSearch != null) {
poiSearch.destroy();
poiSearch = null;
}
if (suggestionSearch != null) {
suggestionSearch.destroy();
suggestionSearch = null;
}
if (shareUrlSearch != null) {
shareUrlSearch.destroy();
shareUrlSearch = null;
}
}
}
| true
|
9272f9077d36ebf149adb34ab34e1a52690cb78e
|
Java
|
fbazzouz/Estival-Club
|
/src/Utils/Constants.java
|
UTF-8
| 1,190
| 1.703125
| 2
|
[] |
no_license
|
package Utils;
public class Constants {
public static final String MAIN = "/views/accueil.fxml";
public static final String MAINVIEW = "/views/main.fxml";
public static final String SIDEMENUVIEW = "/views/sideMenu.fxml";
public static final String LISTERCLIENTHEBERG = "/views/listerClientHeberg.fxml";
public static final String ETATRESERVATION = "/views/etatReservation.fxml";
public static final String LISTERCLIENTREST = "/views/listerClientRestauration.fxml";
public static final String MainPane = "/views/mainPane.fxml";
public static final String ACCEUIL = "/views/accueil.fxml";
//View d'un user non logged in
public static final String RESERVERVIEW = "/views/UserViews/reserverView.fxml";
//View d'un user logged in
public static final String SIDEMENUUSER = "/views/UserViews/userSideMenu.fxml";
public static final String CONSULTERRESERVATIONVIEW = "/views/UserViews/consulterReservationView.fxml";
public static final String ANNULERRESERVATIONVIEW = "/views/UserViews/profil.fxml";
public static final String MODIFERRESERVATIONVIEW = "/views/UserViews/modiferReservationView.fxml";
}
| true
|
093ecb26a1b45e75ad04ca214ae25f53a729ed50
|
Java
|
GameKuchen/vrchatapi-java
|
/src/main/java/io/github/vrchatapi/model/FileStatus.java
|
UTF-8
| 1,668
| 2.375
| 2
|
[
"MIT"
] |
permissive
|
/*
* VRChat API Documentation
*
* The version of the OpenAPI document: 1.4.2
* Contact: me@ruby.js.org
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package io.github.vrchatapi.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.annotations.SerializedName;
import java.io.IOException;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
/**
* Gets or Sets FileStatus
*/
@JsonAdapter(FileStatus.Adapter.class)
public enum FileStatus {
WAITING("waiting"),
COMPLETE("complete"),
NONE("none");
private String value;
FileStatus(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static FileStatus fromValue(String value) {
for (FileStatus b : FileStatus.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
public static class Adapter extends TypeAdapter<FileStatus> {
@Override
public void write(final JsonWriter jsonWriter, final FileStatus enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public FileStatus read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return FileStatus.fromValue(value);
}
}
}
| true
|
b521a1e852fa28a4d7b0109495975bd1bcf6a681
|
Java
|
swati2904/E-WHOLESALE-APPLICATION-JSP-SERVLET
|
/src/controller/LoginController.java
|
UTF-8
| 1,652
| 2.46875
| 2
|
[] |
no_license
|
package controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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 DAO.UserLoginDAO;
import model.User;
@WebServlet("/login")
public class LoginController extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserLoginDAO loginUser = new UserLoginDAO();
private boolean validUser = false;
public LoginController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/WEB-INF/views/login.jsp");
rd.forward(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("email");
String password = request.getParameter("password");
//----------- MODEL OBJECTS -----------------
User user = new User();
user.setUserName(userName);
user.setPassword(password);
// ------------------------------------------VERIFYING THE USER DETAILS--------------------------------------
try {
validUser = loginUser.login(userName, password);
} catch (Exception e) {
e.printStackTrace();
}
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/WEB-INF/views/home.jsp");
rd.forward(request,response);
}
}
| true
|
5cd88e216a3357fa7b8de4ae533c3ee2e449836d
|
Java
|
SAtanasovv/onlineShop
|
/src/main/java/com/satanasov/onlineShop/model/enums/ShipmentMethod.java
|
UTF-8
| 115
| 1.8125
| 2
|
[] |
no_license
|
package com.satanasov.onlineShop.model.enums;
public enum ShipmentMethod {
ECONOMY,
STANDARD,
FAST
}
| true
|
4c062d55a65063f95a48f51ff913a3b17dafd020
|
Java
|
jjurm/fbp
|
/src/main/java/net/talentum/fbp/hardware/drivers/VirtualDisplay.java
|
UTF-8
| 405
| 2.453125
| 2
|
[] |
no_license
|
package net.talentum.fbp.hardware.drivers;
/**
* This class is used besides and never without a {@link DisplayDriver}. It simulates a real display with the
* parameters specified in the {@link DisplayDriver}.
* @author padr31
*/
public class VirtualDisplay {
private DisplayDriver displayDriver;
public VirtualDisplay(DisplayDriver displayDriver) {
this.displayDriver = displayDriver;
}
}
| true
|
0ce777ef058c5d3509fe150f4f06a704c7999052
|
Java
|
BartvaiErika/i4-backend
|
/javaprogramming_before_specialisation/week8programming/Week8/reflectionWeek8/ThermostatTest.java
|
UTF-8
| 1,069
| 3.3125
| 3
|
[] |
no_license
|
//package Week8.reflectionWeek8;
//
//import org.junit.jupiter.api.Assertions;
//import org.junit.jupiter.api.Test;
//
//class ThermostatTest {
// private Thermostat thermostat = new Thermostat(temp -> temp < 0, temp -> temp + " degrees Celsius.");
// private Thermostat thermostat2 = new Thermostat(temp -> temp >= 80, temp -> (temp + 273.15) + " degrees Kelvin.");
//
// @Test
// void testCold() {
// String message = thermostat.sense(12.3);
// String expected = "12.3 degrees Celsius.";
// Assertions.assertEquals(expected,message);
//
// message = thermostat.sense(-3.0);
// expected = "Warning!";
// Assertions.assertEquals(expected,message);
// }
//
// @Test
// void testHot() {
// String message = thermostat.sense(79.0);
// String expected = "Temperature is 352.15 degrees Kelvin.";
// Assertions.assertEquals(expected,message);
//
// message = thermostat.sense(80.0);
// expected = "Warning!";
// Assertions.assertEquals(expected,message);
// }
//}
//
| true
|
4982f3cd8c78194996fbbcbf69353c34e32d9239
|
Java
|
wongshandev/tob_mall
|
/tob-goods/src/main/java/com/service/AttrService.java
|
UTF-8
| 500
| 1.835938
| 2
|
[] |
no_license
|
package com.service;
import com.entities.AttrDO;
import java.util.List;
import java.util.Map;
/**
*
*
* @author chglee
* @email 1992lcg@163.com
* @date 2018-12-25 14:40:29
*/
public interface AttrService {
AttrDO get(Integer attrId);
List<AttrDO> list(Map<String, Object> map);
int count(Map<String, Object> map);
int save(AttrDO attr);
int update(AttrDO attr);
int remove(Integer attrId);
int batchRemove(Integer[] attrIds);
List<Map<String,Object>> findGoodsCategory();
}
| true
|
b33ca5c20945e8056461ccea7fead7c65c2309a5
|
Java
|
koczkak98/JavaWSDLFahrenheitConverter
|
/JavaWSDLFahrenheitConverter/src/main/java/JavaWSDLFahrenheitConverter/forras/AFDTempConverterEndpointServiceSoapBinding.java
|
UTF-8
| 8,383
| 2.140625
| 2
|
[] |
no_license
|
package JavaWSDLFahrenheitConverter.forras;
//----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 5.10.3.0
//
// Created by Quasar Development
//
//----------------------------------------------------
import org.ksoap2.HeaderProperty;
import org.ksoap2.serialization.*;
import org.ksoap2.transport.*;
import org.kxml2.kdom.Element;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class AFDTempConverterEndpointServiceSoapBinding
{
interface AFDIWcfMethod
{
AFDExtendedSoapSerializationEnvelope CreateSoapEnvelope() throws Exception;
Object ProcessResult(AFDExtendedSoapSerializationEnvelope __envelope, Object result) throws Exception;
}
String url="http://www.learnwebservices.com/services/tempconverter";
int timeOut=60000;
public List< HeaderProperty> httpHeaders= new ArrayList< HeaderProperty>();
public boolean enableLogging;
public AFDTempConverterEndpointServiceSoapBinding(){}
public AFDTempConverterEndpointServiceSoapBinding(String url)
{
this.url = url;
}
public AFDTempConverterEndpointServiceSoapBinding(String url,int timeOut)
{
this.url = url;
this.timeOut=timeOut;
}
protected org.ksoap2.transport.Transport createTransport()
{
try
{
java.net.URI uri = new java.net.URI(url);
if(uri.getScheme().equalsIgnoreCase("https"))
{
int port=uri.getPort()>0?uri.getPort():443;
String path=uri.getPath();
if(uri.getQuery()!=null && uri.getQuery()!="")
{
path+="?"+uri.getQuery();
}
return new com.easywsdl.exksoap2.transport.AdvancedHttpsTransportSE(uri.getHost(), port, path, timeOut);
}
else
{
return new com.easywsdl.exksoap2.transport.AdvancedHttpTransportSE(url,timeOut);
}
}
catch (java.net.URISyntaxException e)
{
}
return null;
}
protected AFDExtendedSoapSerializationEnvelope createEnvelope()
{
AFDExtendedSoapSerializationEnvelope envelope= new AFDExtendedSoapSerializationEnvelope(AFDExtendedSoapSerializationEnvelope.VER11);
return envelope;
}
protected List sendRequest(String methodName,AFDExtendedSoapSerializationEnvelope envelope,org.ksoap2.transport.Transport transport ,com.easywsdl.exksoap2.ws_specifications.profile.WS_Profile profile )throws Exception
{
if(transport instanceof com.easywsdl.exksoap2.transport.AdvancedHttpTransportSE )
{
return ((com.easywsdl.exksoap2.transport.AdvancedHttpTransportSE)transport).call(methodName, envelope,httpHeaders,null,profile);
}
else
{
return ((com.easywsdl.exksoap2.transport.AdvancedHttpsTransportSE)transport).call(methodName, envelope,httpHeaders,null,profile);
}
}
Object getResult(Class destObj, Object source, String resultName, AFDExtendedSoapSerializationEnvelope __envelope) throws Exception
{
if(source==null)
{
return null;
}
if(source instanceof SoapPrimitive)
{
SoapPrimitive soap =(SoapPrimitive)source;
if(soap.getName().equals(resultName))
{
Object instance=__envelope.get(source,destObj,false);
return instance;
}
}
else
{
SoapObject soap = (SoapObject)source;
if (soap.hasProperty(resultName))
{
Object j=soap.getProperty(resultName);
if(j==null)
{
return null;
}
Object instance=__envelope.get(j,destObj,false);
return instance;
}
else if( soap.getName().equals(resultName))
{
Object instance=__envelope.get(source,destObj,false);
return instance;
}
}
return null;
}
public Double CelsiusToFahrenheit(final Double TemperatureInCelsius) throws Exception
{
com.easywsdl.exksoap2.ws_specifications.profile.WS_Profile __profile = new com.easywsdl.exksoap2.ws_specifications.profile.WS_Profile();
return (Double)execute(new AFDIWcfMethod()
{
@Override
public AFDExtendedSoapSerializationEnvelope CreateSoapEnvelope(){
AFDExtendedSoapSerializationEnvelope __envelope = createEnvelope();
SoapObject __soapReq = new SoapObject("http://learnwebservices.com/services/tempconverter", "CelsiusToFahrenheitRequest");
__envelope.setOutputSoapObject(__soapReq);
PropertyInfo __info=null;
__info = new PropertyInfo();
__info.namespace="http://learnwebservices.com/services/tempconverter";
__info.name="TemperatureInCelsius";
__info.type=Double.class;
__info.setValue(TemperatureInCelsius);
__soapReq.addProperty(__info);
return __envelope;
}
@Override
public Object ProcessResult(AFDExtendedSoapSerializationEnvelope __envelope, Object __result)throws Exception {
SoapObject __soap=(SoapObject)__result;
Object obj = __soap.getProperty("TemperatureInFahrenheit");
if (obj instanceof SoapPrimitive)
{
SoapPrimitive j =(SoapPrimitive) obj;
return Double.valueOf(j.toString());
}
else if (obj!= null && obj instanceof Double){
return (Double)obj;
}
return null;
}
},"",__profile);
}
/**
* This method is available in Premium account only. To test if generated classes work correctly with your webservice, please use different method. Check http://EasyWsdl.com/Payment/PremiumAccountDetails to see all benefits of Premium account.
*/
public String FahrenheitToCelsius(final String TemperatureInFahrenheit) throws Exception
{
/*This feature is available in Premium account. To test if generated classes work correctly with your webservice, please use different method. Check https://EasyWsdl.com/Payment/PremiumAccountDetails to see all benefits of Premium account.*/
throw new UnsupportedOperationException("This feature is available in Premium account. To test if generated classes work correctly with your webservice, please use different method. Check https://EasyWsdl.com/Payment/PremiumAccountDetails to see all benefits of Premium account.");
}
protected Object execute(AFDIWcfMethod wcfMethod,String methodName,com.easywsdl.exksoap2.ws_specifications.profile.WS_Profile profile) throws Exception
{
org.ksoap2.transport.Transport __httpTransport=createTransport();
__httpTransport.debug=enableLogging;
AFDExtendedSoapSerializationEnvelope __envelope=wcfMethod.CreateSoapEnvelope();
try
{
sendRequest(methodName, __envelope, __httpTransport,profile);
}
finally {
if (__httpTransport.debug) {
if (__httpTransport.requestDump != null) {
System.out.println("requestDump: "+__httpTransport.requestDump);
}
if (__httpTransport.responseDump != null) {
System.out.println("responseDump: "+__httpTransport.responseDump);
}
}
}
Object __retObj = __envelope.bodyIn;
if (__retObj instanceof org.ksoap2.SoapFault){
org.ksoap2.SoapFault __fault = (org.ksoap2.SoapFault)__retObj;
throw convertToException(__fault,__envelope);
}else{
return wcfMethod.ProcessResult(__envelope,__retObj);
}
}
protected Exception convertToException(org.ksoap2.SoapFault fault,AFDExtendedSoapSerializationEnvelope envelope)
{
org.ksoap2.SoapFault newException = fault;
return newException;
}
}
| true
|
e09aefd3311068902622ba3fe9dc0841b614efd9
|
Java
|
hutomadotAI/web-api
|
/service/core-service/src/main/java/com/hutoma/api/connectors/aiservices/AiServicesQueue.java
|
UTF-8
| 9,894
| 2.171875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.hutoma.api.connectors.aiservices;
import com.hutoma.api.common.JsonSerializer;
import com.hutoma.api.common.Tools;
import com.hutoma.api.connectors.*;
import com.hutoma.api.connectors.db.Database;
import com.hutoma.api.connectors.db.DatabaseException;
import com.hutoma.api.containers.ServiceIdentity;
import com.hutoma.api.containers.sub.AiIdentity;
import com.hutoma.api.containers.sub.TrainingStatus;
import com.hutoma.api.logging.ILogger;
import com.hutoma.api.logging.LogMap;
import com.hutoma.api.thread.ITrackedThreadSubPool;
import org.glassfish.jersey.client.JerseyClient;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
public class AiServicesQueue extends ServerConnector {
private static final String LOGFROM = "aiservicesqueue";
private static final String COMMAND_PARAM = "command";
private final Database database;
@Inject
public AiServicesQueue(final Database database,
final ILogger logger,
final IConnectConfig connectConfig,
final JerseyClient jerseyClient,
final JsonSerializer serializer,
final Tools tools,
final ITrackedThreadSubPool threadSubPool) {
super(logger, connectConfig, serializer, tools, jerseyClient, threadSubPool);
this.database = database;
}
/***
* QUeue a command to start training
* @param status
* @param serverType
* @param aiIdentity
* @throws DatabaseException
*/
void userActionStartTraining(final BackendStatus status,
final BackendServerType serverType,
final AiIdentity aiIdentity)
throws DatabaseException {
// get the current status
BackendEngineStatus engineStatus = status.getEngineStatus(serverType);
ServiceIdentity serviceIdentity =
new ServiceIdentity(serverType, aiIdentity.getLanguage(), aiIdentity.getServerVersion());
// set the status to training_queued without changing the progress
this.database.updateAIStatus(serviceIdentity,
aiIdentity.getAiid(), TrainingStatus.AI_TRAINING_QUEUED, "",
engineStatus.getTrainingProgress(), engineStatus.getTrainingError());
// queue this AI for training
this.database.queueUpdate(serviceIdentity, aiIdentity.getAiid(), true, 0, QueueAction.TRAIN);
}
/***
* Stop training now (not a queued action)
* @param backendStatus
* @param serverType
* @param controller
* @param aiIdentity
* @throws DatabaseException
* @throws ServerConnector.AiServicesException
*/
void userActionStopTraining(final BackendStatus backendStatus,
final BackendServerType serverType,
final ControllerConnector controller,
final AiIdentity aiIdentity)
throws DatabaseException, ServerConnector.AiServicesException {
// stop training, and save "stopped" state in the dabatase
stopTrainingIfActive(backendStatus, serverType, controller, aiIdentity, true);
}
/***
* Stop training if the AI is in a state where it reasonably could be training
* @param backendStatus
* @param serverType
* @param controller
* @param aiIdentity
* @param setDbStatus whether to save the stop state in the database.
* TRUE if this is a stop command, FALSE if it part of a different command e.g. a delete
* @throws DatabaseException
* @throws AiServicesException
*/
private void stopTrainingIfActive(final BackendStatus backendStatus,
final BackendServerType serverType,
final ControllerConnector controller,
final AiIdentity aiIdentity,
boolean setDbStatus) throws DatabaseException, AiServicesException {
// get an endpoint map, i.e. a map from serverIdentifier to the actual servertracker object
Map<String, ServerTrackerInfo> map = controller.getVerifiedEndpointMap(
aiIdentity.getLanguage(), ServiceIdentity.DEFAULT_VERSION, serializer);
// get the status of the AI for the backend server we are dealing with
BackendEngineStatus status = backendStatus.getEngineStatus(serverType);
// get a tracker if there is one (meaning the AI might have started training)
ServerTrackerInfo tracker = null;
if (status != null) {
String endpoint = status.getServerIdentifier();
if (endpoint != null && !endpoint.isEmpty()) {
tracker = map.get(endpoint);
}
// if we want to save this state to the DB
if (setDbStatus) {
TrainingStatus newStatus = status.getTrainingStatus();
if (newStatus != null) {
switch (newStatus) {
case AI_TRAINING:
case AI_TRAINING_QUEUED:
case AI_READY_TO_TRAIN:
newStatus = TrainingStatus.AI_TRAINING_STOPPED;
break;
default:
break;
}
// copy the old fields but set new status
this.database.updateAIStatus(
new ServiceIdentity(serverType, aiIdentity.getLanguage(), aiIdentity.getServerVersion()),
aiIdentity.getAiid(), newStatus,
status.getServerIdentifier(), status.getTrainingProgress(), status.getTrainingError());
}
}
// if we get here we know this is not null otherwise the AiServicesException is thrown, but
// we need this check to appease the static tools
if (tracker != null) {
this.stopTrainingDirect(serverType, aiIdentity,
tracker.getServerUrl(), tracker.getServerIdentifier());
}
}
}
/***
* Queue a task to delete an AI
* @param backendStatus
* @param serverType
* @param controller
* @param aiIdentity
* @throws DatabaseException
* @throws ServerConnector.AiServicesException
*/
void userActionDelete(final BackendStatus backendStatus,
final BackendServerType serverType,
final ControllerConnector controller,
final AiIdentity aiIdentity)
throws DatabaseException, ServerConnector.AiServicesException {
// if we are training then stop immediately
stopTrainingIfActive(backendStatus, serverType, controller, aiIdentity, true);
// queue the action to delete, only run this some time in the future after the ai is fully stopped
this.database.queueUpdate(
new ServiceIdentity(serverType, aiIdentity.getLanguage(), aiIdentity.getServerVersion()),
aiIdentity.getAiid(), true, 10, QueueAction.DELETE);
}
/***
* Set the correct ai status and queue state after an upload
* @param backendStatus
* @param serverType
* @param controller
* @param aiIdentity
* @throws DatabaseException
* @throws AiServicesException
*/
void userActionUpload(final BackendStatus backendStatus,
final BackendServerType serverType,
final ControllerConnector controller,
final AiIdentity aiIdentity)
throws DatabaseException, AiServicesException {
ServiceIdentity serviceIdentity = new ServiceIdentity(serverType, aiIdentity.getLanguage(),
aiIdentity.getServerVersion());
// send a stop training command if necessary
stopTrainingIfActive(backendStatus, serverType, controller, aiIdentity, false);
// set the status to undefined while we upload.
// when the back-end is ready it will call back to say ready_to_train
this.database.updateAIStatus(serviceIdentity, aiIdentity.getAiid(),
TrainingStatus.AI_UNDEFINED, "", 0.0, 9999.0);
// clear the queue state
this.database.queueUpdate(serviceIdentity, aiIdentity.getAiid(), false, 0, QueueAction.NONE);
}
/***
* Call from queued task to backend to stop training
*
* @param serverType
* @param aiIdentity
* @param serverEndpoint
* @param serverIdentifier
* @throws AiServicesException
*/
private void stopTrainingDirect(final BackendServerType serverType,
final AiIdentity aiIdentity,
final String serverEndpoint,
final String serverIdentifier)
throws AiServicesException {
LogMap logMap = LogMap.map("Op", "train-stop")
.put("Type", serverType.value())
.put("Server", serverIdentifier)
.put("AIID", aiIdentity.getAiid());
this.logger.logUserInfoEvent(LOGFROM,
String.format("Sending \"stop\" %s to %s", aiIdentity.getAiid().toString(), serverType.value()),
aiIdentity.getDevId().toString(), logMap);
HashMap<String, Callable<InvocationResult>> callables =
getTrainingCallableForEndpoint(aiIdentity, serverEndpoint,
new HashMap<String, String>() {{
put(COMMAND_PARAM, "stop");
}});
executeAndWait(callables);
}
}
| true
|
cd46b15bd386cbb4356c6eb6e97d7f30cd129690
|
Java
|
180254/Battleship44
|
/battleship-back-end/src/test/java/pl/nn44/battleship/util/other/StringsTests.java
|
UTF-8
| 1,287
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
package pl.nn44.battleship.util.other;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import pl.nn44.battleship.util.Strings;
public class StringsTests {
@Test
public void safeSubstringTest1_whole() {
String subStr = Strings.safeSubstring("ala", 0, 3);
Assertions.assertEquals("ala", subStr);
}
@Test
public void safeSubstringTest2_whole() {
String subStr = Strings.safeSubstring("ala", 0);
Assertions.assertEquals("ala", subStr);
}
@Test
public void safeSubstringTest1_some() {
String subStr = Strings.safeSubstring("ala123", 1, 4);
Assertions.assertEquals("la1", subStr);
}
@Test
public void safeSubstringTest2_some() {
String subStr = Strings.safeSubstring("ala123", 2);
Assertions.assertEquals("a123", subStr);
}
@Test
public void safeSubstringTest1_beginTooBig() {
String subStr = Strings.safeSubstring("ala", 3, 4);
Assertions.assertEquals("", subStr);
}
@Test
public void safeSubstringTest2_beginTooBig() {
String subStr = Strings.safeSubstring("ala", 3);
Assertions.assertEquals("", subStr);
}
@Test
public void safeSubstringTest1_endTooBig() {
String subStr = Strings.safeSubstring("ala", 0, 3);
Assertions.assertEquals("ala", subStr);
}
}
| true
|
6b4650a2b7b8963383905124ea521b24583cd089
|
Java
|
yangyusong1121/Android-car
|
/app/src/main/java/com/tgf/kcwc/me/dealerbalance/DealerBalanceActivity.java
|
UTF-8
| 5,259
| 1.835938
| 2
|
[] |
no_license
|
package com.tgf.kcwc.me.dealerbalance;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.tgf.kcwc.R;
import com.tgf.kcwc.base.BaseActivity;
import com.tgf.kcwc.common.Constants;
import com.tgf.kcwc.me.dealerbalance.setpaypwd.SettingPayPwdActivity;
import com.tgf.kcwc.mvp.model.AccountBalanceModel;
import com.tgf.kcwc.mvp.presenter.DealerWalletPresenter;
import com.tgf.kcwc.mvp.view.DealerWalletView;
import com.tgf.kcwc.util.CommonUtils;
import com.tgf.kcwc.util.IOUtils;
import com.tgf.kcwc.view.FunctionView;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* Author:Jenny
* Date:2017/10/31
* E-mail:fishloveqin@gmail.com
* <p>
* 机构钱包
*/
public class DealerBalanceActivity extends BaseActivity implements DealerWalletView<AccountBalanceModel> {
protected TextView balanceTv;
protected ImageView img;
protected RelativeLayout prePaidLayout;
protected ImageView img2;
protected RelativeLayout withdrawCashLayout;
protected ImageView img3;
protected RelativeLayout accountCheckingLayout;
private DealerWalletPresenter mWalletPresenter;
AccountBalanceModel mModel;
private int isPwd = -1;
private static final int EXIST_PWD = 1;
@Override
protected void setUpViews() {
initView();
}
@Override
protected void titleBarCallback(ImageButton back, FunctionView function, TextView text) {
text.setText("小金库");
text.setTextSize(16);
function.setTextResource("明细", R.color.white, 14);
function.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CommonUtils.startNewActivity(mContext, BalanceStatementActivity.class);
}
});
backEvent(back);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_organization_balance);
}
private void initView() {
balanceTv = (TextView) findViewById(R.id.balanceTv);
img = (ImageView) findViewById(R.id.img);
prePaidLayout = (RelativeLayout) findViewById(R.id.prePaidLayout);
prePaidLayout.setOnClickListener(this);
img2 = (ImageView) findViewById(R.id.img2);
withdrawCashLayout = (RelativeLayout) findViewById(R.id.withdrawCashLayout);
withdrawCashLayout.setOnClickListener(this);
img3 = (ImageView) findViewById(R.id.img3);
accountCheckingLayout = (RelativeLayout) findViewById(R.id.accountCheckingLayout);
accountCheckingLayout.setOnClickListener(this);
findViewById(R.id.myBankCardLayout).setOnClickListener(this);
mWalletPresenter = new DealerWalletPresenter();
mWalletPresenter.attachView(this);
}
@Override
protected void onResume() {
super.onResume();
mWalletPresenter.getAccountBalances(IOUtils.getToken(mContext));
}
@Override
public void onClick(View view) {
int id = view.getId();
if (isPwd == -1) {
CommonUtils.showToast(mContext, "正在加载数据...");
return;
}
switch (id) {
case R.id.prePaidLayout:
if (isPwd == EXIST_PWD) {
CommonUtils.startNewActivity(mContext, PrePaidActivity.class);
} else {
CommonUtils.startNewActivity(mContext, SettingPayPwdActivity.class);
}
break;
case R.id.withdrawCashLayout:
Map<String, Serializable> args = new HashMap<String, Serializable>();
if (isPwd == EXIST_PWD) {
args.put(Constants.IntentParams.DATA, "");
CommonUtils.startNewActivity(mContext, args, WithdrawCashActivity.class);
} else {
CommonUtils.startNewActivity(mContext, SettingPayPwdActivity.class);
}
break;
case R.id.accountCheckingLayout:
CommonUtils.startNewActivity(mContext, CheckingAccountActivity.class);
break;
case R.id.myBankCardLayout:
args = new HashMap<String, Serializable>();
args.put(Constants.IntentParams.DATA, isPwd);
CommonUtils.startNewActivity(mContext, args, DealerBankCardActivity.class);
break;
}
}
private void validatePwd(String pwd) {
}
@Override
public void showData(AccountBalanceModel model) {
mModel = model;
isPwd = model.isPwd;
showBalances(model);
}
private void showBalances(AccountBalanceModel model) {
balanceTv.setText(model.money + "");
}
@Override
public void setLoadingIndicator(boolean active) {
showLoadingIndicator(active);
}
@Override
public void showLoadingTasksError() {
dismissLoadingDialog();
}
@Override
public Context getContext() {
return mContext;
}
}
| true
|
6d1cea7db18da663dc42b0af826474a28cd8b071
|
Java
|
bharathd/AdhaServices
|
/src/main/java/com/app/adha/dao/UserDAO.java
|
UTF-8
| 399
| 2.140625
| 2
|
[] |
no_license
|
package com.app.adha.dao;
import java.util.List;
import com.app.adha.entity.User;
public interface UserDAO{
List<User> getUserByPhoneNumber(String phoneNumber);
List<User> getAllUsers();
List<User> getAllUsersByUserRole(int userRole);
User getUserById(int userId);
void addUser(User user);
void updateUser(User user);
void deleteUser(int userId);
int maxRecordId();
}
| true
|
05abc675ab159d608560c76cf9ef5774a7945357
|
Java
|
sunflowersoft/hudup
|
/3_implementation/src/net/hudup/core/client/Server.java
|
UTF-8
| 12,621
| 2.4375
| 2
|
[
"MIT"
] |
permissive
|
/**
*
*/
package net.hudup.core.client;
import java.rmi.Remote;
import java.rmi.RemoteException;
import net.hudup.core.data.DataConfig;
/**
* {@code Server} interface defines abstract model of recommendation server. {@code Server} is responsible for creating {@code service} represented by {@code Service} interface to serve user requests.
* {@code Server} starts, pauses, resumes, and stops by methods {@link #start()}, {@link #pause()}, {@link #resume()}, and {@link #stop()}, respectively.
* {@code Server} interface must be implemented by programmer. Both {@code server} and {@code service} constitute a proper recommendation server (Hudup server).
* As usual, server creates one or many service (s) for serving incoming requests.
* {@code Server} extends {@link Remote}, which means that service supports RMI (abbreviation of Java Remote Method Invocation) for remote interaction in client-server architecture. The tutorial of RMI is available at <a href="https://docs.oracle.com/javase/tutorial/rmi">https://docs.oracle.com/javase/tutorial/rmi</a>.
* <br><br>
* Server has six statuses as follows:
* <ul>
* <li>"started": Server started. If server has just started right after calling {@link #start()}, it is in two statuses: "started" and "running".</li>
* <li>"paused": Server paused. Server are currently in both "started" status and "paused" status.</li>
* <li>"resumed": Server resumed. Server are currently in three statuses: "started", "resumed", and "running".</li>
* <li>"stopped": Server stopped and so server is in "stopped" status.</li>
* <li>"setconfig": Server is in setting its configuration. Sever must stop so that it can set its configuration. So server is now in two statuses: "stopped" and "setconfig".</li>
* <li>"exit": Server exits and so server does not exist. Status "exit" is unreal.</li>
* </ul>
* Some statuses are overlapped; for example, server is in status "paused" is also in status "started".
* When server changes its current status by calling methods such as {@link #start()}, {@link #pause()}, {@link #resume()}, {@link #stop()}, and {@link #exit()}.
* Methods such as {@link #isStarted()}, {@link #isPaused()}, and {@link #isRunning()} are used to query current status of server.
* Every time server change its current status, it notifies an event {@code ServerStatusEvent} to listeners that implement {@link ServerStatusListener} interface.
* Such listeners are called {@code server status listeners}, which must be registered with server by method {@link #addStatusListener(ServerStatusListener)} to receive server status events.
* A {@code server status event} is removed from server by calling {@link #removeStatusListener(ServerStatusListener)}.
* <br><br>
* Within client-server architecture, the popular recommendation scenario includes five following steps in top-down order:
* <ol>
* <li>
* User (or client application) specifies her / his request in text format. Typical client application is the {@code Evaluator} module.
* {@code Interpreter} component in {@code interface layer} parses such text into JSON format request. {@code Listener} component in interface layer sends JSON format request to service layer.
* In distributed environment, {@code balancer} is responsible for choosing optimal service layer site to send JSON request.
* </li>
* <li>
* {Service layer} receives JSON request from interface layer. There are two occasions:
* <ul>
* <li>
* Request is to get favorite items. In this case, request is passed to recommender service. Recommender service applies appropriate strategy into producing a list of favorite items.
* If snapshot (or scanner) necessary to recommendation algorithms is not available in {@code share memory layer}, recommender service requires storage service to create {@code snapshot} (or {@code scanner}).
* After that, the list of favorite items is sent back to interface layer as {@code JSON format result}.
* </li>
* <li>
* Request is to retrieve or update data such as querying item profile, querying average rating on specified item, rating an item, and modifying user profile.
* In this case, request is passed to storage service. If request is to update data then, an {@code update request} is sent to transaction layer.
* If request is to retrieve information then {@code storage service} looks up share memory layer to find out appropriate snapshot or scanner.
* If such snapshot (or scanner) does not exists nor contains requisite information then, a {@code retrieval request} is sent to transaction layer;
* otherwise, in found case, requisite information is extracted from found snapshot (or scanner) and sent back to interface layer as {@code JSON format result}.
* </li>
* </ul>
* </li>
* <li>
* {@code Transaction layer} analyzes {@code update requests} and {@code retrieval requests} from service layer and parses them into transactions.
* Each transaction is a bunch of read and write operations. All low-level operations are harmonized in terms of concurrency requirement and sent to data layer later.
* Some access concurrency algorithms can be used according to pre-defined isolation level.
* </li>
* <li>
* {@code Data layer} processes read and write operations and sends back {@code raw result} to transaction layer. Raw result is the piece of information stored in {@code Dataset} and {@code KBase}.
* Raw result can be output variable indicating whether or not update (write) request is processed successfully. Transaction layer collects and sends back the raw result to service layer.
* Service layer translates raw result into {@code JSON format result} and sends such translated result to interface layer in succession.
* </li>
* <li>
* The {@code interpreter} component in interface layer receives and translates {@code JSON format result} into text format result easily understandable for users.
* </li>
* </ol>
*
* @author Loc Nguyen
* @version 10.0
*
*/
public interface Server extends Remote {
/**
* Server starts.
* @throws RemoteException if any error raises.
*/
void start() throws RemoteException;
/**
* Server pauses.
* @throws RemoteException if any error raises.
*/
void pause() throws RemoteException;
/**
* Server resumes
* @throws RemoteException if any error raises.
*/
void resume() throws RemoteException;
/**
* Server stops. After server stopped, it can re-start by calling {@link #start()}.
* @throws RemoteException if any error raises.
*/
void stop() throws RemoteException;
/**
* Exiting server. After server is exited, it is removed from memory and it cannot be started again.
* @throws RemoteException if any error raises.
*/
void exit() throws RemoteException;
/**
* Testing whether server started.
* @return whether server started.
* @throws RemoteException if any error raises.
*/
boolean isStarted() throws RemoteException;
/**
* Testing whether server paused.
* @return whether server paused.
* @throws RemoteException if any error raises.
*/
boolean isPaused() throws RemoteException;
/**
* Testing whether server is running.
* @return whether server is running.
* @throws RemoteException if any error raises.
*/
boolean isRunning() throws RemoteException;
/**
* Every server owns an internal configuration. This method returns such configuration.
* @return {@link DataConfig}
* @throws RemoteException if any error raises.
*/
DataConfig getConfig() throws RemoteException;
/**
* Every server owns an internal configuration. This method sets a new configuration.
* @param config new configuration.
* @throws RemoteException if any error raises.
*/
void setConfig(DataConfig config) throws RemoteException;
/**
* Server has six statuses as follows:
* <ul>
* <li>"started": Server started. If server has just started right after calling {@link #start()}, it is in two statuses: "started" and "running".</li>
* <li>"paused": Server paused. Server are currently in both "started" status and "paused" status.</li>
* <li>"resumed": Server resumed. Server are currently in three statuses: "started", "resumed", and "running".</li>
* <li>"stopped": Server stopped and so server is in "stopped" status.</li>
* <li>"setconfig": Server is in setting its configuration. Sever must stop so that it can set its configuration. So server is now in two statuses: "stopped" and "setconfig".</li>
* <li>"exit": Server exits and so server does not exist. Status "exit" is unreal.</li>
* </ul>
* Some statuses are overlapped; for example, server is in status "paused" is also in status "started".
* When server changes its current status by calling methods such as {@link #start()}, {@link #pause()}, {@link #resume()}, {@link #stop()}, and {@link #exit()}.
* Methods such as {@link #isStarted()}, {@link #isPaused()}, and {@link #isRunning()} are used to query current status of server.
* Every time server change its current status, it notifies an event {@code ServerStatusEvent} to listeners that implement {@link ServerStatusListener} interface.
* Such listeners are called {@code server status listeners}, which must be registered with server by this method {@link #addStatusListener(ServerStatusListener)} to receive server status events.
* A {@code server status event} is removed from server by calling {@link #removeStatusListener(ServerStatusListener)}.
*
* @param listener the {@code server status listener} that is registered into this server in order to receive server status event represented by {@code ServerStatusEvent} class.
* @return whether add listener successfully
* @throws RemoteException if any error raises.
*/
boolean addStatusListener(ServerStatusListener listener) throws RemoteException;
/**
* Server has six statuses as follows:
* <ul>
* <li>"started": Server started. If server has just started right after calling {@link #start()}, it is in two statuses: "started" and "running".</li>
* <li>"paused": Server paused. Server are currently in both "started" status and "paused" status.</li>
* <li>"resumed": Server resumed. Server are currently in three statuses: "started", "resumed", and "running".</li>
* <li>"stopped": Server stopped and so server is in "stopped" status.</li>
* <li>"setconfig": Server is in setting its configuration. Sever must stop so that it can set its configuration. So server is now in two statuses: "stopped" and "setconfig".</li>
* <li>"exit": Server exits and so server does not exist. Status "exit" is unreal.</li>
* </ul>
* Some statuses are overlapped; for example, server is in status "paused" is also in status "started".
* When server changes its current status by calling methods such as {@link #start()}, {@link #pause()}, {@link #resume()}, {@link #stop()}, and {@link #exit()}.
* Methods such as {@link #isStarted()}, {@link #isPaused()}, and {@link #isRunning()} are used to query current status of server.
* Every time server change its current status, it notifies an event {@code ServerStatusEvent} to listeners that implement {@link ServerStatusListener} interface.
* Such listeners are called {@code server status listeners}, which must be registered with server by this method {@link #addStatusListener(ServerStatusListener)} to receive server status events.
* A {@code server status event} is unregistered from server by calling this method {@link #removeStatusListener(ServerStatusListener)}.
* @param listener the {@code server status listener} that is unregistered from server and it no longer received server status event.
* @return whether add listener successfully
* @throws RemoteException if any error raises.
*/
boolean removeStatusListener(ServerStatusListener listener) throws RemoteException;
/**
* Testing whether server is working properly even though it stopped.
* @return whether ping successfully.
* @throws RemoteException if any error raises.
*/
boolean ping() throws RemoteException;
}
| true
|
73c65adac5502803c1eb3d3acddfb3156177a192
|
Java
|
keepinmindsh/sample
|
/templates/reactive-queue-command-handling/reactive-command-handling/src/main/java/lines/model/ResponseVO.java
|
UTF-8
| 173
| 1.625
| 2
|
[] |
no_license
|
package lines.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class ResponseVO {
private String itemKey;
}
| true
|
554639a4b460e237c3d6a05a56913d20af6fbbef
|
Java
|
AYashchuk/java-training
|
/ITC/src/Design_Pattern/FactoryMethod/PizzaStore/California/CaliforniaStyleCheesePizza.java
|
UTF-8
| 723
| 3.328125
| 3
|
[] |
no_license
|
package Design_Pattern.FactoryMethod.PizzaStore.California;
import Design_Pattern.FactoryMethod.PizzaStore.Pizza;
public class CaliforniaStyleCheesePizza extends Pizza {
public CaliforniaStyleCheesePizza() {
name = "California style Deep dish clam Pizza";
dough = "Extra thick crust dough";
sauce = "Plume Tomato Sauce";
toppings.add("Shredded Mozzarella Cheese");
toppings.add("Tomato");
toppings.add("Olives");
toppings.add("Beef");
}
@Override
public void bake(){
System.out.println("Bake for 40 minutes at 200 C");
}
@Override
public void cut() {
System.out.println("Cutting the pizza into square slices");
}
}
| true
|
44d2c02f67be9f61ce2de5457a9ec85062972d95
|
Java
|
xueqiya/chromium_src
|
/out/release/gen/services/network/public/mojom/mojom_java/generated_java/input_srcjars/org/chromium/network/mojom/LoadInfo.java
|
UTF-8
| 3,981
| 1.859375
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
// LoadInfo.java is auto generated by mojom_bindings_generator.py, do not edit
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is autogenerated by:
// mojo/public/tools/bindings/mojom_bindings_generator.py
// For:
// services/network/public/mojom/network_service.mojom
//
package org.chromium.network.mojom;
public final class LoadInfo extends org.chromium.mojo.bindings.Struct {
private static final int STRUCT_SIZE = 56;
private static final org.chromium.mojo.bindings.DataHeader[] VERSION_ARRAY = new org.chromium.mojo.bindings.DataHeader[] {new org.chromium.mojo.bindings.DataHeader(56, 0)};
private static final org.chromium.mojo.bindings.DataHeader DEFAULT_STRUCT_INFO = VERSION_ARRAY[0];
public int processId;
public int routingId;
public String host;
public int loadState;
public org.chromium.mojo_base.mojom.String16 stateParam;
public long uploadPosition;
public long uploadSize;
private LoadInfo(int version) {
super(STRUCT_SIZE, version);
}
public LoadInfo() {
this(0);
}
public static LoadInfo deserialize(org.chromium.mojo.bindings.Message message) {
return decode(new org.chromium.mojo.bindings.Decoder(message));
}
/**
* Similar to the method above, but deserializes from a |ByteBuffer| instance.
*
* @throws org.chromium.mojo.bindings.DeserializationException on deserialization failure.
*/
public static LoadInfo deserialize(java.nio.ByteBuffer data) {
return deserialize(new org.chromium.mojo.bindings.Message(
data, new java.util.ArrayList<org.chromium.mojo.system.Handle>()));
}
@SuppressWarnings("unchecked")
public static LoadInfo decode(org.chromium.mojo.bindings.Decoder decoder0) {
if (decoder0 == null) {
return null;
}
decoder0.increaseStackDepth();
LoadInfo result;
try {
org.chromium.mojo.bindings.DataHeader mainDataHeader = decoder0.readAndValidateDataHeader(VERSION_ARRAY);
final int elementsOrVersion = mainDataHeader.elementsOrVersion;
result = new LoadInfo(elementsOrVersion);
{
result.processId = decoder0.readInt(8);
}
{
result.routingId = decoder0.readInt(12);
}
{
result.host = decoder0.readString(16, false);
}
{
result.loadState = decoder0.readInt(24);
}
{
org.chromium.mojo.bindings.Decoder decoder1 = decoder0.readPointer(32, false);
result.stateParam = org.chromium.mojo_base.mojom.String16.decode(decoder1);
}
{
result.uploadPosition = decoder0.readLong(40);
}
{
result.uploadSize = decoder0.readLong(48);
}
} finally {
decoder0.decreaseStackDepth();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
protected final void encode(org.chromium.mojo.bindings.Encoder encoder) {
org.chromium.mojo.bindings.Encoder encoder0 = encoder.getEncoderAtDataOffset(DEFAULT_STRUCT_INFO);
encoder0.encode(this.processId, 8);
encoder0.encode(this.routingId, 12);
encoder0.encode(this.host, 16, false);
encoder0.encode(this.loadState, 24);
encoder0.encode(this.stateParam, 32, false);
encoder0.encode(this.uploadPosition, 40);
encoder0.encode(this.uploadSize, 48);
}
}
| true
|
5ed77c1750a79075c09a3581572b50e6dd80b87e
|
Java
|
ian-a-brown/utility
|
/src/test/java/usa/browntrask/utility/impl/FactoryFinderImplTest.java
|
UTF-8
| 1,171
| 2.515625
| 3
|
[] |
no_license
|
/**
* Copyright 2011 by Ian Andrew Brown<br>
* All Rights Reserved
*/
package usa.browntrask.utility.impl;
import static org.junit.Assert.assertEquals;
import usa.browntrask.utility.AbstractFactoryFinderCheck;
import usa.browntrask.utility.Factory;
/**
* Extended {@link AbstractFactoryFinderCheck} test for {@link FactoryFinderImpl}.
* <p>
*
* @author Ian Andrew Brown
* @since V1.7.0 May 3, 2011
* @version V1.7.0 May 6, 2011
*/
public final class FactoryFinderImplTest extends AbstractFactoryFinderCheck<FactoryFinderImpl<Factory>, Factory> {
/** {@inheritDoc} */
@Override
protected final void assertFactory(final Factory factory) {
assertEquals("The factory is the correct class", FactoryMock.class, factory.getClass());
}
/** {@inheritDoc} */
@Override
protected final String chooseFactory() {
return FactoryMock.class.getName();
}
/** {@inheritDoc} */
@Override
protected final FactoryFinderImpl<Factory> createFactoryFinder() {
return new FactoryFinderImpl<Factory>();
}
/** {@inheritDoc} */
@Override
protected final void setUpFactoryFinderType() {
}
/** {@inheritDoc} */
@Override
protected final void tearDownFactoryFinderType() {
}
}
| true
|
4b8922ce58b5e21ac863e835d840e2764de3d93d
|
Java
|
buom0701/EmployeeServices
|
/src/main/java/com/empservices/EmployeeServices/Model/TimeCard.java
|
UTF-8
| 1,265
| 2.234375
| 2
|
[] |
no_license
|
package com.empservices.EmployeeServices.Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import lombok.NonNull;
@Entity
@Table (name = "TIMECARD")
public class TimeCard {
@Id
@GeneratedValue
@Column
private int timecardid;
@Column
private String date;
@Column
private String in;
@Column
private String out;
@ManyToOne
@NonNull
@JoinColumn(name = "emp_id", referencedColumnName = "Id")
private Employee employee;
public int getTimecardid() {
return timecardid;
}
public void setTimecardid(int timecardid) {
this.timecardid = timecardid;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getIn() {
return in;
}
public void setIn(String in) {
this.in = in;
}
public String getOut() {
return out;
}
public void setOut(String out) {
this.out = out;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
}
| true
|
cd9977f9e990e34b83207b24d6da76cc1bc324c5
|
Java
|
diyiliu/little-pet
|
/pet-gw/src/main/java/com/dyl/gw/netty/handler/codec/PetEncoder.java
|
UTF-8
| 575
| 2.25
| 2
|
[] |
no_license
|
package com.dyl.gw.netty.handler.codec;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
/**
* Description: PetEncoder
* Author: DIYILIU
* Update: 2018-07-06 09:51
*/
@Slf4j
public class PetEncoder extends MessageToByteEncoder {
@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) {
ByteBuf buf = (ByteBuf) msg;
if (buf.readableBytes() > 0){
out.writeBytes(buf);
}
}
}
| true
|
482aff2f4d9bd7f042b597634268f5955d385bdb
|
Java
|
Kimtaein931/Biz_2021_01_403_java
|
/Java_025A_Student/src/com/callor/student/Ex_08.java
|
UTF-8
| 650
| 3.78125
| 4
|
[] |
no_license
|
package com.callor.student;
import java.util.Random;
/*
* 정수형 배열 100개를 선언하여
* 10 ~ 100까지 임의의 정수를 생성하여 저장
* 100개의 배열에 담긴 정수 중에 소수들만 찾아서
* Console에 출력
*/
public class Ex_08 {
public static void main(String[] args) {
Random rnd = new Random();
int[] num = new int[100];
int j = 0;
for (int i = 0; i < num.length; i++) {
num[i] = rnd.nextInt(90) + 11;
for (j = 2; j < num[i]; j++) {
if (num[i] % j == 0) {
break;
}
}
if (j < num[i]) {
} else {
System.out.println(i + "번째 소수 : " + num[i]);
}
}
}
}
| true
|
3163c058fe48ed97722869ef79189758f6b09e90
|
Java
|
henqqqcs/catalogonet
|
/catalogonet/src/main/java/com/catalogonet/model/SubCategoria.java
|
UTF-8
| 1,918
| 2.296875
| 2
|
[] |
no_license
|
package com.catalogonet.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import com.catalogonet.util.StringFormat;
@Entity
@Table(name = "sub_categoria")
public class SubCategoria implements Serializable {
private static final long serialVersionUID = -9146984124301460591L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_sub_categoria")
private Long id;
private String nome;
@Column(name = "nome_na_url")
private String nomeNaUrl;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "sub_categoria_tags")
private List<String> tags = new ArrayList<String>();
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "categoria_id")
private Categoria categoria;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.setNomeNaUrl(nome);
this.nome = nome;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public Categoria getCategoria() {
return categoria;
}
public void setCategoria(Categoria categoria) {
this.categoria = categoria;
}
public String getNomeNaUrl() {
return nomeNaUrl;
}
public void setNomeNaUrl(String nomeNaUrl) {
this.nomeNaUrl = StringFormat.formatarStringParaUrl(nomeNaUrl);
}
}
| true
|
674176209947277ee62b84e1015c8a581ab69514
|
Java
|
wubian120/JavaBasic
|
/src/main/java/cn/brady/generic/BridgePair.java
|
UTF-8
| 587
| 3.078125
| 3
|
[] |
no_license
|
package cn.brady.generic;
/**
* Created by Brady on 2017/5/5.
*/
public class BridgePair<T> {
private T first;
private T second;
public BridgePair(){
first = null;
second = null;
}
public BridgePair(T first, T second){
this.first = first;
this.second = second;
}
public T getFirst() {
return first;
}
public T getSecond() {
return second;
}
public void setFirst(T first) {
this.first = first;
}
public void setSecond(T second) {
this.second = second;
}
}
| true
|
f2a8a9ef39d1187b3612976c1407d3580a232ff9
|
Java
|
namtrung2212/android-taxi-driver
|
/app/src/main/java/com/sconnecting/driverapp/ui/taxi/search/lateorder/LateOrderMap.java
|
UTF-8
| 15,449
| 1.601563
| 2
|
[] |
no_license
|
package com.sconnecting.driverapp.ui.taxi.search.lateorder;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.sconnecting.driverapp.R;
import com.sconnecting.driverapp.SCONNECTING;
import com.sconnecting.driverapp.base.InternetHelper;
import com.sconnecting.driverapp.google.GoogleDirectionHelper;
import com.sconnecting.driverapp.location.LocationHelper;
import com.sconnecting.driverapp.base.listener.Completion;
import com.sconnecting.driverapp.data.models.TravelOrder;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
/**
* Created by TrungDao on 10/17/16.
*/
public class LateOrderMap extends Fragment {
SupportMapFragment mapFragment;
View view;
LateOrderScreen parent;
public TravelOrder CurrentOrder() {
return parent.currentOrder;
}
public String currentEncodedPolyline;
public GoogleMap gmsMapView;
public Polyline pathPolyLine;
public Marker mSourceMarker;
public Marker mDestinyMarker;
public LateOrderMap(){
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
parent = (LateOrderScreen) context;
parent.mMapView = this;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.taxi_late_order_map, container, false);
initControls();
return view;
}
public void initControls() {
if (! InternetHelper.checkConnectingToInternet()) {
return;
}
mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.googlemap);
mapFragment.getMapAsync(new OnMapReadyCallback(){
@Override
public void onMapReady(GoogleMap map) {
gmsMapView = map;
if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,android.Manifest.permission.ACCESS_COARSE_LOCATION},2212);
return;
}
gmsMapView.setMyLocationEnabled(false);
gmsMapView.getUiSettings().setMyLocationButtonEnabled(false);
gmsMapView.getUiSettings().setScrollGesturesEnabled(true);
gmsMapView.getUiSettings().setZoomGesturesEnabled(true);
gmsMapView.getUiSettings().setTiltGesturesEnabled(true);
gmsMapView.getUiSettings().setRotateGesturesEnabled(true);
gmsMapView.getUiSettings().setMapToolbarEnabled(false);
gmsMapView.getUiSettings().setZoomControlsEnabled(false);
gmsMapView.setMapType(1);
gmsMapView.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
@Override
public void onCameraIdle() {
}
});
Picasso.with(parent).load(R.drawable.sourcepin).resize(80, 80).centerCrop().into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
if(gmsMapView != null){
mSourceMarker = gmsMapView.addMarker(new MarkerOptions()
.position(new LatLng(0,0))
.title("Điểm đi")
.icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.anchor((float) 0.5,1)
);
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
Picasso.with(parent).load(R.drawable.destinypin).resize(80, 80).centerCrop().into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
if(gmsMapView != null){
mDestinyMarker = gmsMapView.addMarker(new MarkerOptions()
.position(new LatLng(0,0))
.title("Điểm đến")
.icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.anchor((float) 0.5,1)
);
mDestinyMarker.setVisible(false);
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
if(parent.mapReadyListener != null)
parent.mapReadyListener.onReady();
}
}
);
}
@SuppressWarnings("MissingPermission")
public void invalidate(Boolean isFirstTime, final Completion listener){
gmsMapView.setMyLocationEnabled(false);
invalidatePath();
if(listener != null)
listener.onCompleted();
}
public void invalidatePath(){
if(CurrentOrder() == null){
if (pathPolyLine != null)
pathPolyLine.remove();
gmsMapView.setPadding(5, 5, 5, 5);
invalidateRouteMarkers();
}else{
String strEncodedPolyline = null;
if(CurrentOrder().OrderPolyline != null)
strEncodedPolyline = CurrentOrder().OrderPolyline;
final String encoded = strEncodedPolyline;
if(strEncodedPolyline != null && (currentEncodedPolyline == null || currentEncodedPolyline.equals(encoded) == false)) {
new GoogleDirectionHelper(this.getContext()).requestPolyline(gmsMapView, strEncodedPolyline, new PolylineOptions().width(3).color(Color.rgb(73, 139, 199)), new GoogleDirectionHelper.RequestPolylineResult() {
@Override
public void onCompleted(Polyline polyline) {
if (polyline != null) {
if (pathPolyLine != null)
pathPolyLine.remove();
pathPolyLine = polyline;
currentEncodedPolyline = encoded;
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng pos : pathPolyLine.getPoints()) {
builder.include(pos);
}
LatLngBounds bounds = builder.build();
gmsMapView.setPadding(100, 100, 100, 450);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 0);
gmsMapView.moveCamera(cameraUpdate);
}
});
}else{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
if(CurrentOrder().OrderPickupLoc != null)
builder.include(CurrentOrder().OrderPickupLoc.getLatLng());
if(CurrentOrder().OrderDropLoc != null)
builder.include(CurrentOrder().OrderDropLoc.getLatLng());
LatLngBounds bounds = builder.build();
gmsMapView.setPadding(100, 100, 100, 450);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 0);
gmsMapView.moveCamera(cameraUpdate);
}
invalidateRouteMarkers();
}
}
void invalidateRouteMarkers(){
LatLng sourceLoc = null;
LatLng destinyLoc = null;
if(this.CurrentOrder() != null && this.CurrentOrder().OrderPickupLoc != null ){
sourceLoc = this.CurrentOrder().OrderPickupLoc.getLatLng();
}
if(this.CurrentOrder() != null && this.CurrentOrder().OrderDropLoc != null){
destinyLoc = this.CurrentOrder().OrderDropLoc.getLatLng();
}
if(this.mSourceMarker == null){
final LatLng sourceLoc2 = sourceLoc;
Picasso.with(parent).load(R.drawable.sourcepin).resize(80, 80).centerCrop().into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
if(gmsMapView != null){
mSourceMarker = gmsMapView.addMarker(new MarkerOptions()
.position(new LatLng(0,0))
.title("Điểm đi")
.icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.anchor((float) 0.5,1)
);
mSourceMarker.setVisible( sourceLoc2 != null );
if( mSourceMarker.isVisible()){
mSourceMarker.setPosition(sourceLoc2);
}
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
if(this.mSourceMarker != null){
this.mSourceMarker.setVisible( sourceLoc != null );
if( this.mSourceMarker.isVisible()){
this.mSourceMarker.setPosition(sourceLoc);
}
}
if(this.mDestinyMarker == null) {
final LatLng destinyLoc2 = destinyLoc;
Picasso.with(parent).load(R.drawable.destinypin).resize(80, 80).centerCrop().into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
if(gmsMapView != null){
mDestinyMarker = gmsMapView.addMarker(new MarkerOptions()
.position(new LatLng(0,0))
.title("Điểm đến")
.icon(BitmapDescriptorFactory.fromBitmap(bitmap))
.anchor((float) 0.5,1)
);
mDestinyMarker.setVisible( destinyLoc2 != null );
if( mDestinyMarker.isVisible()){
mDestinyMarker.setPosition(destinyLoc2);
}
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
if(this.mDestinyMarker != null) {
this.mDestinyMarker.setVisible(destinyLoc != null);
if (this.mDestinyMarker.isVisible()) {
this.mDestinyMarker.setPosition(destinyLoc);
}
}
}
public void moveToLocation(LatLng target,Boolean isAnimate,Integer zoom ){
if(isAnimate != null && isAnimate == true){
if(zoom != null){
this.gmsMapView.animateCamera(CameraUpdateFactory.newLatLngZoom(target,zoom));
}else{
this.gmsMapView.animateCamera(CameraUpdateFactory.newLatLng(target));
}
return;
}
Location source = LocationHelper.newLocation(target);
Location destiny = LocationHelper.newLocation(this.gmsMapView.getCameraPosition().target);
Float distance = Math.abs(source.distanceTo(destiny));
if(distance > 100 || (isAnimate != null && isAnimate == false)){
if(zoom != null){
this.gmsMapView.moveCamera(CameraUpdateFactory.newLatLngZoom(target,zoom));
}else{
this.gmsMapView.moveCamera(CameraUpdateFactory.newLatLng(target));
}
}else{
if(zoom != null){
this.gmsMapView.animateCamera(CameraUpdateFactory.newLatLngZoom(target,zoom));
}else{
this.gmsMapView.animateCamera(CameraUpdateFactory.newLatLng(target));
}
}
}
}
| true
|
e2814ab61b5269e3ccf594581feb9a70426820ae
|
Java
|
freewind/everrest
|
/everrest-core/src/test/java/org/everrest/core/impl/header/AcceptMediaTypeTest.java
|
UTF-8
| 4,273
| 1.992188
| 2
|
[] |
no_license
|
/*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.everrest.core.impl.header;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
/**
* @author andrew00x
*/
public class AcceptMediaTypeTest {
@Test
public void testValueOf() {
String mt = "text/xml;charset=utf8";
AcceptMediaType acceptedMediaType = AcceptMediaType.valueOf(mt);
Assert.assertEquals("text", acceptedMediaType.getType());
Assert.assertEquals("xml", acceptedMediaType.getSubtype());
Assert.assertEquals("utf8", acceptedMediaType.getParameters().get("charset"));
Assert.assertEquals(1.0F, acceptedMediaType.getQvalue(), 0.0F);
}
@Test
public void testValueOfWithQValue() {
String mt = "text/xml;charset=utf8;q=0.825";
AcceptMediaType acceptedMediaType = AcceptMediaType.valueOf(mt);
Assert.assertEquals("text", acceptedMediaType.getType());
Assert.assertEquals("xml", acceptedMediaType.getSubtype());
Assert.assertEquals("utf8", acceptedMediaType.getParameters().get("charset"));
Assert.assertEquals(0.825F, acceptedMediaType.getQvalue(), 0.0F);
}
@Test
public void testFromString() {
String mt = "text/xml;charset=utf8";
AcceptMediaTypeHeaderDelegate hd = new AcceptMediaTypeHeaderDelegate();
AcceptMediaType acceptedMediaType = hd.fromString(mt);
Assert.assertEquals("text", acceptedMediaType.getType());
Assert.assertEquals("xml", acceptedMediaType.getSubtype());
Assert.assertEquals("utf8", acceptedMediaType.getParameters().get("charset"));
Assert.assertEquals(1.0F, acceptedMediaType.getQvalue(), 0.0F);
}
@Test
public void testFromStringWithQValue() {
String mt = "text/xml;charset=utf8;q=0.825";
AcceptMediaTypeHeaderDelegate hd = new AcceptMediaTypeHeaderDelegate();
AcceptMediaType acceptedMediaType = hd.fromString(mt);
Assert.assertEquals("text", acceptedMediaType.getType());
Assert.assertEquals("xml", acceptedMediaType.getSubtype());
Assert.assertEquals("utf8", acceptedMediaType.getParameters().get("charset"));
Assert.assertEquals(0.825F, acceptedMediaType.getQvalue(), 0.0F);
}
@Test
public void testListProducerNull() {
List<AcceptMediaType> l = HeaderHelper.createAcceptedMediaTypeList(null);
Assert.assertEquals(1, l.size());
Assert.assertEquals(l.get(0).getType(), "*");
Assert.assertEquals(l.get(0).getSubtype(), "*");
Assert.assertEquals(l.get(0).getQvalue(), 1.0F, 0.0F);
}
@Test
public void testListProducerEmptyString() {
List<AcceptMediaType> l = HeaderHelper.createAcceptedMediaTypeList("");
Assert.assertEquals(1, l.size());
Assert.assertEquals(l.get(0).getType(), "*");
Assert.assertEquals(l.get(0).getSubtype(), "*");
Assert.assertEquals(l.get(0).getQvalue(), 1.0F, 0.0F);
}
@Test
public void testListProducer() {
String mt = "text/xml; charset=utf8;q=0.825, text/html;charset=utf8, text/plain;charset=utf8;q=0.8";
List<AcceptMediaType> l = HeaderHelper.createAcceptedMediaTypeList(mt);
Assert.assertEquals(3, l.size());
Assert.assertEquals(l.get(0).getType(), "text");
Assert.assertEquals(l.get(0).getSubtype(), "html");
Assert.assertEquals(l.get(0).getQvalue(), 1.0F, 0.0F);
Assert.assertEquals(l.get(1).getType(), "text");
Assert.assertEquals(l.get(1).getSubtype(), "xml");
Assert.assertEquals(l.get(1).getQvalue(), 0.825F, 0.0F);
Assert.assertEquals(l.get(2).getType(), "text");
Assert.assertEquals(l.get(2).getSubtype(), "plain");
Assert.assertEquals(l.get(2).getQvalue(), 0.8F, 0.0F);
}
}
| true
|
2c3ac47bc18234abc1eb2f819af9a80071635624
|
Java
|
Ford-gxq/javaSE
|
/com.xxx.oop01/src/equals_toStringDemo/Employee.java
|
UTF-8
| 2,027
| 3.84375
| 4
|
[] |
no_license
|
package equals_toStringDemo;
/**
* 自定义员工类, 姓名, 编号, 身高...
* 要求: 比计较员工是否相等要求比较所有成员属性的值,都想等true, 任何一个不相等返回false
* */
/**
员工类
*/
public class Employee {
private int id;
private String name;
private int height;
//alt+insert -> constructor ->select none |选中对应要赋值的属性 enter
//空构造
public Employee() {
}
//有参构造
public Employee(int id, String name, int height) {
this.id = id;
this.name = name;
this.height = height;
}
/**设置器与访问器*/
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 int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", height=" + height +
'}';
}
/**
比较所有员工的属性值
*/
public boolean equals(Object obj){
if(this==obj){
return true;
}
if(obj instanceof Employee){
Employee emp = (Employee)obj;
if(this.id==emp.id && this.name.equals(emp.name) && this.height==emp.height){
return true;
}
}
return false;
}
/** @Override 使用快捷键自动生成equals方法
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return id == employee.id &&
height == employee.height &&
Objects.equals(name, employee.name);
} **/
}
| true
|
ef1d153b5583efe613d3960c92530e25daec0e92
|
Java
|
amadeus1029/chapter02
|
/src/com/javaex/ex15/addGoodsApp.java
|
UTF-8
| 620
| 3.390625
| 3
|
[] |
no_license
|
package com.javaex.ex15;
public class addGoodsApp {
public static void main(String[] args) {
Goods[] goodsArray = new Goods[3];
Goods computer = new Goods("엘지그램",1000000);
Goods camera = new Goods("캐논",500000);
Goods cup = new Goods("머그컵",10000);
goodsArray[0] = computer;
goodsArray[1] = camera;
goodsArray[2] = cup;
//이거 그냥 배열 자체를 출력해도 알아서 toString 찾는 특성이 있음
for(int i=0;i<goodsArray.length;i++) {
System.out.println(goodsArray[i].toString());
}
}
}
| true
|
384334b7fb7c0552f76d640d5f819f90cebc06a1
|
Java
|
wojciechwaldon/users
|
/users-api/src/main/java/com/wojciechwaldon/users/api/authorizeduser/AuthorizedUserHttpEndpoints.java
|
UTF-8
| 2,203
| 2.078125
| 2
|
[] |
no_license
|
package com.wojciechwaldon.users.api.authorizeduser;
import com.wojciechwaldon.cqrs.api.command.CommandExecutor;
import com.wojciechwaldon.cqrs.api.query.QueryExecutor;
import com.wojciechwaldon.users.api.UsersModuleHttpEndpoint;
import com.wojciechwaldon.users.domain.api.authorizeduser.AuthorizedUser;
import com.wojciechwaldon.users.domain.api.authorizeduser.find.FindAuthorizedUserQuery;
import com.wojciechwaldon.users.domain.api.authorizeduser.find.FindAuthorizedUserQueryView;
import com.wojciechwaldon.users.domain.api.authorizeduser.save.SaveAuthorizedUserCommand;
import com.wojciechwaldon.users.domain.api.authorizeduser.save.SaveOrUpdateAuthorizedUserCommand;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@RequestMapping(path = "/user",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE)
public class AuthorizedUserHttpEndpoints extends UsersModuleHttpEndpoint {
public AuthorizedUserHttpEndpoints(CommandExecutor commandExecutor,
QueryExecutor queryExecutor) {
super(commandExecutor, queryExecutor);
}
@PostMapping(
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE
)
public void saveUser(@RequestBody AuthorizedUser authorizedUser) throws Exception {
SaveAuthorizedUserCommand saveAuthorizedUserCommand = SaveAuthorizedUserCommand.of(authorizedUser);
commandExecutor.execute(saveAuthorizedUserCommand);
}
@PostMapping(path = "/update")
public void saveUserOrUpdate(@RequestBody AuthorizedUser authorizedUser) throws Exception {
SaveOrUpdateAuthorizedUserCommand saveAuthorizedUserCommand = SaveOrUpdateAuthorizedUserCommand.of(authorizedUser);
commandExecutor.execute(saveAuthorizedUserCommand);
}
@GetMapping(path = "/{id}")
@ResponseBody
public FindAuthorizedUserQueryView findUser(@PathVariable Long id) throws Exception {
FindAuthorizedUserQuery findAuthorizedUserQuery = FindAuthorizedUserQuery.of(id);
return queryExecutor.execute(findAuthorizedUserQuery);
}
}
| true
|
8941fd9dc6d23cdbce78de44e0013cc5a2bcc358
|
Java
|
markus-17/object-oriented-programming-course
|
/src/main/java/com/lab7/Square.java
|
UTF-8
| 418
| 3.71875
| 4
|
[] |
no_license
|
public class Square extends Figure {
private double width;
public Square(double width) {
this.width = width;
}
@Override
public double getArea() {
return this.width * this.width;
}
@Override
public double getPerimeter() {
return this.width * 4;
}
@Override
public String toString() {
return "Square { width: " + this.width + " }";
}
}
| true
|
1cda6f141a3a2943b97e5db78412a420ef845973
|
Java
|
22896/mombo
|
/app/src/main/java/com/example/mombo/call.java
|
UTF-8
| 1,735
| 2.140625
| 2
|
[] |
no_license
|
package com.example.mombo;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
public class call extends AppCompatActivity implements View.OnClickListener {
private Button mCall;
private Button mDialog;
private EditText mEditNumber;
private String mNum;
private ImageButton mBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
mBack = (ImageButton) findViewById(R.id.back);
mCall = (Button) findViewById(R.id.BtnCall);
mDialog = (Button) findViewById((R.id.BtnDialog));
mEditNumber = (EditText) findViewById((R.id.edtNum));
mCall.setOnClickListener(this);
mDialog.setOnClickListener(this);
mBack.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View w) {
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(intent);
}
});
}
@Override
public void onClick(View v) {
mNum = mEditNumber.getText().toString();
String tel = "tel:" + mNum;
switch (v.getId()) {
case R.id.BtnCall:
startActivity(new Intent("android.intent.action.CALL", Uri.parse(tel)));
break;
case R.id.BtnDialog:
startActivity(new Intent("android.intent.action.DIAL", Uri.parse(tel)));
break;
}
}
}
| true
|
344283bd201b141a539f5e25f0e1ca5d05c0aad4
|
Java
|
pmabiala/sabbath-school-android-legacy
|
/app/src/main/java/com/cryart/sabbathschool/ui/activity/SSBibleVerseActivity.java
|
UTF-8
| 3,825
| 1.757813
| 2
|
[] |
no_license
|
/*
* Copyright (c) 2015 Vitaliy Lim <lim.vitaliy@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.cryart.sabbathschool.ui.activity;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import com.cryart.sabbathschool.R;
import com.cryart.sabbathschool.util.SSConstants;
import com.cryart.sabbathschool.util.SSHelper;
public class SSBibleVerseActivity extends Activity {
private RelativeLayout _SSLoadingHolder;
@Override
protected void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.ss_bible_verse_activity);
getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
ImageButton _SSCloseButton = (ImageButton) findViewById(R.id.ss_bible_verse_activity_close);
_SSLoadingHolder = (RelativeLayout) findViewById(R.id.ss_bible_verse_activity_loading_holder);
_SSLoadingHolder.setVisibility(View.VISIBLE);
_SSCloseButton.setOnClickListener(this.onCloseClick(this));
String _SSBibleDayVerses;
WebView _SSBibleVerseContent;
SharedPreferences _SSPreferences;
_SSPreferences = PreferenceManager.getDefaultSharedPreferences(this);
_SSBibleDayVerses = getIntent().getExtras().getString(SSConstants.SS_BIBLE_VERSE_ACTIVITY_ARGUMENT);
_SSBibleVerseContent = (WebView) findViewById(R.id.ss_bible_verse_activity_content);
_SSBibleVerseContent.loadDataWithBaseURL(SSConstants.SS_WEBAPP_PATH_PREFIX,
SSHelper.readFileFromAssets(this, SSConstants.SS_WEBAPP_BIBLE)
.replaceAll("\\{\\{platform\\}\\}", SSConstants.SS_WEBAPP_PLATFORM)
.replaceAll("small.css", _SSPreferences.getString(SSConstants.SS_SETTINGS_TEXT_SIZE_KEY, SSConstants.SS_SETTINGS_TEXT_SIZE_DEFAULT_VALUE))
.replaceAll("<div class=\"wrapper\">", "<div class=\"wrapper\">" + _SSBibleDayVerses),
"text/html", "utf-8", null);
_SSBibleVerseContent.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
_SSLoadingHolder.setVisibility(View.INVISIBLE);
view.setVisibility(View.VISIBLE);
}
});
}
public View.OnClickListener onCloseClick(final Activity context) {
return new View.OnClickListener() {
@Override
public void onClick(View v) {
context.finish();
}
};
}
}
| true
|
8bd16fc703cb7560412a53fefc9e4d456e8389fc
|
Java
|
aarongraham9/IPCTracker
|
/src/com/kronius/IPCTracker/IPCTrackerDataV2.java
|
UTF-8
| 8,838
| 2.34375
| 2
|
[] |
no_license
|
package com.kronius.IPCTracker;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
public class IPCTrackerDataV2 implements Serializable {
private static final long serialVersionUID = 6969604483485414104L;
private int SUTotal;
private int GerTotal;
private int UKTotal;
private int JapTotal;
private int USTotal;
private List<String> TransactionHistorySU;
private List<String> TransactionHistoryGer;
private List<String> TransactionHistoryUK;
private List<String> TransactionHistoryJap;
private List<String> TransactionHistoryUS;
private boolean isVictoryConditionNine;
private boolean isVictoryCityWashingtonAxis;
private boolean isVictoryCityLondonAxis;
private boolean isVictoryCityLeningradAxis;
private boolean isVictoryCityMoscowAxis;
private boolean isVictoryCityCalcuttaAxis;
private boolean isVictoryCityLosAngelesAxis;
private boolean isVictoryCityBerlinAxis;
private boolean isVictoryCityParisAxis;
private boolean isVictoryCityRomeAxis;
private boolean isVictoryCityShanghaiAxis;
private boolean isVictoryCityManilaAxis;
private boolean isVictoryCityTokyoAxis;
public IPCTrackerDataV2(){
SUTotal = 0;
GerTotal = 0;
UKTotal = 0;
JapTotal = 0;
USTotal = 0;
TransactionHistorySU = new LinkedList<String>();
TransactionHistoryGer = new LinkedList<String>();
TransactionHistoryUK = new LinkedList<String>();
TransactionHistoryJap = new LinkedList<String>();
TransactionHistoryUS = new LinkedList<String>();
isVictoryCityWashingtonAxis = false;
isVictoryCityLondonAxis = false;
isVictoryCityLeningradAxis = false;
isVictoryCityMoscowAxis = false;
isVictoryCityCalcuttaAxis = false;
isVictoryCityLosAngelesAxis = false;
isVictoryCityBerlinAxis = true;
isVictoryCityParisAxis = true;
isVictoryCityRomeAxis = true;
isVictoryCityShanghaiAxis = true;
isVictoryCityManilaAxis = true;
isVictoryCityTokyoAxis = true;
}
public IPCTrackerDataV2(int SUTotalIn, int GerTotalIn, int UKTotalIn, int JapTotalIn, int USTotalIn,
List<String> TransactionHistorySUIn, List<String> TransactionHistoryGerIn,
List<String> TransactionHistoryUKIn, List<String> TransactionHistoryJapIn,
List<String> TransactionHistoryUSIn, boolean isVictoryCityWashingtonAxisIn,
boolean isVictoryCityLondonAxisIn, boolean isVictoryCityLeningradAxisIn,
boolean isVictoryCityMoscowAxisIn, boolean isVictoryCityCalcuttaAxisIn,
boolean isVictoryCityLosAngelesAxisIn, boolean isVictoryCityBerlinAxisIn,
boolean isVictoryCityParisAxisIn, boolean isVictoryCityRomeAxisIn,
boolean isVictoryCityShanghaiAxisIn, boolean isVictoryCityManilaAxisIn,
boolean isVictoryCityTokyoAxisIn){
SUTotal = SUTotalIn;
GerTotal = GerTotalIn;
UKTotal = UKTotalIn;
JapTotal = JapTotalIn;
USTotal = USTotalIn;
TransactionHistorySU = TransactionHistorySUIn;
TransactionHistoryGer = TransactionHistoryGerIn;
TransactionHistoryUK = TransactionHistoryUKIn;
TransactionHistoryJap = TransactionHistoryJapIn;
TransactionHistoryUS = TransactionHistoryUSIn;
isVictoryCityWashingtonAxis = isVictoryCityWashingtonAxisIn;
isVictoryCityLondonAxis = isVictoryCityLondonAxisIn;
isVictoryCityLeningradAxis = isVictoryCityLeningradAxisIn;
isVictoryCityMoscowAxis = isVictoryCityMoscowAxisIn;
isVictoryCityCalcuttaAxis = isVictoryCityCalcuttaAxisIn;
isVictoryCityLosAngelesAxis = isVictoryCityLosAngelesAxisIn;
isVictoryCityBerlinAxis = isVictoryCityBerlinAxisIn;
isVictoryCityParisAxis = isVictoryCityParisAxisIn;
isVictoryCityRomeAxis = isVictoryCityRomeAxisIn;
isVictoryCityShanghaiAxis = isVictoryCityShanghaiAxisIn;
isVictoryCityManilaAxis = isVictoryCityManilaAxisIn;
isVictoryCityTokyoAxis = isVictoryCityTokyoAxisIn;
}
public void setSUTotal(int SUTotalIn){
SUTotal = SUTotalIn;
}
public int getSUTotal(){
return SUTotal;
}
public void setGerTotal(int GerTotalIn){
GerTotal = GerTotalIn;
}
public int getGerTotal(){
return GerTotal;
}
public void setUKTotal(int UKTotalIn){
UKTotal = UKTotalIn;
}
public int getUKTotal(){
return UKTotal;
}
public void setJapTotal(int JapTotalIn){
JapTotal = JapTotalIn;
}
public int getJapTotal(){
return JapTotal;
}
public void setUSTotal(int USTotalIn){
USTotal = USTotalIn;
}
public int getUSTotal(){
return USTotal;
}
public void setTransactionHistorySU(List<String> TransactionHistorySUIn){
TransactionHistorySU = TransactionHistorySUIn;
}
public List<String> getTransactionHistorySU(){
return TransactionHistorySU;
}
public void setTransactionHistoryGer(List<String> TransactionHistoryGerIn){
TransactionHistoryGer = TransactionHistoryGerIn;
}
public List<String> getTransactionHistoryGer(){
return TransactionHistoryGer;
}
public void setTransactionHistoryUK(List<String> TransactionHistoryUKIn){
TransactionHistoryUK = TransactionHistoryUKIn;
}
public List<String> getTransactionHistoryUK(){
return TransactionHistoryUK;
}
public void setTransactionHistoryJap(List<String> TransactionHistoryJapIn){
TransactionHistoryJap = TransactionHistoryJapIn;
}
public List<String> getTransactionHistoryJap(){
return TransactionHistoryJap;
}
public void setTransactionHistoryUS(List<String> TransactionHistoryUSIn){
TransactionHistoryUS = TransactionHistoryUSIn;
}
public List<String> getTransactionHistoryUS(){
return TransactionHistoryUS;
}
public void setIsVictoryConditionNine(boolean isVictoryConditionNineIn){
isVictoryConditionNine = isVictoryConditionNineIn;
}
public boolean getIsVictoryConditionNine(){
return isVictoryConditionNine;
}
public void setIsVictoryCityWashingtonAxis(boolean isVictoryCityWashingtonAxisIn){
isVictoryCityWashingtonAxis = isVictoryCityWashingtonAxisIn;
}
public boolean getIsVictoryCityWashingtonAxis(){
return isVictoryCityWashingtonAxis;
}
public void setIsVictoryCityLondonAxis(boolean isVictoryCityLondonAxisIn){
isVictoryCityLondonAxis = isVictoryCityLondonAxisIn;
}
public boolean getIsVictoryCityLondonAxis(){
return isVictoryCityLondonAxis;
}
public void setIsVictoryCityLeningradAxis(boolean isVictoryCityLeningradAxisIn){
isVictoryCityLeningradAxis = isVictoryCityLeningradAxisIn;
}
public boolean getIsVictoryCityLeningradAxis(){
return isVictoryCityLeningradAxis;
}
public void setIsVictoryCityMoscowAxis(boolean isVictoryCityMoscowAxisIn){
isVictoryCityMoscowAxis = isVictoryCityMoscowAxisIn;
}
public boolean getIsVictoryCityMoscowAxis(){
return isVictoryCityMoscowAxis;
}
public void setIsVictoryCityCalcuttaAxis(boolean isVictoryCityCalcuttaAxisIn){
isVictoryCityCalcuttaAxis = isVictoryCityCalcuttaAxisIn;
}
public boolean getIsVictoryCityCalcuttaAxis(){
return isVictoryCityCalcuttaAxis;
}
public void setIsVictoryCityLosAngelesAxis(boolean isVictoryCityLosAngelesAxisIn){
isVictoryCityLosAngelesAxis = isVictoryCityLosAngelesAxisIn;
}
public boolean getIsVictoryCityLosAngelesAxis(){
return isVictoryCityLosAngelesAxis;
}
public void setIsVictoryCityBerlinAxis(boolean isVictoryCityBerlinAxisIn){
isVictoryCityBerlinAxis = isVictoryCityBerlinAxisIn;
}
public boolean getIsVictoryCityBerlinAxis(){
return isVictoryCityBerlinAxis;
}
public void setIsVictoryCityParisAxis(boolean isVictoryCityParisAxisIn){
isVictoryCityParisAxis = isVictoryCityParisAxisIn;
}
public boolean getIsVictoryCityParisAxis(){
return isVictoryCityParisAxis;
}
public void setIsVictoryCityRomeAxis(boolean isVictoryCityRomeAxisIn){
isVictoryCityRomeAxis = isVictoryCityRomeAxisIn;
}
public boolean getIsVictoryCityRomeAxis(){
return isVictoryCityRomeAxis;
}
public void setIsVictoryCityShanghaiAxis(boolean isVictoryCityShanghaiAxisIn){
isVictoryCityShanghaiAxis = isVictoryCityShanghaiAxisIn;
}
public boolean getIsVictoryCityShanghaiAxis(){
return isVictoryCityShanghaiAxis;
}
public void setIsVictoryCityManilaAxis(boolean isVictoryCityManilaAxisIn){
isVictoryCityManilaAxis = isVictoryCityManilaAxisIn;
}
public boolean getIsVictoryCityManilaAxis(){
return isVictoryCityManilaAxis;
}
public void setIsVictoryCityTokyoAxis(boolean isVictoryCityTokyoAxisIn){
isVictoryCityTokyoAxis = isVictoryCityTokyoAxisIn;
}
public boolean getIsVictoryCityTokyoAxis(){
return isVictoryCityTokyoAxis;
}
}
| true
|
ed0a0362d41d485158e506b20eb4f7f8b33aa821
|
Java
|
xeviff/balancer-service
|
/src/main/java/com/npaw/service/balancer/model/Account.java
|
ISO-8859-1
| 992
| 2.890625
| 3
|
[] |
no_license
|
package com.npaw.service.balancer.model;
import java.util.HashMap;
/**
* Clase de modelo para las cuentas de cliente
* @author Xavier
*
*/
public class Account {
//Los dispositivos que tiene asociados
private HashMap<String,DeviceConfiguration> devicesInfo;
public Account () {
devicesInfo = new HashMap<String, DeviceConfiguration>();
}
/**
* Aade un dispositivo asociado
* @param config
*/
public void addDeviceConfig (DeviceConfiguration config) {
devicesInfo.put(config.getName(), config);
}
/**
* Pasado por parmetro el nombre de un dispositivo, indica si lo tiene asociado
* @param deviceName
* @return
*/
public boolean hasDevice (String deviceName) {
return devicesInfo.containsKey(deviceName);
}
/**
* Devuelve la informacin de uno de sus dispositivos en un objeto de tipo DeviceConfiguration
* @param device
* @return
*/
public DeviceConfiguration getDeviceInfo (String device) {
return devicesInfo.get(device);
}
}
| true
|
9d33a5fa458ca764f03d478f5d2d5eacce2d3154
|
Java
|
HyalwW/CustomViewStuff
|
/app/src/main/java/com/example/customviewstuff/customs/eyes/Eye.java
|
UTF-8
| 1,696
| 2.796875
| 3
|
[] |
no_license
|
package com.example.customviewstuff.customs.eyes;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RadialGradient;
import android.graphics.Shader;
/**
* Created by Wang.Wenhui
* Date: 2020/5/25
* Description: blablabla
*/
public abstract class Eye {
protected float cx, cy, width, height, ballRadius;
protected Path drawPath;
private RadialGradient gradient;
Eye(float cx, float cy, float width, float height) {
this.cx = cx;
this.cy = cy;
this.width = width;
this.height = height;
ballRadius = width * 0.2f;
drawPath = new Path();
}
void drawRedBase(Canvas canvas, Paint paint) {
drawRedBase(canvas, paint, ballRadius);
}
void drawRedBase(Canvas canvas, Paint paint, float radius) {
if (gradient == null) {
gradient = new RadialGradient(cx, cy, radius, new int[]{Color.RED, 0xFF8B0000, Color.TRANSPARENT}, new float[]{0f, 0.95f, 1f}, Shader.TileMode.CLAMP);
}
paint.setShader(gradient);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setStrokeWidth(5f);
canvas.drawCircle(cx, cy, radius, paint);
paint.setShader(null);
}
void blackDot(Canvas canvas, Paint paint) {
blackDot(canvas, paint, ballRadius * 0.18f);
}
void blackDot(Canvas canvas, Paint paint, float radius) {
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(cx, cy, radius, paint);
}
public abstract void draw(Canvas canvas, Paint paint);
public abstract Eye next();
}
| true
|
16540fbe1cd5c17e47007021e575e4a1f1312107
|
Java
|
smartaid1980/STOutsource
|
/src/main/java/com/servtech/servcloud/app/controller/shengtai_pdf/ShengTaiPDFController.java
|
UTF-8
| 11,363
| 2.15625
| 2
|
[] |
no_license
|
package com.servtech.servcloud.app.controller.shengtai_pdf;
import com.servtech.servcloud.app.controller.iiot.IiotFileUploadController;
import com.servtech.servcloud.core.util.RequestResult;
import com.servtech.servcloud.core.util.SysPropKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.*;
/**
* controller
* Created by kevin on 2020/3/2.
*/
@RestController
@RequestMapping("shengtai/pdf")
public class ShengTaiPDFController {
@Autowired
private HttpServletResponse response;
private static final Logger log = LoggerFactory.getLogger(ShengTaiPDFController.class);
@RequestMapping(value = "upload", method = RequestMethod.POST)
public RequestResult<?> upload(@RequestParam("file") MultipartFile file) {
try {
String fileAllName = file.getOriginalFilename();
String fileName = fileAllName.substring(0, fileAllName.lastIndexOf("."));
String rawdataPath = System.getProperty(SysPropKey.DATA_PATH);
File saveFile = new File(rawdataPath + "\\pdf\\upload\\" + fileName + ".pdf");
file.transferTo(saveFile);
String statusEndPath = rawdataPath + "\\pdf\\status\\" + fileName + ".end";
File endFile = new File(statusEndPath);
if(endFile.exists()){
endFile.delete();
}
String statusStartPath = rawdataPath + "\\pdf\\status\\" + fileName + ".start";
File startFile = new File(statusStartPath);
if(startFile.exists()){
startFile.delete();
}
FileWriter writeStartFile = new FileWriter(new File(statusStartPath));
writeStartFile.close();
String timestampPath = rawdataPath + "\\pdf\\recordTimestamp\\" + fileName + "\\";
File timestampFolder = new File(timestampPath);
if (!timestampFolder.exists()) {
timestampFolder.mkdirs();
}
File[] timestamps = timestampFolder.listFiles();
if(timestamps != null && timestamps.length > 0){
for(File timestamp : timestamps){
timestamp.delete();
}
}
String recordTimestamp = timestampPath + fileName + "@@" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis())) + ".txt";
FileWriter write = new FileWriter(new File(recordTimestamp));
write.close();
String cmdStr = "cmd.exe /c start appendTextToPDF.exe " + fileName + ".pdf";
String filePath = rawdataPath.substring(0, rawdataPath.lastIndexOf("rawdata")) + "\\program\\AppendPDF";
log.info("filePaht : " + filePath);
Runtime.getRuntime().exec(cmdStr, null, new File(filePath));
return RequestResult.success(new DataImportCmd.ResponseData(0, "success"));
} catch (IOException e) {
e.printStackTrace();
return RequestResult.fail(new DataImportCmd.ResponseData(1, "IO Exception"));
}
}
@RequestMapping(value = "download", method = RequestMethod.GET)
public RequestResult<?> download(@RequestParam("fileName") String fileName, @RequestParam("language") String language) {
String filePath = System.getProperty(SysPropKey.DATA_PATH) + "/pdf/download/" + language + "/" + fileName + ".pdf";
log.info("filePath : " + filePath);
File file = new File(filePath);
String mimeType = "application/pdf";
String headerKey = "Content-Disposition";
String headerValue = "attachment; filename=\" " + fileName + ".pdf\"";
if (file.exists()) {
try {
FileInputStream in = new FileInputStream(file);
response.setContentType(mimeType);
response.setHeader(headerKey, headerValue);
ServletOutputStream out = response.getOutputStream();
byte[] bytes = new byte[1024];
int byteSize;
while ((byteSize = in.read(bytes)) != -1) {
out.write(bytes, 0, byteSize);
}
out.flush();
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return RequestResult.success();
}
@RequestMapping(value = "check_status", method = RequestMethod.GET)
public RequestResult<?> checkStatus() {
String statusPath = System.getProperty(SysPropKey.DATA_PATH) + "/pdf/status";
log.info("statusPath : " + statusPath);
File path = new File(statusPath);
List<String> complete = new ArrayList<>();
List<String> withoutEnd = new ArrayList<>();
Map<String, List<String>> result = new HashMap<>();
if (path.isDirectory()) {
File[] fileList = path.listFiles();
if (fileList == null || fileList.length == 0)
return RequestResult.success(result);
for (int i = 0; i < fileList.length; i++) {
String fileAllName = fileList[i].getName();
String fileName = fileAllName.substring(0, fileAllName.lastIndexOf("."));
String extension = fileAllName.substring(fileAllName.lastIndexOf(".") + 1, fileAllName.length());
if (extension.equals("end")) {
complete.add(fileName);
if (withoutEnd.contains(fileName)) {
withoutEnd.remove(fileName);
}
} else {
if (!complete.contains(fileName)) {
withoutEnd.add(fileName);
}
}
}
result.put("complete", addTimestamp(complete));
result.put("withoutEnd", addTimestamp(withoutEnd));
}
return RequestResult.success(result);
}
private List<String> addTimestamp(List<String> fileNameList) {
List<String> result = new ArrayList<>();
for(String fileName : fileNameList){
String timestampPath = System.getProperty(SysPropKey.DATA_PATH) + "\\pdf\\recordTimestamp\\" + fileName + "\\";
System.out.println("timestampPath : " +timestampPath);
File[] files = new File(timestampPath).listFiles();
System.out.println("files.length : " +files.length);
if(files != null && files.length > 0){
System.out.println("files[0].getName() : " + files[0].getName());
result.add(files[0].getName());
}
}
return result;
}
public static class DataImportCmd {
private String[] commands;
private String[] envp;
private File file;
private DataImportCmd(Builder builder) {
this.commands = builder.commands;
this.envp = builder.envp;
this.file = builder.file;
}
public static class Builder {
private String[] commands;
private String[] envp;
private File file;
public Builder setCommands(String[] commands) {
if (commands == null || commands.length == 0) {
throw new BuilderExection("commands is null or isEmpty");
}
this.commands = commands;
return this;
}
public Builder setEnvp(String[] envp) {
this.envp = envp;
return this;
}
public Builder setFile(File file) {
this.file = file;
return this;
}
public DataImportCmd build() {
return new DataImportCmd(this);
}
}
ResponseData runCmd() {
try {
ProcessBuilder pb = new ProcessBuilder(this.commands).directory(this.file).redirectErrorStream(true);
Process proc = pb.start();
ExecutorService executor = Executors.newCachedThreadPool();
Callable<ResponseData> task = new Message(proc.getInputStream());
Future<ResponseData> future = executor.submit(task);
proc.waitFor();
return future.get();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return null;
}
static class Message implements Callable<ResponseData> {
private InputStream is;
static final String SEP = System.getProperty("line.separator");
Message(InputStream is) {
this.is = is;
}
@Override
public ResponseData call() throws Exception {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
List<String> msgList = new ArrayList<String>();
String dataStr = "";
String line = "";
while ((line = br.readLine()) != null) {
if (line.indexOf("###") > -1) {
msgList.add(line.substring(line.indexOf("###") + 3));
} else if (line.indexOf("#DATA#") > -1) {
dataStr = line.substring(line.indexOf("#DATA#") + 6);
} else if (line.indexOf("@@@") > -1) {
System.out.println(line.substring(line.indexOf("@@@") + 6));
} else {
log.info("Process log : " + line);
}
}
log.info("msgList : " + msgList.toString());
log.info("dataStr : " + dataStr);
if (msgList.size() > 0) {
return new ResponseData(1, msgList);
} else {
return new ResponseData(0, dataStr);
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
static class ResponseData<T> {
int status;
int type;
T data;
ResponseData(int status, T data) {
this.status = status;
this.data = data;
}
}
static class BuilderExection extends RuntimeException {
public BuilderExection(String msg) {
super(msg);
}
}
}
}
| true
|
6d577e91e1f4bb9aa7018059f33bc3bdeb2bd87a
|
Java
|
Cong96/basic-skill
|
/algorithm/src/main/java/com.leetcode/string/ZconvertSolution.java
|
UTF-8
| 1,981
| 3.796875
| 4
|
[] |
no_license
|
package com.leetcode.string;
import java.util.ArrayList;
import java.util.List;
/**
* @ClassName ZconvertSolution
* @Description
* @Author BryantCong
* @Date 2020/2/1 21:17
* @Version V1.0
* 将一个给定字符串根据给定的行数,以从上往下、从左到右进行 Z 字形排列。
* <p>
* 比如输入字符串为 "LEETCODEISHIRING" 行数为 3 时,排列如下:
* <p>
* L C I R
* E T O E S I I G
* E D H N
* 之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"LCIRETOESIIGEDHN"。
* <p>
* 请你实现这个将字符串进行指定行数变换的函数:
* <p>
* string convert(string s, int numRows);
* 示例 1:
* <p>
* 输入: s = "LEETCODEISHIRING", numRows = 3
* 输出: "LCIRETOESIIGEDHN"
* 示例 2:
* <p>
* 输入: s = "LEETCODEISHIRING", numRows = 4
* 输出: "LDREOEIIECIHNTSG"
* 解释:
* <p>
* L D R
* E O E I I
* E C I H N
* T S G
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/zigzag-conversion
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
**/
public class ZconvertSolution {
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
List<StringBuilder> res = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
res.add(new StringBuilder());
}
int flag = -1;
int i = 0;
for (char c : s.toCharArray()) {
res.get(i).append(c);
if (numRows == 0 || numRows == numRows - 1) {
flag = -flag;
}
i += flag;
}
StringBuilder result = new StringBuilder();
for (StringBuilder row : res) {
result.append(row);
}
return res.toString();
}
}
| true
|
cb5ddab561e6f583c47b09be6c49a87d9d6073e8
|
Java
|
PaulVenter94/curs22-fighttournament
|
/src/main/java/org/fasttrackit/chuninexam/ChuninExamApplication.java
|
UTF-8
| 327
| 1.609375
| 2
|
[] |
no_license
|
package org.fasttrackit.chuninexam;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ChuninExamApplication {
public static void main(String[] args) {
SpringApplication.run(ChuninExamApplication.class, args);
}
}
| true
|
6fa4085938ee0b4be7c7fa75c587fed4e23a5cc9
|
Java
|
TaitonProject/TaitonBank
|
/src/main/java/com/taiton/jsonConverter/UserSerializer.java
|
UTF-8
| 1,004
| 2.0625
| 2
|
[] |
no_license
|
package com.taiton.jsonConverter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.taiton.entity.UserEntity;
import java.io.IOException;
/**
* Created by Taiton on 1/14/2017.
*/
public class UserSerializer extends JsonSerializer<UserEntity> {
@Override
public void serialize(UserEntity userEntity, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeStartObject();
jsonGenerator.writeNumberField("id", userEntity.getId());
jsonGenerator.writeStringField("username", userEntity.getUsername());
jsonGenerator.writeStringField("password", userEntity.getPassword());
jsonGenerator.writeObjectField("roleByRoleIdRole", userEntity.getRoleByRoleIdRole());
jsonGenerator.writeEndObject();
}
}
| true
|
ef5db6a5e862c8759a700b8eb3f07c958ef131ff
|
Java
|
Ernakh/AulaAtosUFNRestAPISpring
|
/src/main/java/com/fabriciolondero/AulaAtosUFNRestAPISpring/Models/Disciplina.java
|
UTF-8
| 751
| 2.34375
| 2
|
[] |
no_license
|
package com.fabriciolondero.AulaAtosUFNRestAPISpring.Models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Disciplina
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable=false)
private String nome;
@Column(nullable=false)
private int vagas;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getVagas() {
return vagas;
}
public void setVagas(int vagas) {
this.vagas = vagas;
}
}
| true
|
b7f8bcd3084e523080464924b306a1df5f20ab17
|
Java
|
khanhchi96/Ad_Team10_Mobile
|
/app/src/main/java/com/example/ad_team10/storeActivities/ViewDisbursementByDeptActivity.java
|
UTF-8
| 4,503
| 2.109375
| 2
|
[] |
no_license
|
//Author: Phung Khanh Chi
package com.example.ad_team10.storeActivities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.ad_team10.R;
import com.example.ad_team10.adapters.CustomDepartmentAdapter;
import com.example.ad_team10.clients.RestService;
import com.example.ad_team10.models.CustomDepartment;
import com.google.gson.Gson;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ViewDisbursementByDeptActivity extends AppCompatActivity {
private final int ON_UPDATE_RETURN = 1;
private final int ON_VIEW_RETURN = 0;
RestService restService;
ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_list);
restService = new RestService();
listView = findViewById(R.id.listView);
loadDepartment();
}
private void loadDepartment(){
final Call<List<CustomDepartment>> call = restService.getService().getDepartmentList();
call.enqueue(new Callback<List<CustomDepartment>>() {
@Override
public void onResponse(Call<List<CustomDepartment>> call, Response<List<CustomDepartment>> response) {
final List<CustomDepartment> departments = response.body();
final CustomDepartmentAdapter adapter = new CustomDepartmentAdapter(
ViewDisbursementByDeptActivity.this, R.layout.custom_department, departments);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
adapter.chosenId = position;
listView.invalidateViews();
Button btnView = view.findViewById(R.id.btnView);
btnView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Gson gson = new Gson();
String jsonDepartment = gson.toJson(departments.get(position));
goToDetailPage(jsonDepartment);
}
});
Button btnUpdate = view.findViewById(R.id.btnUpdate);
btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Gson gson = new Gson();
String jsonDepartment = gson.toJson(departments.get(position));
goToUpdatePage(jsonDepartment);
}
});
}
});
}
@Override
public void onFailure(Call<List<CustomDepartment>> call, Throwable t) {
Toast.makeText(getApplicationContext(), "onFailure called ", Toast.LENGTH_SHORT).show();
call.cancel();
}
});
}
private void goToDetailPage(String jsonDepartment){
Intent intent = new Intent(ViewDisbursementByDeptActivity.this, ViewDisbursementDetailActivity.class);
intent.putExtra("department", jsonDepartment);
startActivityForResult(intent, ON_VIEW_RETURN);
}
private void goToUpdatePage(String jsonDepartment){
Intent intent = new Intent(ViewDisbursementByDeptActivity.this, UpdateDisbursementDetailActivity.class);
intent.putExtra("department", jsonDepartment);
startActivityForResult(intent, ON_UPDATE_RETURN);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == ON_UPDATE_RETURN || requestCode == ON_VIEW_RETURN) {
if (resultCode == RESULT_OK) {
String jsonDepartment = intent.getStringExtra("department");
loadDepartment();
goToDetailPage(jsonDepartment);
}
}
}
}
| true
|
fcfe2dcf690c308cf339a70ed850da363c8b78c0
|
Java
|
nadia-mm/Java-WeatherAPI
|
/src/main/java/com/nadia/weather/configuration/WeatherDBConfiguration.java
|
UTF-8
| 2,607
| 2.109375
| 2
|
[] |
no_license
|
package com.nadia.weather.configuration;
import com.nadia.weather.repository.weather.WeatherProviderRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackageClasses = WeatherProviderRepository.class,
entityManagerFactoryRef = "weatherDSFactory", transactionManagerRef = "weatherDSTransactionManager")
public class WeatherDBConfiguration {
@Autowired
private Environment env;
@Primary
@Bean
@ConfigurationProperties(prefix = "spring.datasource.db2")
public DataSourceProperties weatherDSProperties() {
return new DataSourceProperties();
}
@Primary
@Bean
public DataSource weatherDS() {
return weatherDSProperties().initializeDataSourceBuilder().build();
}
@Primary
@Bean
public LocalContainerEntityManagerFactoryBean weatherDSFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(weatherDS());
factory.setPackagesToScan(new String[]{
"com.nadia.weather.entity.weather"
});
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
factory.setJpaProperties(jpaProperties);
return factory;
}
@Primary
@Bean
public PlatformTransactionManager weatherDSTransactionManager() {
EntityManagerFactory factory = weatherDSFactory().getObject();
return new JpaTransactionManager(factory);
}
}
| true
|
e5004790f8058b017f253a223ea946a6934f8b2c
|
Java
|
kamalkumar1729/data-structures
|
/src/main/java/first/java/collection/Maps.java
|
UTF-8
| 1,284
| 3.71875
| 4
|
[] |
no_license
|
package first.java.collection;
import java.util.*;
public class Maps {
public static void main(String[] args) {
Map<String,Student> map = new HashMap<>();
Student student1 = new Student("AA",null,12);
Student student2 = new Student("BB",102,13);
Student student3 = new Student("CC",13,14);
Student student4 = new Student("DD",104,14);
Student student5 = new Student("EE",null,14);
// System.out.println(student1.hashCode());
// System.out.println(student2.hashCode());
// System.out.println(student3.hashCode());
// System.out.println("Hello");
// student3=student2;
// System.out.println(student1.hashCode());
// System.out.println(student2.hashCode());
// System.out.println(student3.hashCode());
List<Student> list = new ArrayList<>();
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
list.add(student5);
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return 0;
}
});
list.forEach(student -> System.out.println(student.toString()));
}
}
| true
|
f7a57ab425db7dfc02f8586f7997cc968e40633a
|
Java
|
nexodrone/algo3-2013-2c-tp2
|
/src/modelo/Vehiculo.java
|
UTF-8
| 3,589
| 2.734375
| 3
|
[] |
no_license
|
package modelo;
import modelo.excepciones.CalleBloqueadaPorPiqueteExcepcion;
import org.simpleframework.xml.Attribute;
import org.simpleframework.xml.Element;
import control.Logger;
public abstract class Vehiculo {
@Element(name = "posicionActual")
private Posicion posicion;
@Attribute
private int cantidadDeMovimientos;
private Direccion direccion;
public Vehiculo(Posicion nuevaPosicion) {
posicion = nuevaPosicion;
this.cantidadDeMovimientos = 0;
}
public Vehiculo() {
}
public Posicion getPosicion() {
return this.posicion;
}
public int getCantidadDeMovimientos() {
return this.cantidadDeMovimientos;
}
public abstract String asString();
public void moverEnDireccion(Direccion unaDireccion, Calle calleAPasar) throws CalleBloqueadaPorPiqueteExcepcion {
direccion = unaDireccion;
pasarPorCalle(calleAPasar);
this.setPosicion(this.calcularSiguientePosicion());
}
public Posicion calcularSiguientePosicion() {
if (direccion != null) {
return this.calcularSiguientePosicion(direccion);
}
return posicion;
}
public void sumarMovimientos(int movimientos) {
this.cantidadDeMovimientos = this.cantidadDeMovimientos + movimientos;
}
public void aplicarPorcentajeAMovimientos(int porcentaje) {
float movimientosResultantes = this.cantidadDeMovimientos + (float) this.cantidadDeMovimientos * porcentaje / 100;
this.cantidadDeMovimientos = Math.round(movimientosResultantes);
}
public boolean tienenElMismoEstado(Vehiculo vehiculo) {
boolean cantidad = (cantidadDeMovimientos == vehiculo.getCantidadDeMovimientos());
boolean posicionesIguales = posicion.equals(vehiculo.getPosicion());
return (cantidad && posicionesIguales);
}
public void setCantidadDeMovimientos(int cantidad) {
cantidadDeMovimientos = cantidad;
}
public Direccion getDireccion() {
return direccion;
}
public void setPosicion(Posicion unaPosicion) {
posicion = unaPosicion;
}
public Posicion calcularSiguientePosicion(Direccion unaDireccion) {
Posicion nuevaPosicion = this.posicion.copy();
/* System.out.println("calcularSiguientePosicion");
System.out.println("Posicion actual" + posicion.asString());
System.out.println("Direccion" + unaDireccion.x() + "," + unaDireccion.y());*/
nuevaPosicion.incrementarY(unaDireccion.y());
nuevaPosicion.incrementarX(unaDireccion.x());
/*System.out.println("Nueva posicion" + nuevaPosicion.asString());*/
return nuevaPosicion;
}
public void pasarPorCalle(Calle calleAPasar) {
Obstaculo obstaculo = calleAPasar.getObstaculo();
if (obstaculo != null) {
Logger.instance.log("Obstaculo:");
this.aplicarEvento(obstaculo);
};
Sorpresa sorpresa = calleAPasar.getSorpresa();
if (sorpresa != null) {
Logger.instance.log("Sorpresa:");
this.aplicarEvento(sorpresa);
calleAPasar.setSorpresa(null);
};
this.sumarMovimientos(1);
}
public abstract void aplicarEvento(EventoColicion evento);
// public void guardar(String path) throws Exception {
// Serializer serializador = new Persister();
// File resultado = new File(path);
// serializador.write(this, resultado);
// }
}
| true
|
652736707b5f21d1ee5f26b8344b56ebcbf5a3ec
|
Java
|
cvetan/bookstore
|
/src/BookstoreWEB/src/main/java/com/github/cvetan/bookstore/mb/category/CategoryListMB.java
|
UTF-8
| 2,936
| 2.15625
| 2
|
[] |
no_license
|
package com.github.cvetan.bookstore.mb.category;
import com.github.cvetan.bookstore.model.Category;
import com.github.cvetan.bookstore.sb.configuration.ConfigurationSBLocal;
import com.github.cvetan.bookstore.util.Redirector;
import com.github.cvetan.bookstore.util.ResourceBundleLoader;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.inject.Named;
import org.omnifaces.cdi.ViewScoped;
/**
*
* @author cvetan
*/
@Named(value = "categoryListMB")
@ViewScoped
public class CategoryListMB extends CategoryMB implements Serializable {
@EJB
private ConfigurationSBLocal configurationSB;
private int paginationLimit;
private boolean selected;
private Category selectedCategory;
/**
* Creates a new instance of CategoryListMB
*/
public CategoryListMB() {
}
public ConfigurationSBLocal getConfigurationSB() {
return configurationSB;
}
public void setConfigurationSB(ConfigurationSBLocal configurationSB) {
this.configurationSB = configurationSB;
}
public int getPaginationLimit() {
return paginationLimit;
}
public void setPaginationLimit(int paginationLimit) {
this.paginationLimit = paginationLimit;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public Category getSelectedCategory() {
return selectedCategory;
}
public void setSelectedCategory(Category selectedCategory) {
this.selectedCategory = selectedCategory;
}
@PostConstruct
public void initPage() {
getData();
paginationLimit = Integer.parseInt(configurationSB.getItem("backendPaginationLimit"));
}
public void onRowSelect() {
selected = true;
}
public void onRowUnselect() {
selected = false;
}
public String openCreateForm() {
return "/admin/category-form?faces-redirect=true";
}
public String openEditForm() {
return "/admin/category-form?faces-redirect=true&id=" + selectedCategory.getId();
}
public String delete() {
try {
categorySB.delete(selectedCategory.getId());
selected = false;
rawList.remove(selectedCategory);
formatedList.remove(selectedCategory);
String message = ResourceBundleLoader.loadFromClass("messages", "categoryDeleted");
return Redirector.redirectWithMessage(message, FacesMessage.SEVERITY_INFO, "/admin/category-list?faces-redirect=true");
} catch (Exception ex) {
return Redirector.redirectWithMessage(ex.getMessage(), FacesMessage.SEVERITY_ERROR, "/admin/category-list?faces-redirect=true");
}
}
}
| true
|
10b0e6739bf716446b5ebfc5efce0e62a380dbe0
|
Java
|
mberezuieva/Study
|
/Study/src/com/course/onseo/Vector.java
|
UTF-8
| 1,605
| 3.625
| 4
|
[] |
no_license
|
package com.course.onseo;
public class Vector {
private double x;
private double y;
private double z;
Vector (double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
//System.out.println("Thank you for the input");
}
// finding vector length
public double vectorLength () {
return Math.sqrt (x*x + y*y + z*z);
}
// finding scalar produce of 2 vectors
public double scalarProduct (Vector vector) {
return (x*vector.x + y*vector.y + z*vector.z);
}
// finding vector produce of 2 vectors
public Vector vectorProduct (Vector vector) {
return new Vector
((y*vector.z - z*vector.y),
(z*vector.x - x*vector.z),
(x*vector.y - y*vector.x));
}
// finding corner between 2 vectors
public double vectorCorner (Vector vector) {
return scalarProduct(vector) / ( vectorLength() * vector.vectorLength() );
}
// finding vectors sum
public Vector add (Vector vector) {
return new Vector
((x + vector.x),
(y + vector.y),
(z + vector.z));
}
// finding vector difference
public Vector subtract (Vector vector) {
return new Vector((x - vector.x), (y - vector.y), (z - vector.z));
}
public static Vector [] Generator (int N) {
Vector [] vectors = new Vector[N];
for (int i = 0; i < N; i++) {
vectors[i] = new Vector (Math.random(), Math.random(), Math.random());
}
return vectors;
}
}
| true
|
d0cf8e35a118a423e9887e1425253db048628933
|
Java
|
pavanhp001/Spring-boot-proct
|
/Spring-proctice/src/SCenter/viper-client-api/src/main/java/com/allconnect/viper/service/auth/AuthenticationService.java
|
UTF-8
| 1,188
| 2.1875
| 2
|
[] |
no_license
|
package com.A.V.service.auth;
import java.util.Calendar;
import com.A.V.domain.User;
import com.A.V.gateway.jms.UAMClientJMS;
import com.A.vo.UserAuthorization;
public enum AuthenticationService {
INSTANCE;
private static final String END_POINT_NAME = "endpoint.uam.in";
public UserAuthorization authenticate(String userid, String password){
UAMClientJMS jmsClient = new UAMClientJMS();
password = java.util.regex.Matcher.quoteReplacement(password);
userid = java.util.regex.Matcher.quoteReplacement(userid);
String template = jmsClient.getAuthenticateRequest(userid, password);
UserAuthorization userAuthorization = jmsClient.send("jms", END_POINT_NAME, template);
return userAuthorization;
}
public User getUser(final String loginId) {
User user = new User();
user.setName("");
user.setLoginId(loginId);
user.setEnabled(Boolean.TRUE);
user.setDateEffectiveFrom(Calendar.getInstance());
user.setDateEffectiveTo(Calendar.getInstance());
user.setId(System.currentTimeMillis());
user.setLastLoginAt(Calendar.getInstance());
user.setLoginAttempt(1);
return user;
}
}
| true
|
f5bc1e6d69145b4c0ef59f1c7d644eb47c5eb711
|
Java
|
MrNocTV/Algorithms
|
/SolvedProblems/HackerRank/src/EvenTree.java
|
UTF-8
| 2,037
| 3.8125
| 4
|
[
"MIT"
] |
permissive
|
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
/**
*
* @author Loc Truong Van
* @category Algorithm
* @site HackerRank
* @link https://www.hackerrank.com/challenges/even-tree/problem
* @idea While inserting edges, count the children of a node, then check how
* many subtrees have even number of nodes, and minus one (tree with 2
* nodes does not need to be cut)
*
*/
public class EvenTree {
private class Node {
int data;
int numNode;
List<Node> children;
Node parent;
Node(int data) {
this.data = data;
numNode = 1;
children = new ArrayList<>();
}
@Override
public String toString() {
return String.valueOf(data);
}
}
Map<Integer, Node> tree;
boolean[] visited;
public EvenTree(int n) {
tree = new HashMap<>();
for (int i = 1; i <= n; ++i)
tree.put(i, new Node(i));
visited = new boolean[n + 1];
Arrays.fill(visited, false);
visited[1] = true;
}
public void insert(int u, int v) {
if (visited[u]) {
Node parent = tree.get(u);
Node child = tree.get(v);
child.parent = parent;
parent.children.add(child);
while (parent != null) {
parent.numNode += 1;
parent = parent.parent;
}
visited[v] = true;
} else if (visited[v]) {
Node parent = tree.get(v);
Node child = tree.get(u);
child.parent = parent;
parent.children.add(child);
while (parent != null) {
parent.numNode += 1;
parent = parent.parent;
}
visited[u] = true;
}
}
public long countCut() {
return tree.values().stream().filter(node -> node.numNode % 2 == 0).count() - 1;
}
@SuppressWarnings("resource")
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int m = input.nextInt();
EvenTree et = new EvenTree(n);
for (int i = 1; i <= m; ++i) {
int u = input.nextInt();
int v = input.nextInt();
et.insert(u, v);
}
System.out.println(et.countCut());
}
}
| true
|
befde3294c0aa564db56fdd07448fcdacbedb3f4
|
Java
|
cuba-platform/reports
|
/modules/core/src/com/haulmont/reports/role/ReportsMinimalRoleDefinition.java
|
UTF-8
| 3,009
| 1.65625
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (c) 2008-2020 Haulmont.
*
* 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.haulmont.reports.role;
import com.haulmont.cuba.security.app.role.AnnotatedRoleDefinition;
import com.haulmont.cuba.security.app.role.annotation.EntityAccess;
import com.haulmont.cuba.security.app.role.annotation.EntityAttributeAccess;
import com.haulmont.cuba.security.app.role.annotation.Role;
import com.haulmont.cuba.security.app.role.annotation.ScreenAccess;
import com.haulmont.cuba.security.entity.EntityOp;
import com.haulmont.cuba.security.role.EntityAttributePermissionsContainer;
import com.haulmont.cuba.security.role.EntityPermissionsContainer;
import com.haulmont.cuba.security.role.ScreenPermissionsContainer;
import com.haulmont.reports.entity.Report;
import com.haulmont.reports.entity.ReportGroup;
import com.haulmont.reports.entity.ReportTemplate;
/**
* System role that grants minimal permissions for run reports required for all users of generic UI client.
*/
@Role(name = ReportsMinimalRoleDefinition.ROLE_NAME)
public class ReportsMinimalRoleDefinition extends AnnotatedRoleDefinition {
public static final String ROLE_NAME = "system-reports-minimal";
@Override
@ScreenAccess(screenIds = {
"report$inputParameters",
"report$Report.run",
"report$showReportTable",
"report$showPivotTable",
"report$showChart",
"commonLookup"
})
public ScreenPermissionsContainer screenPermissions() {
return super.screenPermissions();
}
@Override
@EntityAccess(entityClass = Report.class, operations = {EntityOp.READ})
@EntityAccess(entityClass = ReportGroup.class, operations = {EntityOp.READ})
@EntityAccess(entityClass = ReportTemplate.class, operations = {EntityOp.READ})
public EntityPermissionsContainer entityPermissions() {
return super.entityPermissions();
}
@Override
@EntityAttributeAccess(entityClass = Report.class, view = {"locName", "description", "code", "updateTs", "group"})
@EntityAttributeAccess(entityClass = ReportGroup.class, view = {"title", "localeNames"})
@EntityAttributeAccess(entityClass = ReportTemplate.class, view = {"code","name","customDefinition","custom","alterable"})
public EntityAttributePermissionsContainer entityAttributePermissions() {
return super.entityAttributePermissions();
}
@Override
public String getLocName() {
return "Reports Minimal";
}
}
| true
|
102981aa08f841fc65fbf38e5a2c0131005c925a
|
Java
|
sparrowflyer/jishu
|
/src/main/java/com/wanmoxing/jishu/util/CellphoneUtil.java
|
UTF-8
| 1,791
| 2.03125
| 2
|
[] |
no_license
|
package com.wanmoxing.jishu.util;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
public class CellphoneUtil {
private static final String accessKeyID = "LTAIk9Yduza9gtuL";
private static final String accessKeySecret = "Cq7To1isupCapKfxfXcWtS8UVKXcNF";
private static final String signName = "叽叔";
private static final String templateCode= "SMS_163525386";
public static CommonResponse sendSms(String phoneNumber, String random) {
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyID, accessKeySecret);
IAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
//request.setProtocol(ProtocolType.HTTPS);
request.setMethod(MethodType.POST);
request.setDomain("dysmsapi.aliyuncs.com");
request.setVersion("2017-05-25");
request.setAction("SendSms");
request.putQueryParameter("RegionId", "cn-hangzhou");
request.putQueryParameter("PhoneNumbers", phoneNumber);
request.putQueryParameter("SignName", signName);
request.putQueryParameter("TemplateCode", templateCode);
request.putQueryParameter("TemplateParam", "{\"code\":\"" + random + "\"}");
CommonResponse response = new CommonResponse();
try {
response = client.getCommonResponse(request);
} catch (ServerException e) {
e.printStackTrace();
} catch (ClientException e) {
e.printStackTrace();
}
return response;
}
}
| true
|
5e6520dce4d4a86705d62e1b4a3b6471e189a449
|
Java
|
pieczatek/mtg-search
|
/app/src/main/java/com/icyjars/mtgcards/Service/MtgioService.java
|
UTF-8
| 578
| 2.046875
| 2
|
[] |
no_license
|
package com.icyjars.mtgcards.Service;
import com.icyjars.mtgcards.Model.Mtgio;
import com.icyjars.mtgcards.Model.MtgioSingleCard;
import java.util.Map;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.QueryMap;
public interface MtgioService {
String SERVICE_ENDPOINT = "https://api.magicthegathering.io";
@GET("/v1/cards")
Call<Mtgio> getCards(@QueryMap Map<String, String> parameters);
@GET("/v1/cards/{multiverseid}")
Call<MtgioSingleCard> getSingleCard(@Path("multiverseid") int multiverseid);
}
| true
|
084b6ae5b78d94dc96a66a80baf77ba0c12323e2
|
Java
|
piskorzm/PseudoCube
|
/app/src/main/java/com/example/pseudoqube/MainActivity.java
|
UTF-8
| 1,163
| 2.28125
| 2
|
[] |
no_license
|
package com.example.pseudoqube;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import com.example.pseudoqube.views.PseudoCube;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
PseudoCube cube = new PseudoCube(this);
Button sort = findViewById(R.id.sort);
Button randomize = findViewById(R.id.randomize);
sort.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PseudoCube tempCube = findViewById(R.id.cube);
tempCube.init(null);
}
});
randomize.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PseudoCube tempCube = findViewById(R.id.cube);
tempCube.randomize();
}
});
}
}
| true
|
0a3ad75b5358ec052281d32c5e8f89532a59f575
|
Java
|
ammarbarafwala/cs3220
|
/Homework01/src/cs3220/servlet/homework01/CreateFolder.java
|
UTF-8
| 3,158
| 2.6875
| 3
|
[] |
no_license
|
package cs3220.servlet.homework01;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletContext;
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 cs3220.servlet.homework01.model.Folder;
/**
* Servlet implementation class CreateFolder
*/
@WebServlet("/CreateFolder")
public class CreateFolder extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String errorMessage=request.getParameter("errorMessage")==null?"":"<br>"+request.getParameter("errorMessage")+"<br>";
PrintWriter out=response.getWriter();
out.print("<html>"
+ "<head><title></title></head>"
+ "<body>"
+ "<form method='post' action='CreateFolder'>"
+ "New Folder: <input type='text' name='name'/> ");
if(request.getParameter("currentName")!=null)
out.print( "<input type='hidden' name='currentName' value='"+request.getParameter("currentName")+""+"'>");
out.print( errorMessage
+ "<input type='hidden' name='parentId' value='"+request.getParameter("parentId")+"'>"
+ "<input type='submit' value='Create'/>"
+ "</form>"
+ "</body>"
+ "</html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext sc=getServletContext();
Map<Integer,Map<String,Folder>> map=(Map<Integer, Map<String, Folder>>) sc.getAttribute("homework01.map");
int parentId=Integer.parseInt(request.getParameter("parentId"));
String currentName=request.getParameter("currentName");
int id=(int) sc.getAttribute("homework01.id");
int currentId=0;
Folder current=null;
String path="",path2="parentId="+parentId+"&&";
if(currentName!=null){
current=map.get(parentId).get(currentName);
currentId=current.getId();
path="?currentName="+currentName.replaceAll(" ", "%20")+"&&parentId="+parentId;
path2="currentName="+currentName.replaceAll(" ", "%20")+"&&"+path2;
}
String name=request.getParameter("name").trim();
//Checking if name entered is empty
if(name.isEmpty())
response.sendRedirect("CreateFolder?"+path2+"errorMessage=Name field cannot be empty.");
//checking if folder with same name exists
else if(map.get(currentId)!=null && map.get(currentId).containsKey(name))
response.sendRedirect("CreateFolder?"+path2+"errorMessage=A folder with this name already exists.");
//create folder with the name inserted and map it to its parent
else{
if(map.containsKey(currentId))
map.get(currentId).put(name, new Folder(++id, name, current));
else{
Map<String, Folder> tempMap=new HashMap<>();
tempMap.put(name, new Folder(++id, name, current));
map.put(currentId, tempMap);
}
sc.setAttribute("homework01.id",id);
response.sendRedirect("OnlineFileManager"+path);
}
}
}
| true
|
0fb1cbd8e00a1176712a54bce69ebc042ee1aa27
|
Java
|
eamv-hi/foobot
|
/foobot.ejbClient/ejbModule/foobot/ejb/domain/Batch.java
|
UTF-8
| 1,252
| 2.21875
| 2
|
[] |
no_license
|
package foobot.ejb.domain;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
public class Batch implements Serializable {
private static final long serialVersionUID = 1L;
private String uuid;
private LocalDateTime start;
private LocalDateTime end;
private String compatibility;
private List<Measurement> measurements = new ArrayList<>();
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public LocalDateTime getStart() {
return start;
}
public void setStart(LocalDateTime start) {
this.start = start;
}
public LocalDateTime getEnd() {
return end;
}
public void setEnd(LocalDateTime end) {
this.end = end;
}
public String getCompatibility() {
return compatibility;
}
public void setCompatibility(String compatibility) {
this.compatibility = compatibility;
}
public List<Measurement> getMeasurements() {
return measurements;
}
@Override
public String toString() {
return "Batch [uuid=" + uuid + ", start=" + start + ", end=" + end + ", compatibility=" + compatibility
+ ", measurements=" + measurements + "]";
}
}
| true
|
bcb2fbfb206c0e92ee0378f78df82fd696a067b5
|
Java
|
NRolfe/Cornucopia
|
/src/edu/clarkson/catalfmr/ee363/project3/Main.java
|
UTF-8
| 1,028
| 2.84375
| 3
|
[] |
no_license
|
package edu.clarkson.catalfmr.ee363.project3;
import java.util.Random;
import edu.clarkson.rolfens.ee363.cornucopia.decorators.Carrot;
import edu.clarkson.rolfens.ee363.cornucopia.decorators.Produce;
import edu.clarkson.rolfens.ee363.cornucopia.decorators.Vegetable;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Producer farm = new Producer();
Supplier sysco = new Supplier();
Consumer resturant = new Consumer();
farm.addObserver(sysco);
sysco.addObserver(resturant);
farm.grow();
System.out.println("Supplier Inv:" + sysco.inventory.size());
Random buy = new Random();
int toBuy = buy.nextInt(2) + 0;
if (toBuy == 1) {
farm.notifyObservers(farm.bananaInventory);
} else {
farm.notifyObservers(farm.carrotInventory);
}
System.out.println("Supplier Inv:" + sysco.inventory.size());
System.out.println("Product Available: "
+ resturant.getProductAvailable().get(0).getName());
System.out.println("---End transaction----");
}
}
| true
|
23eaabbbf98c7b72fa7470c5d8efe50db8126136
|
Java
|
TimelyD/Timely-master
|
/easeui/src/com/hyphenate/easeui/widget/EaseContactList.java
|
UTF-8
| 6,281
| 2.078125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.hyphenate.easeui.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hyphenate.easeui.R;
import com.hyphenate.easeui.adapter.EaseContactAdapter;
import com.hyphenate.easeui.domain.EaseUser;
import java.util.ArrayList;
import java.util.List;
public class EaseContactList extends RelativeLayout {
protected static final String TAG = EaseContactList.class.getSimpleName();
protected Context context;
protected ListView listView;
protected EaseContactAdapter adapter;
protected List<EaseUser> contactList;
protected EaseSidebar sidebar;
protected int primaryColor;
protected int primarySize;
protected boolean showSiderBar;
protected Drawable initialLetterBg;
static final int MSG_UPDATE_LIST = 0;
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_LIST:
if (adapter != null) {
adapter.clear();
adapter.addAll(new ArrayList<EaseUser>(contactList));
adapter.notifyDataSetChanged();
mContactNumTv.setText(String.format(getContext().getString(R.string.num_of_contact),
contactList.size()));
}
break;
default:
break;
}
super.handleMessage(msg);
}
};
protected int initialLetterColor;
private TextView mContactNumTv;
public EaseContactList(Context context) {
super(context);
init(context, null);
}
public EaseContactList(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public EaseContactList(Context context, AttributeSet attrs, int defStyle) {
this(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
this.context = context;
TypedArray ta = context.obtainStyledAttributes(attrs, com.hyphenate.easeui.R.styleable.EaseContactList);
primaryColor = ta.getColor(com.hyphenate.easeui.R.styleable.EaseContactList_ctsListPrimaryTextColor, 0);
primarySize = ta.getDimensionPixelSize(com.hyphenate.easeui.R.styleable
.EaseContactList_ctsListPrimaryTextSize, 0);
showSiderBar = ta.getBoolean(com.hyphenate.easeui.R.styleable.EaseContactList_ctsListShowSiderBar, true);
initialLetterBg = ta.getDrawable(com.hyphenate.easeui.R.styleable.EaseContactList_ctsListInitialLetterBg);
initialLetterColor = ta.getColor(com.hyphenate.easeui.R.styleable.EaseContactList_ctsListInitialLetterColor, 0);
ta.recycle();
LayoutInflater.from(context).inflate(com.hyphenate.easeui.R.layout.ease_widget_contact_list, this);
listView = (ListView) findViewById(com.hyphenate.easeui.R.id.list);
sidebar = (EaseSidebar) findViewById(com.hyphenate.easeui.R.id.sidebar);
if (!showSiderBar)
sidebar.setVisibility(View.GONE);
}
/*
* init view
*/
public void init(List<EaseUser> contactList) {
this.contactList = contactList;
adapter = new EaseContactAdapter(context, 0, new ArrayList<EaseUser>(contactList));
adapter.setPrimaryColor(primaryColor).setPrimarySize(primarySize).setInitialLetterBg(initialLetterBg)
.setInitialLetterColor(initialLetterColor);
adapter.setEaseContactListHelper(mEaseContactListHelper);
listView.setAdapter(adapter);
/*mContactNumTv = new TextView(context);
int padding = (int) (5 * context.getResources().getDisplayMetrics().density + 0.5f);
//使用viewgroup模拟器api_19报错
mContactNumTv.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
.LayoutParams.WRAP_CONTENT));
mContactNumTv.setPadding(padding, padding, padding, padding);
mContactNumTv.setGravity(Gravity.CENTER);
mContactNumTv.setText(String.format(getContext().getString(R.string.num_of_contact), contactList.size()));
listView.addFooterView(mContactNumTv);
mContactNumTv.setOnClickListener(null)*/
View footer = LayoutInflater.from(context).inflate(R.layout.footer_contact_list, null);
mContactNumTv = (TextView)footer.findViewById(R.id.tv_num);
mContactNumTv.setText(String.format(getContext().getString(R.string.num_of_contact), contactList.size()));
listView.addFooterView(footer);
//避免长按弹出contextmenu引起bug
footer.setOnClickListener(null);
if (showSiderBar) {
sidebar.setListView(listView);
}
}
public void refresh() {
Message msg = handler.obtainMessage(MSG_UPDATE_LIST);
handler.sendMessage(msg);
}
public void filter(CharSequence str) {
adapter.getFilter().filter(str);
}
public ListView getListView() {
return listView;
}
public void setShowSiderBar(boolean showSiderBar) {
if (showSiderBar) {
sidebar.setVisibility(View.VISIBLE);
} else {
sidebar.setVisibility(View.GONE);
}
}
private EaseContactListHelper mEaseContactListHelper;
public interface EaseContactListHelper {
/**
* 设置该用户是否有设置加密
* @param username
* @param msgClock
* @param avatar
* @param nameView
*/
void onSetIsMsgClock(String username, ImageView msgClock, ImageView avatar, TextView nameView);
}
public void setEaseContactListHelper(EaseContactListHelper easeContactListHelper) {
this.mEaseContactListHelper = easeContactListHelper;
}
}
| true
|
c4a01148882c36e5c53e8b19c46ab6df6fb4baff
|
Java
|
Vinniefern99/Java3
|
/Assignment_1/src/Modules/InsertIntoArrayMain.java
|
UTF-8
| 3,216
| 3.359375
| 3
|
[] |
no_license
|
package Modules;
//Main file for iTunes project - insertion example.
//CS 1C, Foothill_Main1 College, Michael Loceff, creator
import cs_1c.*;
import java.util.*;
import java.text.*;
//------------------------------------------------------
public class InsertIntoArrayMain
{
// ------- main --------------
public static void main(String[] args) throws Exception
{
// to time the algorithm -------------------------
long startTime, stopTime;
NumberFormat tidy = NumberFormat.getInstance(Locale.US);
tidy.setMaximumFractionDigits(4);
// how we read the data from files
iTunesEntryReader tunesInput = new iTunesEntryReader("itunes_file.txt");
int arraySize;
// how we test the success of the read:
if (tunesInput.readError())
{
System.out.println("couldn't open " + tunesInput.getFileName()
+ " for input.");
return;
}
// create an array of objects for our own use:
arraySize = tunesInput.getNumTunes();
// we add 1 to make room for an insertion
iTunesEntry[] tunesArray = new iTunesEntry[arraySize + 1];
for (int k = 0; k < arraySize; k++)
tunesArray[k] = tunesInput.getTune(k);
// 5 positions we will "insert at" in the larger iTunes list of 80 tunes
int writePosition;
final int NUM_INSERTIONS = 500;
int[] somePositions = {3, 67, 20, 15, 59 };
int numPositions = somePositions.length;
System.out.println("Doing " + NUM_INSERTIONS + " insertions in array having "
+ arraySize + " iTunes." );
//get start time
startTime = System.nanoTime();
// we will do NUM_INSERTIONS insertions, throwing away tunes that run off the top
for (int attempt = 0; attempt < NUM_INSERTIONS; attempt++)
{
writePosition = somePositions[ attempt % numPositions ];
// move everything up one
for (int k = arraySize; k > writePosition; k--)
tunesArray[k] = tunesArray[k-1];
// now put a new tune into the free position
tunesArray[writePosition].setArtist("Amerie");
tunesArray[writePosition].setTitle("Outro");
tunesArray[writePosition].setTime(63);
}
// how we determine the time elapsed -------------------
stopTime = System.nanoTime();
// report algorithm time
System.out.println("\nAlgorithm Elapsed Time: "
+ tidy.format((stopTime - startTime) / 1e9)
+ " seconds.\n");
}
}
/* ---------------- Runs -------------------
Doing 5000000 insertions in array having 79 iTunes.
Algorithm Elapsed Time: 0.2352 seconds.
---------
Doing 500000 insertions in array having 79 iTunes.
Algorithm Elapsed Time: 0.0327 seconds.
---------
Doing 50000 insertions in array having 79 iTunes.
Algorithm Elapsed Time: 0.0125 seconds.
---------
Doing 5000 insertions in array having 79 iTunes.
Algorithm Elapsed Time: 0.0072 seconds.
---------
Doing 500 insertions in array having 79 iTunes.
Algorithm Elapsed Time: 0.0007 seconds.
---------
Doing 50 insertions in array having 79 iTunes.
Algorithm Elapsed Time: 0.0001 seconds.
---------------------------------------- */
| true
|
b8dcb78b1e26e3d0bb7652a2f5219f583bec9946
|
Java
|
GodofMunch/Algorithms-and-Data-Structures
|
/Lab 5/src/Person.java
|
UTF-8
| 1,642
| 3.21875
| 3
|
[] |
no_license
|
import java.text.SimpleDateFormat;
import java.util.Date;
public class Person implements Comparable<Person> {
private String forename;
private String surname;
private Date dob;
public String getForename() {
return forename;
}
public String getSurname() {
return surname;
}
public Date getDob() {
return this.dob;
}
public void setForename(String forename) {
this.forename = forename;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Person(String forename, String surname, Date dob) {
this.forename = forename;
this.surname = surname;
this.dob = dob;
}
public Person() {
setForename("");
setSurname("");
setDob(new Date());
}
public int compareTo(Person other) {
/*if(surname.compareTo(other.surname)== 0)
return forename.compareTo(other.forename);
else if(surname.compareTo(other.surname)==0 &&
forename.compareTo(other.forename)==0) {
if(dob.compareTo(other.dob) > 0)
return other.dob.compareTo(dob);
else
return dob.compareTo(other.dob);
}
else
return surname.compareTo(other.surname);*/
return forename.compareTo(other.forename);
}
public String toString() {
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
return "\nName : " + forename + " " + surname + ", Date of Birth : " + sdf.format(dob);
}
}
| true
|
e08d459350158369d5db334e0e997f148fbb5fe3
|
Java
|
kimsc93/ssafy_algo_lecture
|
/algo_lecture/src/day9/BattleField.java
|
UTF-8
| 3,255
| 3.15625
| 3
|
[] |
no_license
|
package day01;
import java.io.InputStream;
import java.util.Scanner;
public class BattleField {
public static void main(String[] args) {
InputStream input = BattleField.class.getResourceAsStream("input.txt");
System.setIn(input);
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int tc=1;tc<T;tc++) {
int H = sc.nextInt();
int W = sc.nextInt();
char[][] map = new char[H][W];
int curI=0;
int curJ=0;
char curDir='>';
for(int i=0;i<H;i++) {
String strW = sc.next();
map[i] = strW.toCharArray();
}
int instructLength = sc.nextInt();
String instruct = sc.next();
char[] instCh = new char[instructLength];
for(int i=0;i<instructLength;i++) {
instCh[i] = instruct.charAt(i);
}
for(int i=0;i<H;i++) {
for(int j=0;j<W;j++) {
if(map[i][j]=='^'||map[i][j]=='<'||map[i][j]=='>'||map[i][j]=='v') {
curI=i;
curJ=j;
curDir=map[i][j];
}
}
}
for(int i=0;i<instructLength;i++) {
switch(instCh[i]) {
case 'U':
curDir='^';
map[curI][curJ] = '^';
if(curI-1>=0 && map[curI-1][curJ]!='-' && map[curI-1][curJ]=='.') {
map[curI][curJ] = '.';
curI-=1;
map[curI][curJ] = '^';
}
break;
case 'D':
curDir='v';
map[curI][curJ] = 'v';
if(curI+1<H && map[curI+1][curJ]!='-' && map[curI+1][curJ]=='.') {
map[curI][curJ] = '.';
curI+=1;
map[curI][curJ] = 'v';
}
break;
case 'L':
curDir='<';
map[curI][curJ] = '<';
if(curJ-1>=0 && map[curI][curJ-1]!='-' && map[curI][curJ-1]=='.') {
map[curI][curJ] = '.';
curJ-=1;
map[curI][curJ] = '<';
}
break;
case 'R':
curDir='>';
map[curI][curJ] = '>';
if(curJ+1<W && map[curI][curJ+1]!='-'&& map[curI][curJ+1]=='.') {
map[curI][curJ] = '.';
curJ+=1;
map[curI][curJ] = '>';
}
break;
case 'S':
shoot(map,curI,curJ,curDir);
break;
}
}
System.out.print("#"+tc+" ");
for(int i=0;i<H;i++) {
for(int j=0;j<W;j++) {
System.out.print(map[i][j]);
}
System.out.println();
}
}
}
public static void shoot(char[][] map,int curI,int curJ,char curDir) {
switch(curDir){
case '>':
while(true) {
curJ++;
if(curJ>map[0].length-1) break;
else if(map[curI][curJ]=='*') {
map[curI][curJ]='.';
break;
}
else if(map[curI][curJ]=='#') break;
}
break;
case '<':
while(true) {
curJ--;
if(curJ<0) break;
else if(map[curI][curJ]=='*') {
map[curI][curJ]='.';
break;
}
else if(map[curI][curJ]=='#') break;
}
break;
case '^':
while(true) {
curI--;
if(curI<0) break;
else if(map[curI][curJ]=='*') {
map[curI][curJ]='.';
break;
}
else if(map[curI][curJ]=='#') break;
}
break;
case 'v':
while(true) {
curI++;
if(curI>map.length-1) break;
else if(map[curI][curJ]=='*') {
map[curI][curJ]='.';
break;
}
else if(map[curI][curJ]=='#') break;
}
break;
}
}
}
| true
|
abcdc35ad237fd407d5cda9ad133fadda7a3aae5
|
Java
|
lpeano/WebWorkLoadd
|
/src/com/workload/PatternSpecs.java
|
UTF-8
| 2,296
| 2.765625
| 3
|
[] |
no_license
|
package com.workload;
import java.util.HashMap;
import java.util.Map;
public class PatternSpecs {
private double Elapsed;
private String PatternName;
/**
* @return the elapsed
*/
private Map<String,String> PatternVariable;
public PatternSpecs(String PatternName,double Elapsed) {
this.Elapsed=Elapsed;
this.PatternName=PatternName;
}
public PatternSpecs(Builder builder) {
// TODO Auto-generated constructor stub
this.PatternName=builder.getPatternName();
this.Elapsed=builder.getElapsed();
this.PatternVariable=builder.PatternVariable;
}
public double getElapsed() {
return Elapsed;
}
/**
* @param elapsed the elapsed to set
*/
public void setElapsed(double elapsed) {
Elapsed = elapsed;
}
/**
* @return the patternName
*/
public String getPatternName() {
return PatternName;
}
/**
* @param patternName the patternName to set
*/
public void setPatternName(String patternName) {
PatternName = patternName;
}
/**
* @return the patternVariable
*/
public Map<String,String> getPatternVariable() {
return PatternVariable;
}
/**
* @param patternVariable the patternVariable to set
*/
public void setPatternVariable(Map<String,String> patternVariable) {
PatternVariable = patternVariable;
}
public static class Builder {
private double Elapsed;
private String PatternName;
public Map<String,String> PatternVariable=new HashMap<String,String>();
public PatternSpecs build() {
PatternSpecs patternSpecs=new PatternSpecs(this);
return patternSpecs;
}
/**
* @return the elapsed
*/
public double getElapsed() {
return Elapsed;
}
/**
* @param elapsed the elapsed to set
*/
public Builder setElapsed(double elapsed) {
Elapsed = elapsed;
return this;
}
/**
* @return the patternName
*/
public String getPatternName() {
return PatternName;
}
/**
* @param patternName the patternName to set
*/
public Builder setPatternName(String patternName) {
this.PatternName = patternName;
return this;
}
public Builder setPatternVariable(String Name,String Value) {
this.PatternVariable.put(Name, Value);
return this;
}
}
}
| true
|
e44716379cd86f674f82d0dbf7b190d4f72ea1e6
|
Java
|
aucd29/nvapp
|
/libhsp-permission/src/main/java/com/hanwha/libhsp_permission/RxPermissionResult.java
|
UTF-8
| 828
| 1.71875
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* Copyright (C) Hanwha Systems Corp. 2018. All rights reserved.
*
* This software is covered by the license agreement between
* the end user and Hanwha Systems Corp. and may be
* used and copied only in accordance with the terms of the
* said agreement.
*
* Hanwha Systems Corp. assumes no responsibility or
* liability for any errors or inaccuracies in this software,
* or any consequential, incidental or indirect damage arising
* out of the use of the software.
*/
package com.hanwha.libhsp_permission;
/**
* Created by <a href="mailto:aucd29@hanwha.com">Burke Choi</a> on 2018. 5. 31.. <p/>
*/
public final class RxPermissionResult {
public final int code;
public final boolean result;
public RxPermissionResult(int code, boolean result) {
this.code = code;
this.result = result;
}
}
| true
|
8470fb139245ed3342c28732290f99122ee2817c
|
Java
|
xinglonglu/Spring-Authorization
|
/src/main/java/com/lxl/config/MainController.java
|
UTF-8
| 636
| 1.96875
| 2
|
[] |
no_license
|
package com.lxl.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lxl.authorization.manager.TokenManager;
@Controller
public class MainController {
@Autowired
private TokenManager manager;
@RequestMapping("/")
@ResponseBody
public String home() {
System.out.println("666666666666666");
long userId =123l;
manager.deleteToken(userId);
return "Hello World!";
}
}
| true
|
48bfc054ba19be1a44e4df789ca7f05dbd9a3cd8
|
Java
|
CTAJlb/project-PDA-Selenide
|
/src/test/java/ru/st/selenium/test/testPda/DocumentsTest.java
|
UTF-8
| 5,746
| 1.921875
| 2
|
[] |
no_license
|
package ru.st.selenium.test.testPda;
import com.codeborne.selenide.testng.TextReport;
import ru.st.selenium.model.Administration.Directories.Directories;
import ru.st.selenium.model.DocflowAdministration.DictionaryEditor.DictionaryEditor;
import ru.st.selenium.model.DocflowAdministration.DocumentRegistrationCards.*;
import ru.st.selenium.pages.Page;
import ru.st.selenium.pages.pagespda.DocumentsPagePDA;
import ru.st.selenium.pages.pagespda.InternalPagePDA;
import ru.st.selenium.pages.pagespda.LoginPagePDA;
import ru.st.selenium.pages.pagesweb.Administration.DirectoriesEditFormPage;
import ru.st.selenium.pages.pagesweb.Administration.TaskTypeListObjectPage;
import ru.st.selenium.pages.pagesweb.DocflowAdministration.DictionaryEditorPage;
import ru.st.selenium.pages.pagesweb.DocflowAdministration.FormDocRegisterCardsEditPage;
import ru.st.selenium.pages.pagesweb.DocflowAdministration.GridDocRegisterCardsPage;
import ru.st.selenium.pages.pagesweb.Internal.InternalPage;
import ru.st.selenium.pages.pagesweb.Login.LoginPage;
import ru.st.selenium.test.data.ModuleDocflowAdministrationObjectTestCase;
import ru.st.selenium.test.data.Retry;
import ru.st.selenium.test.listeners.ScreenShotOnFailListener;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
import static com.codeborne.selenide.Selenide.open;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertTrue;
/**
* Раздел - Документы
*/
@Listeners({ScreenShotOnFailListener.class, TextReport.class})
public class DocumentsTest extends ModuleDocflowAdministrationObjectTestCase {
/**
* Проверка создания документа и отображение его в гриде
*
* @param directories
* @param dictionaryEditor
* @param registerCards
* @throws Exception TODO 1. retryAnalyzer = Retry.class - добавить параметр в аннотацию тест; 2.Создание Документа и проверка созданного документа в гриде PDA
*/
@Test(priority = 1, dataProvider = "objectDataDocument")
public void createRegCardDocumentAllFields(Directories directories, DictionaryEditor dictionaryEditor, DocRegisterCards registerCards) throws Exception {
LoginPage loginPage = open(Page.WEB_PAGE_URL, LoginPage.class);
loginPage.loginAs(ADMIN);
InternalPage internalPage = loginPage.initializedInsidePage(); // Инициализируем внутренюю стр. системы и переходим на нее
assertThat("Check that the displayed menu item 8 (Logo; Tasks; Documents; Messages; Calendar; Library; Tools; Details)",
internalPage.hasMenuUserComplete()); // Проверяем отображение п.м. на внутренней странице
// Переход в раздел Администрирование/Справочники
TaskTypeListObjectPage directoriesPageWeb = internalPage.gotoDirectories();
// добавляем объект - Справочник
directoriesPageWeb.addDirectories(directories);
// переходим в форму редактирования Справочника
DirectoriesEditFormPage directoriesEditPage = internalPage.gotoDirectoriesEditPage();
// Добавляем настройки И поля спр-ка
directoriesEditPage.addFieldDirectories(directories);
// Переход в раздел - Администрирование ДО/Редактор словарей
DictionaryEditorPage dictionaryEditorPage = internalPage.goToDictionaryEditor();
dictionaryEditorPage.addDictionaryEditor(dictionaryEditor);
// Переход в раздел Администрирование ДО/Регистрационные карточки документов
GridDocRegisterCardsPage gridDocRegisterCardsPage = internalPage.goToGridDocRegisterCards();
// Добавление РКД с проинициализированными объектами
FormDocRegisterCardsEditPage formDocRegisterCardsEditPage = gridDocRegisterCardsPage.addDocRegisterCards();
// Добавление полей РКД
formDocRegisterCardsEditPage.addFieldsDocRegisterCards(registerCards);
// Добавление настроек РКД
formDocRegisterCardsEditPage.addSettingsDocRegisterCards(registerCards);
// Сохранение настроек РКД
formDocRegisterCardsEditPage.saveAllChangesInDoc(registerCards);
internalPage.logout(); // Выход из системы
assertTrue(loginPage.isNotLoggedIn());
}
/**
* проверка - Отображение грида документа
*/
@Test(priority = 2, retryAnalyzer = Retry.class)
public void checkMapGridOfDocuments() throws Exception {
LoginPagePDA loginPagePDA = open(Page.PDA_PAGE_URL, LoginPagePDA.class);
// Авторизация
loginPagePDA.loginAsAdmin(ADMIN);
InternalPagePDA internalPagePDA = loginPagePDA.goToInternalMenu(); // Инициализируем внутренюю стр. системы и переходим на нее
assertThat("Check that the displayed menu item 4 (Tasks; Create Task; Today; Document)",
internalPagePDA.hasMenuUserComplete());
DocumentsPagePDA documentsPagePDA = internalPagePDA.goToDocuments();
documentsPagePDA.checkMapGridsDocuments();
internalPagePDA.logout(); // Выход из системы
assertTrue(loginPagePDA.isNotLoggedInPDA());
}
}
| true
|
ca4a1e43c33ad1594141d05b164c9c0b39511dbe
|
Java
|
kksb0831/javaStudy
|
/src/my/day08/b/DOWHILE/FactorialMain2.java
|
UTF-8
| 1,266
| 3.8125
| 4
|
[] |
no_license
|
package my.day08.b.DOWHILE;
import java.util.Scanner;
public class FactorialMain2 {
public static void main(String[] args) {
// === 입사문제 ===
/*
>> 알고 싶은 팩토리얼 수 입력 => 5 Enter
>> 5! = 120
// 5 * 4 * 3 * 2 * 1
*/
Scanner sc = new Scanner(System.in);
do {
try {
System.out.print(">> 알고 싶은 팩토리얼 수 입력 => ");
int num = Integer.parseInt(sc.nextLine());
if (num <= 0){
System.out.println(">> 자연수를 입력하세요!! <<");
continue;
}
int result = 1;
String str = "";
for (int i = num; i > 0; i--) {
result *= i;
str += (i > 1)? i + "*": i + "=";
}
System.out.println(num+"! = " + str + result);
break;
} catch (NumberFormatException e) {
System.out.println(">> 자연수를 입력하세요!! <<");
}
} while (true);
sc.close();
System.out.println("\n~~~~ 프로그램 종료!! ~~~~");
}
}
| true
|
67902d39684030b66767a2fcc62feb8ace6713ba
|
Java
|
daveogle85/planit-food-api
|
/rest-api/src/test/java/com/planitfood/typeConverters/QuantitiesTypeConverterTests.java
|
UTF-8
| 3,180
| 2.890625
| 3
|
[] |
no_license
|
package com.planitfood.typeConverters;
import com.planitfood.enums.Unit;
import com.planitfood.models.Dish;
import com.planitfood.models.Ingredient;
import com.planitfood.models.Quantity;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class QuantitiesTypeConverterTests {
@Test
public void convertsIngredientsToQuantities() throws Exception {
Ingredient i1 = new Ingredient("1", "test 1");
Ingredient i2 = new Ingredient("2", "test 2");
Quantity q1 = new Quantity(12.1, Unit.UNIT);
Quantity q2 = new Quantity(2, Unit.G);
i1.setQuantity(12.1);
i2.setQuantity(2);
i2.setUnit(Unit.G);
ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>(Arrays.asList(i1, i2));
Dish dish = new Dish("1");
dish.setIngredients(ingredients);
dish = QuantitiesTypeConverter.convertIngredientsToQuantities(dish);
Assertions.assertNotNull(dish.getQuantities());
Assertions.assertEquals(q1, dish.getQuantities().get("1"));
Assertions.assertEquals(q2, dish.getQuantities().get("2"));
}
@Test
public void convertsQuantitiesToIngredients() throws Exception {
Quantity q1 = new Quantity(12.1, Unit.UNIT);
Quantity q2 = new Quantity(2, Unit.G);
Ingredient i1 = new Ingredient("1", "test 1");
Ingredient i2 = new Ingredient("2", "test 2");
Ingredient i3 = new Ingredient("3", "test 3");
Dish dish = new Dish("1");
HashMap<String, Quantity> quants = new HashMap<>();
quants.put("1", q1);
quants.put("2", q2);
dish.setQuantities(quants);
dish.setIngredients(new ArrayList<>(Arrays.asList(i1, i2, i3)));
dish = QuantitiesTypeConverter.convertQuantitiesToIngredients(dish);
Assertions.assertEquals(q1.getQuantity(), dish.getIngredients().get(0).getQuantity());
Assertions.assertEquals(q1.getUnit(), dish.getIngredients().get(0).getUnit());
Assertions.assertEquals(q2.getQuantity(), dish.getIngredients().get(1).getQuantity());
Assertions.assertEquals(q2.getUnit(), dish.getIngredients().get(1).getUnit());
Assertions.assertNull(dish.getIngredients().get(2).getQuantity());
}
@Test
public void convertQuantitiesToString() throws Exception {
QuantitiesTypeConverter qtc = new QuantitiesTypeConverter();
HashMap<String, Quantity> test = new HashMap<>();
test.put("1", new Quantity(10, Unit.CUP));
Map result = qtc.convert(test);
Assertions.assertEquals("{\"quantity\":10.0,\"unit\":\"CUP\"}", result.get("1"));
}
@Test
public void convertStringToQuantites() throws Exception {
QuantitiesTypeConverter qtc = new QuantitiesTypeConverter();
HashMap<String, String> test = new HashMap<>();
test.put("1", "{\"quantity\":10.0,\"unit\":\"CUP\"}");
Quantity expected = new Quantity(10, Unit.CUP);
Map result = qtc.unconvert(test);
Assertions.assertEquals(expected, result.get("1"));
}
}
| true
|
957c7a007dbeeb7ea60e95c9ea8090a7a34a7183
|
Java
|
smmckee22/cucumber-java-toy
|
/src/main/java/org/maxwu/jrefresh/greenHook/GreenHook.java
|
UTF-8
| 250
| 1.90625
| 2
|
[
"MIT"
] |
permissive
|
package org.maxwu.jrefresh.greenHook;
import java.lang.annotation.*;
/**
* Created by maxwu on 1/17/17.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface GreenHook {
public String value() default "";
}
| true
|
e64f3181e11aab07906e18a84b53f6685e974ac4
|
Java
|
TencentCloud/tencentcloud-sdk-java-intl-en
|
/src/main/java/com/tencentcloudapi/tdmq/v20200217/TdmqErrorCode.java
|
UTF-8
| 12,141
| 2.265625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.tencentcloudapi.tdmq.v20200217;
public enum TdmqErrorCode {
// CAM authentication failed.
AUTHFAILURE_UNAUTHORIZEDOPERATION("AuthFailure.UnauthorizedOperation"),
// Operation failed.
FAILEDOPERATION("FailedOperation"),
// An exception occurred while calling the transaction service.
FAILEDOPERATION_CALLTRADE("FailedOperation.CallTrade"),
// CMQ backend error.
FAILEDOPERATION_CMQBACKENDERROR("FailedOperation.CmqBackendError"),
// Failed to create the cluster.
FAILEDOPERATION_CREATECLUSTER("FailedOperation.CreateCluster"),
// Failed to create the environment.
FAILEDOPERATION_CREATEENVIRONMENT("FailedOperation.CreateEnvironment"),
// Failed to create the environment role.
FAILEDOPERATION_CREATEENVIRONMENTROLE("FailedOperation.CreateEnvironmentRole"),
// Failed to create the namespace.
FAILEDOPERATION_CREATENAMESPACE("FailedOperation.CreateNamespace"),
// An error occurred while creating the producer.
FAILEDOPERATION_CREATEPRODUCERERROR("FailedOperation.CreateProducerError"),
// An error occurred while creating the TDMQ client.
FAILEDOPERATION_CREATEPULSARCLIENTERROR("FailedOperation.CreatePulsarClientError"),
// Failed to create the role.
FAILEDOPERATION_CREATEROLE("FailedOperation.CreateRole"),
// Failed to create the key.
FAILEDOPERATION_CREATESECRETKEY("FailedOperation.CreateSecretKey"),
// Failed to create the subscription.
FAILEDOPERATION_CREATESUBSCRIPTION("FailedOperation.CreateSubscription"),
// Failed to create the topic.
FAILEDOPERATION_CREATETOPIC("FailedOperation.CreateTopic"),
// Failed to delete the cluster.
FAILEDOPERATION_DELETECLUSTER("FailedOperation.DeleteCluster"),
// Failed to delete the environment role.
FAILEDOPERATION_DELETEENVIRONMENTROLES("FailedOperation.DeleteEnvironmentRoles"),
// Failed to delete the environment.
FAILEDOPERATION_DELETEENVIRONMENTS("FailedOperation.DeleteEnvironments"),
// Failed to delete the namespace.
FAILEDOPERATION_DELETENAMESPACE("FailedOperation.DeleteNamespace"),
// Failed to delete the role.
FAILEDOPERATION_DELETEROLES("FailedOperation.DeleteRoles"),
// Failed to delete the subscription.
FAILEDOPERATION_DELETESUBSCRIPTIONS("FailedOperation.DeleteSubscriptions"),
// Failed to delete the topic.
FAILEDOPERATION_DELETETOPICS("FailedOperation.DeleteTopics"),
// Failed to query the subscription data.
FAILEDOPERATION_DESCRIBESUBSCRIPTION("FailedOperation.DescribeSubscription"),
// Failed to get the environment attributes.
FAILEDOPERATION_GETENVIRONMENTATTRIBUTESFAILED("FailedOperation.GetEnvironmentAttributesFailed"),
// Failed to get the number of topic partitions.
FAILEDOPERATION_GETTOPICPARTITIONSFAILED("FailedOperation.GetTopicPartitionsFailed"),
// This instance is not ready. Please try again later.
FAILEDOPERATION_INSTANCENOTREADY("FailedOperation.InstanceNotReady"),
// The message size exceeds the upper limit of 1 MB.
FAILEDOPERATION_MAXMESSAGESIZEERROR("FailedOperation.MaxMessageSizeError"),
// The uploaded `msgID` is incorrect.
FAILEDOPERATION_MESSAGEIDERROR("FailedOperation.MessageIDError"),
// You must clear the associated namespace before proceeding.
FAILEDOPERATION_NAMESPACEINUSE("FailedOperation.NamespaceInUse"),
// An error occurred while receiving the message.
FAILEDOPERATION_RECEIVEERROR("FailedOperation.ReceiveError"),
// Message receiving timed out. Please try again.
FAILEDOPERATION_RECEIVETIMEOUT("FailedOperation.ReceiveTimeout"),
// Failed to configure message rewind.
FAILEDOPERATION_RESETMSGSUBOFFSETBYTIMESTAMPFAILED("FailedOperation.ResetMsgSubOffsetByTimestampFailed"),
// You must clear the associated role data before proceeding.
FAILEDOPERATION_ROLEINUSE("FailedOperation.RoleInUse"),
// Failed to save the key.
FAILEDOPERATION_SAVESECRETKEY("FailedOperation.SaveSecretKey"),
// Message sending timed out.
FAILEDOPERATION_SENDMESSAGETIMEOUTERROR("FailedOperation.SendMessageTimeoutError"),
// Failed to send the message.
FAILEDOPERATION_SENDMSGFAILED("FailedOperation.SendMsgFailed"),
// Failed to set the message retention policy.
FAILEDOPERATION_SETRETENTIONPOLICY("FailedOperation.SetRetentionPolicy"),
// Failed to configure the message TTL.
FAILEDOPERATION_SETTTL("FailedOperation.SetTTL"),
// You must clear the associated topic data before proceeding.
FAILEDOPERATION_TOPICINUSE("FailedOperation.TopicInUse"),
// Please use a partition topic.
FAILEDOPERATION_TOPICTYPEERROR("FailedOperation.TopicTypeError"),
// Failed to update the environment.
FAILEDOPERATION_UPDATEENVIRONMENT("FailedOperation.UpdateEnvironment"),
// Failed to update the environment role.
FAILEDOPERATION_UPDATEENVIRONMENTROLE("FailedOperation.UpdateEnvironmentRole"),
// Failed to update the role.
FAILEDOPERATION_UPDATEROLE("FailedOperation.UpdateRole"),
// Failed to update the topic.
FAILEDOPERATION_UPDATETOPIC("FailedOperation.UpdateTopic"),
// You must clear the associated VPC routing data before proceeding.
FAILEDOPERATION_VPCINUSE("FailedOperation.VpcInUse"),
// Internal error.
INTERNALERROR("InternalError"),
// The broker service is exceptional.
INTERNALERROR_BROKERSERVICE("InternalError.BrokerService"),
// Failed to get attributes.
INTERNALERROR_GETATTRIBUTESFAILED("InternalError.GetAttributesFailed"),
// Internal error.
INTERNALERROR_ILLEGALMESSAGE("InternalError.IllegalMessage"),
// You can try again.
INTERNALERROR_RETRY("InternalError.Retry"),
// System error.
INTERNALERROR_SYSTEMERROR("InternalError.SystemError"),
// Incorrect parameter.
INVALIDPARAMETER("InvalidParameter"),
// Invalid management API address
INVALIDPARAMETER_INVALIDADMINURL("InvalidParameter.InvalidAdminUrl"),
// Incorrect partition count.
INVALIDPARAMETER_PARTITION("InvalidParameter.Partition"),
// The uploaded tenant name is incorrect.
INVALIDPARAMETER_TENANTNOTFOUND("InvalidParameter.TenantNotFound"),
// The correct token was not obtained.
INVALIDPARAMETER_TOKENNOTFOUND("InvalidParameter.TokenNotFound"),
// The parameter value is incorrect.
INVALIDPARAMETERVALUE("InvalidParameterValue"),
//
INVALIDPARAMETERVALUE_ATLEASTONE("InvalidParameterValue.AtLeastOne"),
// The cluster name already exists.
INVALIDPARAMETERVALUE_CLUSTERNAMEDUPLICATION("InvalidParameterValue.ClusterNameDuplication"),
// The parameter value is out of the value range.
INVALIDPARAMETERVALUE_INVALIDPARAMS("InvalidParameterValue.InvalidParams"),
// A required parameter is missing.
INVALIDPARAMETERVALUE_NEEDMOREPARAMS("InvalidParameterValue.NeedMoreParams"),
// The message TTL value is invalid.
INVALIDPARAMETERVALUE_TTL("InvalidParameterValue.TTL"),
// The uploaded topic name is incorrect.
INVALIDPARAMETERVALUE_TOPICNOTFOUND("InvalidParameterValue.TopicNotFound"),
// The quota limit is exceeded.
LIMITEXCEEDED("LimitExceeded"),
// The number of clusters under the instance exceeds the limit.
LIMITEXCEEDED_CLUSTERS("LimitExceeded.Clusters"),
// The number of environments under the instance exceeds the limit.
LIMITEXCEEDED_ENVIRONMENTS("LimitExceeded.Environments"),
// The number of namespaces under the instance exceeds the limit.
LIMITEXCEEDED_NAMESPACES("LimitExceeded.Namespaces"),
// The remaining quota has been exceeded. Please enter a valid value.
LIMITEXCEEDED_RETENTIONSIZE("LimitExceeded.RetentionSize"),
// The message retention period limit has been exceeded. Please enter a valid value.
LIMITEXCEEDED_RETENTIONTIME("LimitExceeded.RetentionTime"),
// The number of subscribers under the instance exceeds the limit.
LIMITEXCEEDED_SUBSCRIPTIONS("LimitExceeded.Subscriptions"),
// The number of topics under the instance exceeds the limit.
LIMITEXCEEDED_TOPICS("LimitExceeded.Topics"),
// Missing parameter.
MISSINGPARAMETER("MissingParameter"),
// A required parameter is missing.
MISSINGPARAMETER_NEEDMOREPARAMS("MissingParameter.NeedMoreParams"),
// Messages in the subscribed topic are being consumed.
OPERATIONDENIED_CONSUMERRUNNING("OperationDenied.ConsumerRunning"),
// Operations on the default environment are not allowed.
OPERATIONDENIED_DEFAULTENVIRONMENT("OperationDenied.DefaultEnvironment"),
// The resource is in use.
RESOURCEINUSE("ResourceInUse"),
// The cluster already exists.
RESOURCEINUSE_CLUSTER("ResourceInUse.Cluster"),
// The environment role already exists.
RESOURCEINUSE_ENVIRONMENTROLE("ResourceInUse.EnvironmentRole"),
// A namespace with the same name already exists.
RESOURCEINUSE_NAMESPACE("ResourceInUse.Namespace"),
// The queue already exists.
RESOURCEINUSE_QUEUE("ResourceInUse.Queue"),
// The role already exists.
RESOURCEINUSE_ROLE("ResourceInUse.Role"),
// A subscription with the same name already exists.
RESOURCEINUSE_SUBSCRIPTION("ResourceInUse.Subscription"),
// A topic with the same name already exists.
RESOURCEINUSE_TOPIC("ResourceInUse.Topic"),
// Insufficient resource.
RESOURCEINSUFFICIENT("ResourceInsufficient"),
// The resource does not exist.
RESOURCENOTFOUND("ResourceNotFound"),
// The service cluster does not exist.
RESOURCENOTFOUND_BROKERCLUSTER("ResourceNotFound.BrokerCluster"),
// The cluster does not exist.
RESOURCENOTFOUND_CLUSTER("ResourceNotFound.Cluster"),
// The environment does not exist.
RESOURCENOTFOUND_ENVIRONMENT("ResourceNotFound.Environment"),
// The environment role does not exist.
RESOURCENOTFOUND_ENVIRONMENTROLE("ResourceNotFound.EnvironmentRole"),
// The instance doesn’t exist.
RESOURCENOTFOUND_INSTANCE("ResourceNotFound.Instance"),
// The namespace does not exist.
RESOURCENOTFOUND_NAMESPACE("ResourceNotFound.Namespace"),
// The role does not exist.
RESOURCENOTFOUND_ROLE("ResourceNotFound.Role"),
// The subscription does not exist.
RESOURCENOTFOUND_SUBSCRIPTION("ResourceNotFound.Subscription"),
// The topic does not exist.
RESOURCENOTFOUND_TOPIC("ResourceNotFound.Topic"),
// The resource is unavailable.
RESOURCEUNAVAILABLE("ResourceUnavailable"),
// Assignment exception.
RESOURCEUNAVAILABLE_CREATEFAILED("ResourceUnavailable.CreateFailed"),
// You must top up before proceeding.
RESOURCEUNAVAILABLE_FUNDREQUIRED("ResourceUnavailable.FundRequired"),
// The system is being upgraded.
RESOURCEUNAVAILABLE_SYSTEMUPGRADE("ResourceUnavailable.SystemUpgrade"),
// The resources have been sold out.
RESOURCESSOLDOUT("ResourcesSoldOut"),
// Unauthorized operation.
UNAUTHORIZEDOPERATION("UnauthorizedOperation"),
// Unknown parameter error.
UNKNOWNPARAMETER("UnknownParameter"),
// Unsupported operation.
UNSUPPORTEDOPERATION("UnsupportedOperation"),
// The instance does not support configuration downgrade.
UNSUPPORTEDOPERATION_INSTANCEDOWNGRADE("UnsupportedOperation.InstanceDowngrade");
private String value;
private TdmqErrorCode (String value){
this.value = value;
}
/**
* @return errorcode value
*/
public String getValue() {
return value;
}
}
| true
|
8607c3a79f8f8b0a8e3d32beff5925cb2d8961e6
|
Java
|
TimaPaps/test_21_century
|
/src/main/java/ru/ptv/test21century/controllers/OrdersController.java
|
UTF-8
| 2,570
| 2.328125
| 2
|
[] |
no_license
|
package ru.ptv.test21century.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import ru.ptv.test21century.models.Orders;
import ru.ptv.test21century.repositoryes.OrderRepository;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;
/**
* 26.05.2021 12:39
* test_21_century
*
* @author Papsuev Timofey
* @version v1.0
*/
@RestController
public class OrdersController implements ApplicationRunner {
/**
*
*/
private final OrderRepository orderRepository;
@Autowired
public OrdersController(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
@PostMapping("/orders")
public Orders add(@RequestBody Orders orders) {
orderRepository.save(orders);
return orders;
}
public Orders update(@RequestBody Orders orders) {
Orders ordersInDb = orderRepository.getById(orders.getId());
ordersInDb.setClient(orders.getClient());
ordersInDb.setDate(Timestamp.valueOf(LocalDateTime.now()));
ordersInDb.setAddress(orders.getAddress());
orderRepository.save(ordersInDb);
return ordersInDb;
}
public Long delete(Orders orders) {
orderRepository.delete(orders);
return orders.getId();
}
@GetMapping("/orders")
public List<Orders> findAll() {
return orderRepository.findAll();
}
public Orders findById(Long id) {
return orderRepository.getById(id);
}
@Override
public void run(ApplicationArguments args) throws Exception {
long count = orderRepository.count();
if (count == 0) {
Orders order1 = Orders.builder()
.client("Иванов Иван Иванович")
.date(Timestamp.valueOf(LocalDateTime.now()))
.address("г.Первый, ул.Вторая, д.3")
.build();
Orders order2 = Orders.builder()
.client("Петров Петр Петрович")
.date(Timestamp.valueOf(LocalDateTime.now()))
.address("г.Второй, ул.Третья, д.4")
.build();
add(order1);
add(order2);
}
}
}
| true
|
9035491374f89407b2635ff00f5d91b9de7b1dbb
|
Java
|
GIIRRII/myHackerRankSolutions
|
/30 Days of Code/Day 12 - Inheritance/Solution.java
|
UTF-8
| 1,417
| 3.5625
| 4
|
[] |
no_license
|
class Student extends Person{
private int[] testScores;
/*
* Class Constructor
*
* @param firstName - A string denoting the Person's first name.
* @param lastName - A string denoting the Person's last name.
* @param id - An integer denoting the Person's ID number.
* @param scores - An array of integers denoting the Person's test scores.
*/
public Student(String firstName, String lastName, int id, int score [])
{
super(firstName, lastName, id);
this.firstName = firstName;
this.lastName = lastName;
this.idNumber = id;
this.testScores = score;
}
/*
* Method Name: calculate
* @return A character denoting the grade.
*/
public char calculate()
{
int i=0, sum=0, avg =0;
for(int s : testScores)
{ i++;
sum+=s;
}
avg = sum/i;
if(avg>=90&&avg<=100)
return 'O';
else
if(avg>=80&&avg<90)
return 'E';
else
if(avg>=70&&avg<80)
return 'A';
else
if(avg>=55&&avg<70)
return 'P';
else
if(avg>=40&&avg<55)
return 'D';
else
return 'T';
}
}
| true
|
ce766ebbec4e3e6ffe0ab34ef7c0c2b4355a05ee
|
Java
|
satasoy6/Selenium
|
/src/com/syntax/class07/SimpleWindowHandle.java
|
UTF-8
| 1,573
| 3.296875
| 3
|
[] |
no_license
|
package com.syntax.class07;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import com.syntax.utils.drivers;
public class SimpleWindowHandle extends drivers{
public static void main(String[] args) {
drivers("chrome");
driver.get("https://accounts.google.com/signup/v2/webcreateaccount?flowName=GlifWebSignIn&flowEntry=SignUp");
String signUpTitle=driver.getTitle();
System.out.println("The main page title is::"+signUpTitle);
driver.findElement(By.linkText("Help")).click();//help window opens automatically
/*
* How to get window handles
* In Selenium we have 2 methods to get the hand of a window
* getWindowHandle();
* getWindowHandles();
*
*/
Set<String> allWindowHandles=driver.getWindowHandles();
//Returns set of string IDs of all windows currently opened by the current instance
System.out.println("Number of windows open are::"+allWindowHandles.size());
Iterator<String>it=allWindowHandles.iterator();
String MainWindowHandle=it.next();//returns the id of the main window
System.out.println("The id of the main Window is::"+MainWindowHandle);
String childWindowHandle=it.next();//returns the id of the child window
System.out.println("The id of the child window is ::"+childWindowHandle);
//Using switch to method we switch to another window by passing the handle/ID of window
driver.switchTo().window(childWindowHandle);
String childWindowTitle=driver.getTitle();
System.out.println("Child page Title is::"+childWindowTitle);
}
}
| true
|
33356514abd44c0726b68ae0dca6839223e8fe4d
|
Java
|
ZoroSpace/Coursera
|
/src/Week4/Solver.java
|
UTF-8
| 6,952
| 3.15625
| 3
|
[] |
no_license
|
package Week4;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.MinPQ;
import edu.princeton.cs.algs4.Stack;
import edu.princeton.cs.algs4.StdOut;
/**
* Created by Zoro on 17-7-12.
*/
public class Solver {
private class SearchNode implements Comparable<SearchNode> {
Board currentBoard;
int steps;
SearchNode previousNode;
public SearchNode(Board currentBoard, int steps, SearchNode previousNode) {
this.currentBoard = currentBoard;
this.steps = steps;
this.previousNode = previousNode;
}
@Override
public int compareTo(SearchNode that) {
if (this.steps + this.currentBoard.manhattan() <
that.steps + that.currentBoard.manhattan()) return -1;
if (this.steps + this.currentBoard.manhattan() >
that.steps + that.currentBoard.manhattan()) return 1;
return 0;
}
}
private boolean solvableFlag = false;
private Stack<Board> solution = new Stack<>();
public Solver(Board initialBoard) {
if (initialBoard == null)
throw new IllegalArgumentException("The constructor received a null argument.");
MinPQ<SearchNode> openList = new MinPQ<>();
SearchNode initialSearchNode = new SearchNode(initialBoard,0,null);
openList.insert(initialSearchNode);
SearchNode end;//CLOSED
MinPQ<SearchNode> twinOpenList = new MinPQ<>();
SearchNode twinInitialSearchNode = new SearchNode(initialBoard.twin(),0,null);
twinOpenList.insert(twinInitialSearchNode);
SearchNode twinEnd;
while (!openList.min().currentBoard.isGoal() && !twinOpenList.min().currentBoard.isGoal()) {
SearchNode currentNode = openList.delMin();
//add current to CLOSED
// end = currentNode;
// label:
for (Board board : currentNode.currentBoard.neighbors()) {
if (currentNode.previousNode != null) {
if (!board.equals(currentNode.previousNode.currentBoard))
openList.insert(new SearchNode(board,currentNode.steps + 1,currentNode));
} else {
openList.insert(new SearchNode(board,currentNode.steps + 1,currentNode));
}
// //if neighbor in OPEN and cost less than g(neighbor):
// for (SearchNode node : openList) {
// if (board.equals(node.currentBoard)) {
// if (currentNode.steps + 1 < node.steps) {
// node.steps = currentNode.steps + 1;
// node.previousNode = currentNode;
// }
// continue label;
// }
// }
// //if neighbor in CLOSED and cost less than g(neighbor):
// for (SearchNode node = end;node != null;node = node.previousNode) {
// if (board.equals(node.currentBoard)) {
// if (currentNode.steps + 1 < node.steps) {
// node.steps = currentNode.steps + 1;
// node.previousNode = currentNode;
// }
// continue label;
// }
// }
// //if neighbor not in OPEN and neighbor not in CLOSED:
// openList.insert(new SearchNode(board,currentNode.steps + 1,currentNode));
}
SearchNode twinCurrentNode = twinOpenList.delMin();
//add current to CLOSED
// twinEnd = twinCurrentNode;
// label2:
for (Board board : twinCurrentNode.currentBoard.neighbors()) {
if (twinCurrentNode.previousNode != null) {
if ( !board.equals(twinCurrentNode.previousNode.currentBoard)) {
twinOpenList.insert(new SearchNode(board,twinCurrentNode.steps + 1,twinCurrentNode));
}
} else {
twinOpenList.insert(new SearchNode(board,twinCurrentNode.steps + 1,twinCurrentNode));
}
// //if neighbor in OPEN and cost less than g(neighbor):
// for (SearchNode node : twinOpenList) {
// if (board.equals(node.currentBoard)) {
// if (twinCurrentNode.steps + 1 < node.steps) {
// node.steps = twinCurrentNode.steps + 1;
// node.previousNode = twinCurrentNode;
// }
// continue label2;
// }
// }
// //if neighbor in CLOSED and cost less than g(neighbor):
// for (SearchNode node = twinEnd;node != null;node = node.previousNode) {
// if (board.equals(node.currentBoard)) {
// if (twinCurrentNode.steps + 1 < node.steps) {
// node.steps = twinCurrentNode.steps + 1;
// node.previousNode = twinCurrentNode;
// }
// continue label2;
// }
// }
// //if neighbor not in OPEN and neighbor not in CLOSED:
// twinOpenList.insert(new SearchNode(board,twinCurrentNode.steps + 1,twinCurrentNode));
}
}
if (openList.min().currentBoard.isGoal()) {
solvableFlag = true;
end = openList.min();
for (SearchNode node = end;node != null;node = node.previousNode) {
solution.push(node.currentBoard);
}
} else if (twinOpenList.min().currentBoard.isGoal()) {
solvableFlag = false;
}
}
public boolean isSolvable() {
return solvableFlag;
}
public Iterable<Board> solution() {
if (!isSolvable()) {
return null;
} else {
return solution;
}
}
public int moves() {
if (!isSolvable()) return -1;
else return solution.size() - 1;
}
public static void main(String[] args) {
// create initial board from file
In in = new In(args[0]);
int n = in.readInt();
int[][] blocks = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
blocks[i][j] = in.readInt();
Board initial = new Board(blocks);
// solve the puzzle
Solver solver = new Solver(initial);
// print solution to standard output
if (!solver.isSolvable())
StdOut.println("No solution possible");
else {
StdOut.println("Minimum number of moves = " + solver.moves());
for (Board board : solver.solution())
StdOut.println(board);
}
}
}
| true
|
d9d39e0f2cbc2bab696e66c8dc71d7a07c64c835
|
Java
|
jhonattas/e-deploy
|
/app/src/main/java/com/soucriador/edeploy/jhonattas/ui/activities/SearchActivity.java
|
UTF-8
| 1,560
| 2.09375
| 2
|
[] |
no_license
|
package com.soucriador.edeploy.jhonattas.ui.activities;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.soucriador.edeploy.jhonattas.R;
public class SearchActivity extends AppCompatActivity {
EditText edNome;
EditText edEstado;
Button btSubmit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
findComponents();
}
void findComponents() {
// encontra os componentes dentro do layout
edNome = findViewById(R.id.edNome);
edEstado = findViewById(R.id.edEstado);
btSubmit = findViewById(R.id.btPesquisa);
// adiciona a acao do botao de pesquisa
btSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle b = new Bundle();
b.putString("nome", edNome.getText().toString());
b.putString("estado", edEstado.getText().toString());
Intent i = new Intent(SearchActivity.this, ListAllCitiesActivity.class);
i.putExtras(b);
startActivity(i);
}
});
edNome.requestFocus();
}
@Override
public void onBackPressed() {
finish();
}
}
| true
|
46404b3def0eddb70003faab0eb575470827437b
|
Java
|
MichaelWangC/WEB_Demo
|
/CRM_API/src/com/api/service/CustomerService.java
|
UTF-8
| 322
| 1.796875
| 2
|
[] |
no_license
|
package com.api.service;
import com.api.beans.Customer;
import java.util.List;
/**
* Created by wangc on 2017/8/24.
*/
public interface CustomerService {
String addCustomer(Customer customer);
List<Customer> getCustomerList(Integer start, Integer limit, String custname, String ownerId, String customerId);
}
| true
|
411581486500a7e6a57f1505510fc91c3e2f7c1f
|
Java
|
IoTUDresden/proteus
|
/bundles/utils/eu.vicci.process.client/src/main/java/eu/vicci/process/client/subscribers/FeedbackServiceSubscriber.java
|
UTF-8
| 647
| 1.96875
| 2
|
[] |
no_license
|
package eu.vicci.process.client.subscribers;
import eu.vicci.process.model.util.configuration.TopicId;
import eu.vicci.process.model.util.messages.core.CompensationRequest;
import eu.vicci.process.model.util.messages.core.IMessageReceiver;
import ws.wamp.jawampa.PubSubData;
public class FeedbackServiceSubscriber extends AbstractSubscriber<PubSubData, CompensationRequest> {
public FeedbackServiceSubscriber(IMessageReceiver<CompensationRequest> receiver) {
super(receiver, TopicId.FEEDBACK_COMPENSATION);
}
@Override
public void onNext(PubSubData arg0) {
receiver.onMessage(convertFromJson(arg0, CompensationRequest.class));
}
}
| true
|
8948d80fa3b454abed8d9288e2048cdc59f8aef5
|
Java
|
roverxiafan/service
|
/service-core/src/main/java/com/example/util/encrypt/AES.java
|
UTF-8
| 2,589
| 3.15625
| 3
|
[] |
no_license
|
package com.example.util.encrypt;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* @title: AES
* @Description: AES加解密
* @author: roverxiafan
* @date: 2016/11/7 15:56
*/
@Slf4j
public class AES {
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
/**
* AES 加密操作
*
* @param content 待加密内容
* @param password 加密密码
* @return 返回Base64转码后的加密数据
*/
public static String encrypt(String content, String password) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password));
byte[] result = cipher.doFinal(byteContent);
return Base64.encodeBase64String(result);
} catch (Exception e) {
log.error("AES encrypt exception", e);
}
return null;
}
/**
* AES 解密操作
*
* @param content Base64转码后的加密数据
* @param password 解密密码
* @return 解密内容
*/
public static String decrypt(String content, String password) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password));
byte[] result = cipher.doFinal(Base64.decodeBase64(content));
return new String(result, "utf-8");
} catch (Exception e) {
log.error("AES decrypt exception", e);
}
return null;
}
private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException {
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
kg.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kg.generateKey();
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
}
public static void main(String[] args) {
String str = "{\"a\":1, \"b\":\"test测试\"}";
String secretKey = "a&e1i*sdf5u*1";
String s1 = AES.encrypt(str, secretKey);
System.out.println(s1);
System.out.println(AES.decrypt(s1, secretKey));
}
}
| true
|
507ce11d269a1e69cad931c4d75bab8568592030
|
Java
|
hyj911208/AndroidLibs
|
/common/src/main/java/com/kunpeng/common/base/ui/BaseActivity.java
|
UTF-8
| 5,128
| 2.03125
| 2
|
[] |
no_license
|
package com.kunpeng.common.base.ui;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.kunpeng.common.base.ui.callback.UiCallback;
import com.kunpeng.common.bus.BusFactory;
import com.kunpeng.common.manager.ActivityStackManager;
import com.kunpeng.common.utils.ToolsHelper;
/**
* @Author xuqm
* @Date 2019/12/18-21:59
* @Email xuqinmin12@sina.com
*/
public abstract class BaseActivity<V extends ViewDataBinding> extends AppCompatActivity implements UiCallback {
protected String TAG = this.getClass().getSimpleName();
protected Activity mContext;
private V binding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ARouter.getInstance().inject(this);
//act统一管理
ActivityStackManager.getInstance().pushOneActivity(this);
//统一的context管理
this.mContext = this;
//layout加载
if (getLayoutId() > 0) {
bindUI(getLayoutId());
}
//子类重写进行页面初始化
initData(savedInstanceState);
// 沉浸式状态栏
ImmersionBar.with(this).keyboardEnable(true).statusBarDarkFont(isDark()).init();
//各种点击事件监听的初始化
setListener();
}
// 状态栏字体颜色 --- true 黑色
protected boolean isDark(){
return false;
}
protected V getBinding() {
return binding;
}
public void bindUI(@LayoutRes int layoutResID) {
binding = DataBindingUtil.setContentView(mContext, layoutResID);
}
@Override
protected void onStart() {
super.onStart();
if (useEventBus()) {
BusFactory.getBus().register(this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
ActivityStackManager.getInstance().popOneActivity(this);
if (useEventBus()) {
BusFactory.getBus().unregister(this);
}
// 必须调用该方法,防止内存泄漏
//ImmersionBar.with(this).destroy();
}
/**
* 当前页面启用eventbus,需要
* *@Subscribe(threadMode = ThreadMode.MAIN)
* *public void...
*/
@Override
public boolean useEventBus() {
return false;
}
@Override
public void setListener() {
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//非默认值
if (newConfig.fontScale != 1) {
getResources();
}
// 如果你的app可以横竖屏切换,并且适配4.4或者emui3手机请务必在onConfigurationChanged方法里添加这句话
ImmersionBar.with(this).init();
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev)) {
hideInput(v);
}
return super.dispatchTouchEvent(ev);
}
// 必不可少,否则所有的组件都不会有TouchEvent了
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
public void hideInput(View v) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
public boolean isShouldHideInput(View v, MotionEvent event) {
if ((v instanceof EditText)) {
int[] leftTop = { 0, 0 };
//获取输入框当前的location位置
v.getLocationInWindow(leftTop);
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + v.getHeight();
int right = left + v.getWidth();
// 点击的是输入框区域,保留点击EditText的事件
return !(event.getX() > left) || !(event.getX() < right) || !(event.getY() > top) ||
!(event.getY() < bottom);
}
return false;
}
private long exitTime = 0;// 等待时间
public void exit() {
if ((System.currentTimeMillis() - exitTime) > 2000) {
ToolsHelper.showInfo("再按一次退出该页面");
exitTime = System.currentTimeMillis();
} else {
ActivityStackManager.getInstance().finishAllActivity();
}
}
}
| true
|