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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
600cf6956035529a478f0f9331061b980b11823d | Java | goustein/Graphs | /src/main/java/com/goustein/graphs/directed/TopologicalSortDIrectedGraphs.java | UTF-8 | 1,601 | 3.140625 | 3 | [] | no_license | package com.goustein.graphs.directed;
import java.util.LinkedList;
import java.util.Stack;
import com.goustein.graphs.DirectedEdge;
import com.goustein.graphs.EdgeWeightedDAG;
public class TopologicalSortDIrectedGraphs {
static Stack<Integer> topStack = new Stack<Integer>();
static boolean [] isVisted;
static Stack<Integer> stack = new Stack();
static boolean [] inStack;
public static void main(String[] args) {
EdgeWeightedDAG g = DiGraphIntializer.getdigraph();
Stack<Integer> stack = topologicalSort(g);
System.out.println(stack);
}
static Stack<Integer> topologicalSort(EdgeWeightedDAG g){
isVisted = new boolean[g.vertex];
inStack = new boolean[g.vertex];
if(DirectedGraphCycleCheck.hasCycle(g)){
System.out.println("Has a cycle");
}else{
for(int i =0 ;i < g.vertex ; i++){
if(!isVisted[i]){
DFS(i, g);
}
}
}
return topStack;
}
static void DFS(int source,EdgeWeightedDAG g){
isVisted[source] = true;
stack.add(source);
inStack[source] = true;
while(!stack.isEmpty()){
int node =stack.peek();
int nextUnvistedNode = getUnvistedNode(node, g);
if(nextUnvistedNode == -1){
int poped =stack.pop();
topStack.add(poped);
}else{
stack.add(nextUnvistedNode);
isVisted[nextUnvistedNode] = true;
}
}
}
static private int getUnvistedNode(int node, EdgeWeightedDAG g) {
LinkedList<DirectedEdge> list = g.adj[node];
for(int i =0 ; i< list.size() ;i++){
if(!isVisted[list.get(i).to]) return list.get(i).to;
}
return -1;
}
}
| true |
0806b9b0eb069545e7694160e52994d150e99673 | Java | nengqiang/java-thoughts | /algorithm-demo/src/main/java/com/hnq/study/everyday/earlier/IsPalindrome.java | UTF-8 | 1,974 | 4 | 4 | [] | no_license | package com.hnq.study.everyday.earlier;
import java.util.stream.IntStream;
/**
* 给你一个整数 x ,如果 x 是一个回文整数,返回 true ;否则,返回 false 。
*
* 回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。例如,121 是回文,而 123 不是。
*
*
*
* 示例 1:
*
* 输入:x = 121
* 输出:true
* 示例2:
*
* 输入:x = -121
* 输出:false
* 解释:从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
* 示例 3:
*
* 输入:x = 10
* 输出:false
* 解释:从右向左读, 为 01 。因此它不是一个回文数。
* 示例 4:
*
* 输入:x = -101
* 输出:false
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/palindrome-number
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @author henengqiang
* @date 2021/6/19
*/
public class IsPalindrome {
public static void main(String[] args) {
System.out.println(isPalindrome2(121));
System.out.println(isPalindrome2(-121));
System.out.println(isPalindrome2(10));
System.out.println(isPalindrome2(-101));
}
private static boolean isPalindrome(int x) {
// 21ms
if (x < 0) {
return false;
}
String s = String.valueOf(x);
char[] sc = s.toCharArray();
return IntStream.range(0, sc.length / 2).allMatch(i -> sc[i] == sc[sc.length - 1 - i]);
}
private static boolean isPalindrome2(int x) {
// 10 ms
if (x < 0 || x != 0 && x % 10 == 0) {
return false;
}
String s = String.valueOf(x);
int l = 0, r = s.length() - 1;
while (l < r) {
if (s.charAt(l) != s.charAt(r)) {
return false;
}
l++;
r--;
}
return true;
}
}
| true |
81a0f3169caaa6b6cd7f699a92731a8250d7c4d8 | Java | hanbing2018/leetCode | /src/main/java/链表/_92_反转链表_II.java | UTF-8 | 1,043 | 3.640625 | 4 | [] | no_license | package 链表;
public class _92_反转链表_II {
//https://leetcode-cn.com/problems/reverse-linked-list-ii/
/**
* 两层递归。首先构造递归函数能够翻转前k个节点,再递归调用此函数即可
*
* @param head
* @param m
* @param n
* @return
*/
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m == 1) {
return reverseK(head, n);
}
ListNode newHead = reverseBetween(head.next, m - 1, n - 1);
head.next = newHead;
return head;
}
//翻转链表前k个节点,这个函数可以当做通用函数用在链表翻转类的题目中
//用一个全局变量next指向第k+1个节点
ListNode next = null;
private ListNode reverseK(ListNode head, int k) {
if (k == 1) {
next = head.next;
return head;
}
ListNode newHead = reverseK(head.next, k - 1);
head.next.next = head;
head.next = next;
return newHead;
}
}
| true |
8f1a679b12c15301f33af832f165ba1f1ee5dbba | Java | kesav09/java_programs | /src/array/BinarySearch.java | UTF-8 | 4,624 | 3.890625 | 4 | [] | no_license | package array;
import java.util.HashMap;
public class BinarySearch {
static int[] num = new int[]{2, 2, 2, 2, 2};
static int[] numbers = new int[]{ 1, 13, 42, 42, 42, 77, 78 };
public static void main(String [] args){
// binarySearch(num, 12);
System.out.println(binarySearchIterative(num, 4));
findIndex(numbers, 42);
// PrintIndicesForValue(numbers, 42);
}
public static void binarySearch(int [] num, int k){
if(num.length < 1 || k < num[0] || k > num[num.length-1]) return;
if(num.length == 1 && num[0] != k) return;
System.out.println(binarySearch(num, 0, num.length-1, k));
}
//recursive solution
public static boolean binarySearch(int [] num, int start, int end, int k){
int midpoint = (start + end) / 2;
if (num[midpoint] > k)
return binarySearch(num, 0, midpoint-1, k);
else if(num[midpoint] < k)
return binarySearch(num, midpoint+1, end, k);
else if(num[midpoint] == k)
return true;
else
return false;
}
//iterative solution
public static boolean binarySearchIterative(int [] num, int k){
if(num.length < 1 || k < num[0] || k > num[num.length-1]) return false;
int i = 0;
int j = num.length - 1;
while(i <= j){
int midpoint = (i + j) / 2;
if (num[midpoint] > k)
j = midpoint - 1;
else if (num[midpoint] < k)
i = midpoint + 1;
else if (num[midpoint] == k)
return true;
}
return false;
}
//given a sorted array find the start and end of a particular integer in an array
//use modified binary search
public static HashMap<Integer, String> findIndex(int [] num, int k ){
HashMap<Integer, String> map = new HashMap<Integer, String>();
if(num.length < 1 || k < num[0] || k > num[num.length-1]) return null;
if(num.length == 1 && num[0] == k){
map.put(num[0], "(0, 0)");
}
int start = 0;
int end = num.length - 1;
if (num[start] == k && num[end] == k){
map.put(k, "(start index = "+start+", end index = "+end+")");
System.out.println(map);
} else {
while (start <= end) {
int midpoint = (start + end) / 2;
if (num[midpoint] > k)
end = midpoint - 1;
else if (num[midpoint] < k)
start = midpoint + 1;
else {
int j = midpoint;
int i = midpoint;
while (num[midpoint] == num[i]) {
i--;
if (i < 0)
break;
}
while (num[midpoint] == num[j]) {
j++;
if (j == num.length)
break;
}
map.put(k, "(start index = " + (i + 1) + ", end index = " + (j - 1) + ")");
System.out.println(map);
return map;
}
}
}
return null;
}
// sortedArray = { 1, 13, 42, 42, 42, 77, 78 } would print: "42 was found at Indices: 2, 3, 4"
public static void PrintIndicesForValue(int[] numbers, int target) {
if (numbers == null)
return;
int low = 0, high = numbers.length - 1;
// get the start index of target number
int startIndex = -1;
while (low <= high) {
int mid = (high - low) / 2 + low;
if (numbers[mid] > target) {
high = mid - 1;
} else if (numbers[mid] == target) {
startIndex = mid;
high = mid - 1;
} else
low = mid + 1;
}
// get the end index of target number
int endIndex = -1;
low = 0;
high = numbers.length - 1;
while (low <= high) {
int mid = (high - low) / 2 + low;
if (numbers[mid] > target) {
high = mid - 1;
} else if (numbers[mid] == target) {
endIndex = mid;
low = mid + 1;
} else
low = mid + 1;
}
if (startIndex != -1 && endIndex != -1){
for(int i=0; i+startIndex<=endIndex;i++){
if(i>0)
System.out.print(',');
System.out.print(i+startIndex);
}
}
}
/**
* unknown array length or unlimited array.
* input(<array>,0,1,<searchElement>)
* @param num
* @param start
* @param end
* @param search
* @return
*/
public static Integer modifiedBinarySearch(int[] num, int start, int end, int search) {
if (start > end) {
return null;
}
try {
if (num[end] < search) {
return modifiedBinarySearch(num, end, 2 * end, search);
} else {
int mid = (start + end) / 2;
if (num[mid] == search) {
return mid;
} else if (num[mid] > search) {
return modifiedBinarySearch(num, start, mid - 1, search);
} else {
return modifiedBinarySearch(num, mid + 1, end, search);
}
}
} catch (ArrayIndexOutOfBoundsException e) {
return modifiedBinarySearch(num, start, end - 1, search);
}
}
}
| true |
66c070e532d933c5125296fdd8f3b2867934e51f | Java | Jimmeh94/Avatar | /src/main/java/avatar/event/ChatEvents.java | UTF-8 | 1,156 | 2.40625 | 2 | [
"MIT"
] | permissive | package avatar.event;
import avatar.Avatar;
import avatar.game.chat.ChatColorTemplate;
import avatar.game.user.UserPlayer;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.filter.cause.First;
import org.spongepowered.api.event.message.MessageChannelEvent;
import org.spongepowered.api.text.Text;
public class ChatEvents {
@Listener
public void onChat(MessageChannelEvent.Chat event, @First Player player){
event.setCancelled(true);
UserPlayer userPlayer = Avatar.INSTANCE.getUserManager().findUserPlayer(player).get();
userPlayer.getChatChannel().displayMessage(build(event.getRawMessage().toPlain(), userPlayer));
}
private Text build(String message, UserPlayer userPlayer){
ChatColorTemplate color = userPlayer.getChatColorTemplate();
return Text.builder().append(Text.of(color.getPrefix(), userPlayer.getTitle().getDisplay()))
.append(Text.of(color.getName(), userPlayer.getPlayer().get().getName() + ": "))
.append(Text.of(color.getMessage(), message)).build();
}
}
| true |
9d9ca4090da451987a709341fc2e40446fda1fdb | Java | jeancarlosdanese/design-patterns | /outros/AngularJS/src/main/java/br/com/danese/model/Pessoa.java | UTF-8 | 5,642 | 2.046875 | 2 | [] | no_license | package br.com.danese.model;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.LazyToOne;
import org.hibernate.annotations.LazyToOneOption;
import org.hibernate.bytecode.internal.javassist.FieldHandled;
import org.hibernate.bytecode.internal.javassist.FieldHandler;
import org.hibernate.envers.Audited;
import org.hibernate.envers.NotAudited;
import org.hibernate.validator.constraints.NotBlank;
import br.com.danese.model.dominio.DominioEstadoCivil;
import br.com.danese.model.dominio.DominioSexo;
import br.com.danese.model.dominio.DominioTipoPessoa;
import br.com.danese.validator.CpfCnpj;
import javax.xml.bind.annotation.XmlRootElement;
@SuppressWarnings("deprecation")
@Audited
@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = "cpfcnpj", name = "cpfcnpj_ukey"))
@XmlRootElement
public class Pessoa implements BaseModel<Long>, FieldHandled {
private static final long serialVersionUID = 2038138058466087609L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private FieldHandler handler;
@NotBlank
@Size(min = 3, max = 100)
@Pattern(regexp = "[^0-9]*", message = "não deve conter números")
private String nome;
@Enumerated(EnumType.STRING)
@Column(length = 8)
private DominioTipoPessoa tipoPessoa;
@Enumerated(EnumType.STRING)
@Column(length = 9)
private DominioSexo sexo;
@Enumerated(EnumType.STRING)
@Column(length = 10)
private DominioEstadoCivil estadoCivil;
@Temporal(TemporalType.DATE)
private Date dataNascimento;
@CpfCnpj
private String cpfCnpj;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
@PrimaryKeyJoinColumn
@LazyToOne(LazyToOneOption.NO_PROXY)
private Usuario usuario;
@NotAudited
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "pessoa", orphanRemoval = true)
@ForeignKey(name = "pessoa_fkey")
private List<EnderecoEmail> emails;
@NotAudited
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "pessoa", orphanRemoval = true)
@ForeignKey(name = "pessoa_fkey")
private List<Endereco> enderecos;
@NotAudited
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "pessoa", orphanRemoval = true)
@ForeignKey(name = "pessoa_fkey")
private List<Telefone> telefones;
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.isEmpty() ? null : nome;
}
public DominioSexo getSexo() {
return sexo;
}
public void setSexo(DominioSexo sexo) {
this.sexo = sexo;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
public DominioTipoPessoa getTipoPessoa() {
return tipoPessoa;
}
public void setTipoPessoa(DominioTipoPessoa tipoPessoa) {
this.tipoPessoa = tipoPessoa;
}
public String getCpfCnpj() {
return cpfCnpj;
}
public void setCpfCnpj(String cpfCnpj) {
this.cpfCnpj = cpfCnpj.isEmpty() ? null : cpfCnpj;
}
public Usuario getUsuario() {
if (handler != null) {
return (Usuario) handler.readObject(this, "usuario", usuario);
}
return usuario;
}
public void setUsuario(Usuario usuario) {
if (handler != null) {
this.usuario = (Usuario) handler.writeObject(this, "usuario",
this.usuario, usuario);
}
this.usuario = usuario;
}
public List<EnderecoEmail> getEmails() {
return emails;
}
public void setEmails(List<EnderecoEmail> emails) {
this.emails = emails;
}
public List<Endereco> getEnderecos() {
return enderecos;
}
public void setEnderecos(List<Endereco> enderecos) {
this.enderecos = enderecos;
}
public List<Telefone> getTelefones() {
return telefones;
}
public void setTelefones(List<Telefone> telefones) {
this.telefones = telefones;
}
@Override
public void setFieldHandler(FieldHandler handler) {
this.handler = handler;
}
@Override
public FieldHandler getFieldHandler() {
return handler;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Pessoa other = (Pessoa) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
public boolean isEmpresa() {
if (this.tipoPessoa != null
&& this.tipoPessoa.equals(DominioTipoPessoa.JURIDICA)) {
return true;
}
return false;
}
public DominioEstadoCivil getEstadoCivil() {
return estadoCivil;
}
public void setEstadoCivil(DominioEstadoCivil estadoCivil) {
this.estadoCivil = estadoCivil;
}
} | true |
f1f43045be8e21ea2896a0e2cedafefd356a40b1 | Java | j0sephx/JavaAutomationFrameworkProject | /src/main/java/application/common/utilities/WebDriverHelper.java | UTF-8 | 2,194 | 2.53125 | 3 | [] | no_license | package application.common.utilities;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class WebDriverHelper
{
private static final String CHROME_PATH = System.getProperty("user.dir") + "//drivers//chromedriver.exe";
private static final String FIREFOX_PATH = System.getProperty("user.dir") + "//drivers//geckodriver.exe";
private static final String IE_PATH = System.getProperty("user.dir") + "//drivers//IEDriverServer.exe";
private static WebDriver driver;
public static void createDriver(String browserName)
{
if (browserName.equals("CHROME"))
{
System.setProperty("webdriver.chrome.driver", CHROME_PATH);
driver = new ChromeDriver();
}
else if (browserName.equals("FIREFOX"))
{
System.setProperty("webdriver.gecko.driver", FIREFOX_PATH);
driver = new FirefoxDriver();
}
else if (browserName.equals("IE"))
{
System.setProperty("webdriver.ie.driver", IE_PATH);
driver = new InternetExplorerDriver();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
public static void destroyWebdriver()
{
driver.quit();
}
public static WebDriver getDriver()
{
return driver;
}
public static void getURL(String url)
{
driver.navigate().to(url);
}
public static void switchIframe()
{
driver.switchTo().defaultContent();
}
public static void takeScreenshot() throws IOException
{
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
FileUtils.copyFile(scrFile, new File("C:\\NewWorkSpace\\Screenshots\\" + timeStamp +".png"));
}
} | true |
4d55476b785e11b628cc252bfbcd71dc71fb30d1 | Java | zhuzhsh/play-freemarker-plugin | /play/modules/freemarker/Plugin.java | UTF-8 | 4,046 | 1.984375 | 2 | [] | no_license | /**
*
* Copyright 2010, greenlaw110@gmail.com.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
* User: Green Luo
* Date: Mar 26, 2010
*
*/
package play.modules.freemarker;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.regex.Pattern;
import play.Play;
import play.PlayPlugin;
import play.exceptions.UnexpectedException;
import play.mvc.Http.Request;
import play.mvc.results.Result;
import play.templates.Template;
import play.vfs.VirtualFile;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
public class Plugin extends PlayPlugin {
public static final String VERSION = "1.2.3";
public static PlayPlugin templateLoader = null;
private final static Pattern p_ = Pattern.compile(".*\\.(ftl)");
private static Configuration cfg = new Configuration();
public static freemarker.template.Template getTemplate(String name){
try {
return cfg.getTemplate(name);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public Template loadTemplate(VirtualFile file) {
if (!p_.matcher(file.getName()).matches())
return null;
if (null == templateLoader)
return new FreemarkerTemplate(file);
return templateLoader.loadTemplate(file);
}
@Override
public void onApplicationStart() {
VirtualFile appRoot = VirtualFile.open(Play.applicationPath);
VirtualFile tmplRoot= appRoot.child("/");
try {
File file=tmplRoot.getRealFile();
cfg.setDirectoryForTemplateLoading(file);
cfg.setObjectWrapper(new DefaultObjectWrapper());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Extend play format processing
*/
@Override
public void beforeActionInvocation(Method actionMethod) {
/*Request request = Request.current();
Header h = request.headers.get("user-agent");
if (null == h)
return;
String userAgent = h.value();
if (pIE678_.matcher(userAgent).matches())
return; // IE678 is tricky!, IE678 is buggy, IE678 is evil!
if (request.headers.get("accept") != null) {
String accept = request.headers.get("accept").value();
if (accept.indexOf("text/csv") != -1)
request.format = "csv";
if (accept
.matches(".*application\\/(excel|vnd\\.ms\\-excel|x\\-excel|x\\-msexcel).*"))
request.format = "xls";
if (accept
.indexOf("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") != -1)
request.format = "xlsx";
}*/
}
/*
* Set response header if needed
*/
@Override
public void onActionInvocationResult(Result result) {
Request request = Request.current();
if (null == request.format || !request.format.matches("(ftl)"))
return;
}
public static class FreemarkerTemplate extends Template {
private File file = null;
private FreemarkerRender r_ = null;
public FreemarkerTemplate(VirtualFile file) {
this.name = file.relativePath();
this.file = file.getRealFile();
}
public FreemarkerTemplate(FreemarkerRender render) {
r_ = render;
}
@Override
public void compile() {
if (!file.canRead())
throw new UnexpectedException("template file not readable: "
+ name);
}
@Override
protected String internalRender(Map<String, Object> args) {
throw null == r_ ? new FreemarkerRender(name, args) : r_;
}
}
}
| true |
e0f2c9cabb3b9e7a12560f29fe6cc8cd62935a9b | Java | zerohouse/webthstone | /src/main/java/org/next/ws/core/StaticValues.java | UTF-8 | 539 | 1.734375 | 2 | [] | no_license | package org.next.ws.core;
public class StaticValues {
public static final int DEFAULT_HAND_MAX_SIZE = 10;
public static final int DEFAULT_FIELD_MAX_SIZE = 7;
public static final int DEFAULT_MIN_VITAL = 0;
public static final int TURN_TIME_OUT = 32000;
public static final int MY_GAME_HERO_ID = 0;
public static final int ENEMY_GAME_HERO_ID = 1;
public static final int DEFAULT_ATTACK_COUNT_WHEN_PLAYED = 0;
public static final long DEFAULT_PAGE_SIZE = 10;
public static final String DELIMITER = ",";
}
| true |
600c940476134f3c5d6bcd439b031646f8ef43ac | Java | mnagel2/CMSC204 | /Assignment/DonationManager.java | UTF-8 | 2,733 | 3.46875 | 3 | [] | no_license | /**
*
* @author jake
* Donation manager class, implements DonationManageInterface
*/
public class DonationManager implements DonationManageInterface {
// CONTAINER
Container container = new Container(5);
VolunteerLine volunteerLine = new VolunteerLine(5);
RecipientLine recipientLine = new RecipientLine(5);
/**
* Manager method to call loadContainer
* @param dPackage
* @return true
*/
@Override
public boolean managerLoadContainer(DonationPackage dPackage) throws ContainerException {
try {
container.loadContainer(dPackage);
}
catch (ContainerException e) {
throw new ContainerException("The Container is Full");
}
return true;
}
@Override
/**
* Manager method to call addNewVolunteer
* @param Volunteer v
* @return true
*/
public boolean managerQueueVolunteer(Volunteer v) throws VolunteerException {
try {
volunteerLine.addNewVolunteer(v);
}
catch (VolunteerException e) {
throw new VolunteerException("Volunteer Line is Full");
}
return true;
}
@Override
/**
* Manager method to call addNewRecipient
* @param Recipient r
* @return true
*/
public boolean managerQueueRecipient(Recipient r) throws RecipientException {
try {
recipientLine.addNewRecipient(r);
}
catch (RecipientException e) {
throw new RecipientException("Recipient Line is Full");
}
return true;
}
/**
* Handles the donation of a package, which involves modifying the volunteer and recipient line
* @param
* @return 0
*/
@Override
public int donatePackage() throws VolunteerException, ContainerException, RecipientException {
if (container.removePackageFromContainer() == null) {
throw new ContainerException("Container is Empty");
}
if (volunteerLine.addNewVolunteer(volunteerLine.volunteerTurn()) == false) {
throw new VolunteerException("Volunteer Queue is Empty");
}
if (recipientLine.recipientTurn() == null) {
throw new RecipientException("Recipient Queue is empty");
}
return 0;
}
/**
* Manager method to call container toArrayPackage
* @param
* @return arr
*/
@Override
public DonationPackage[] managerArrayPackage() {
return container.toArrayPackage();
}
/**
* Manager method to call container toArrayVolunteer
* @param
* @return arr
*/
@Override
public Volunteer[] managerArrayVolunteer() {
return volunteerLine.toArrayVolunteer();
}
/**
* Manager method to call container toArrayRecipient
* @param
* @return arr
*/
@Override
public Recipient[] managerArrayRecipient() {
return recipientLine.toArrayRecipient();
}
}
| true |
74daa410928f4db2e56417d06d76839ef89fa489 | Java | BruceTim/intelligentjoy-advertising-api | /intelligentjoy-advertising-api-base/src/main/java/com/intelligentjoy/advertising/api/base/model/tree/TreeModel.java | UTF-8 | 2,504 | 2.78125 | 3 | [] | no_license | package com.intelligentjoy.advertising.api.base.model.tree;
import com.intelligentjoy.advertising.api.base.model.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
/**
* 权限树
*
* @author BruceTim
* @date 2020-12-04
*/
public class TreeModel<T extends TreeNode> implements Serializable {
private static final long serialVersionUID = 3544897406484560446L;
private List<T> nodes = null;
public TreeModel() {
nodes = Collections.emptyList();
}
public TreeModel(List<T> nodes) {
this.nodes = nodes;
}
/**
* 建立树形结构
*
* @return
*/
public List<TreeNode> buildTree() {
if (nodes == null || nodes.isEmpty()) {
return Collections.emptyList();
}
List<TreeNode> nodeList = nodes.stream().filter(e -> e.getParentId() == null || 0L == e.getParentId().longValue())
.map(node -> buildChildTree(node))
.sorted(Comparator.comparingInt(TreeNode::getOrder))
.collect(Collectors.toList());
return nodeList;
}
/**
* 递归,建立子树形结构
*
* @param pNode
* @return
*/
private TreeNode buildChildTree(TreeNode pNode) {
List<TreeNode> childResources = nodes.stream().filter(e -> pNode.getId().equals(e.getParentId()))
.map(node -> buildChildTree(node))
.sorted(Comparator.comparingInt(TreeNode::getOrder))
.collect(Collectors.toList());
pNode.setChildren(childResources);
return pNode;
}
public static void main(String[] args) {
List<Resource> resources = new ArrayList<>(20);
for (Integer i = 1; i <= 20; i++) {
Resource resource = new Resource();
resource.setResourceId(i);
resource.setResourceCode(i.toString());
resource.setActionUrl(i.toString());
resource.setResourceName(i.toString());
resource.setDescription(i.toString());
resource.setParentId(i > 10 ? (i + 2) % 7 : (i - 1) % 5);
resource.setType(1);
resource.setLevel(1);
resource.setOrder(i % 5);
resources.add(resource);
}
resources.forEach(e -> System.out.println(e.getParentId()));
resources = new TreeModel(resources).buildTree();
}
} | true |
e10b1c2a06e04003cbb0abee8940b1e720706d02 | Java | wnr/Lab1 | /src/core/WordFinder.java | WINDOWS-1252 | 4,919 | 3.015625 | 3 | [] | no_license | package core;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
public final class WordFinder {
public static WordPair find(String word) throws IOException {
int smallIndex = hashSmallIndex(word);
if(!new File(Main.SMALL_INDICES_PATH + smallIndex).isFile()){
// We don't have the "hash-file" meaning we do not have the word!
return null;
}
// Get the fi
FileBuffered smallIndexFileStart = new FileBuffered(Main.SMALL_INDICES_PATH + smallIndex, "r");
FileRandom mediumIndexFile = new FileRandom(Main.MEDIUM_INDEX_NAME, "r");
// Get the starting pos and the starting word before the search starts
long mediumIndexStart = Long.parseLong(smallIndexFileStart.readLine());
String mediumIndexStartWord = mediumIndexFile.readWordStandStill(mediumIndexStart);
smallIndexFileStart.close();
WordPair startPair = new WordPair(mediumIndexStartWord, mediumIndexStart);
WordPair endPair = null;
boolean foundFile = false;
for(int i = 1; smallIndex + i <= hashSmallIndex("") && !foundFile; i++){
if(new File(Main.SMALL_INDICES_PATH + (smallIndex + i)).isFile()){
FileBuffered smallIndexFileEnd = new FileBuffered(Main.SMALL_INDICES_PATH + (smallIndex + i), "r");
endPair = mediumIndexFile.readWordWalkLeft(Long.parseLong(smallIndexFileEnd.readLine()) - 1);
smallIndexFileEnd.close();
foundFile = true;
}
}
if(!foundFile){
// We have not found a "ending file" meaning we have to set the last word in medium file as the ending-file.
endPair = mediumIndexFile.readWordWalkLeft(mediumIndexFile.length()-1);
}
long bigIndex;
if(startPair.text.equals(word)){
bigIndex = mediumIndexFile.readWordsIndex(startPair.index);
} else if(endPair.text.equals(word)){
bigIndex = mediumIndexFile.readWordsIndex(endPair.index);
} else{
bigIndex = binarySearch(startPair, endPair, word, mediumIndexFile);
}
if(bigIndex == -1){
return null;
}
LinkedList<Long> bigIndicesList = getBigIndices(bigIndex, word);
return getFinalResult(bigIndicesList, word);
}
public static WordPair getFinalResult(LinkedList<Long> bigIndicesList, String word) throws UnsupportedEncodingException, IOException{
FileRandom korpusFile = new FileRandom(Main.KORPUS_NAME, "r");
StringBuilder returnText = new StringBuilder();
for(long korpusIndex : bigIndicesList){
returnText.append(korpusFile.getSurroundingText(korpusIndex, word.length()).replaceAll("(\\n)+", " ") + "\n");
}
korpusFile.close();
return new WordPair(returnText.toString(), bigIndicesList.size());
}
public static LinkedList<Long> getBigIndices(long bigIndex, String searchWord) throws IOException{
FileRandom bigIndexFile = new FileRandom(Main.BIG_INDEX_NAME, "r");
LinkedList<Long> returnList = new LinkedList<Long>();
bigIndexFile.seek(bigIndex);
WordPair bigPair = bigIndexFile.readWordPairLinewise();
while(!(bigPair == null || !bigPair.text.equals(searchWord))){
returnList.add(bigPair.index);
bigPair = bigIndexFile.readWordPairLinewise();
}
bigIndexFile.close();
return returnList;
}
public static long binarySearch(WordPair lowPair, WordPair highPair, String searchWord, FileRandom mediumIndexFile) throws IOException{
String lowWord = lowPair.text;
long lowIndex = lowPair.index;
String highWord = highPair.text;
long highIndex = highPair.index;
long midIndex = lowIndex + (highIndex-lowIndex)/2;
WordPair midPair = mediumIndexFile.readWordWalkRight(midIndex);
if(midPair.text.equals(highWord)){
midPair = mediumIndexFile.readWordWalkLeft(midIndex);
}
if(midPair.text.equals(lowWord)){
return -1;
}
int compareValue = searchWord.compareTo(midPair.text);
if(compareValue == 0){
return mediumIndexFile.readWordsIndex(midPair.index);
} else if(compareValue < 0 ){
return binarySearch(lowPair, midPair, searchWord, mediumIndexFile);
} else{
return binarySearch(midPair, highPair, searchWord, mediumIndexFile);
}
}
public static int hashSmallIndex(String word){
int returnValue = 0;
for(int i = 0; i < 3 && i < word.length(); i++){
if(i == 0){
returnValue += convertCharToInt(word.charAt(i))*871-870;
} else if(i == 1){
returnValue += convertCharToInt(word.charAt(i))*30 -29;
} else {
returnValue += convertCharToInt(word.charAt(i));
}
}
return returnValue;
}
private static int convertCharToInt(char c){
int code = (int) c;
if(code > 64 && code < 91){
return code - 64;
}else if(code > 96 && code < 123){
return code - 96;
}else if(code == 229 || code == 197){
return 27;
}else if(code == 228 || code == 196){
return 28;
}else if(code == 246 || code == 214){
return 29;
} else{
throw new RuntimeException("Character is not a letter: " + c + " and gives the ascii: " + code);
}
}
}
| true |
1988bd0b1a90ccf7c4bbe35de844f6e972e99550 | Java | ManuelPalomares/QuinpacAndroidApp | /src/main/java/com/web/webmapsoft/clientews/NLIZstPmDataSibtc.java | UTF-8 | 12,637 | 2.03125 | 2 | [] | no_license | package com.web.webmapsoft.clientews;
//----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 4.1.9.1
//
// Created by Quasar Development at 28-11-2015
//
//---------------------------------------------------
import java.util.Hashtable;
import org.ksoap2.serialization.*;
public class NLIZstPmDataSibtc extends AttributeContainer implements KvmSerializable
{
public String CodBarras;
public String NewCodBarras;
public String NumSerie;
public String Lote;
public String CapaCloro;
public String TaraReal;
public String TipoRecipi;
public String TaraImpresa;
public String FchPruHidro;
public String FchNextPrueba;
public String TaraNueva;
public String Estacion;
public NLIZstPmDataSibtc ()
{
}
public NLIZstPmDataSibtc (java.lang.Object paramObj,NLIExtendedSoapSerializationEnvelope __envelope)
{
if (paramObj == null)
return;
AttributeContainer inObj=(AttributeContainer)paramObj;
if(inObj instanceof SoapObject)
{
SoapObject soapObject=(SoapObject)inObj;
int size = soapObject.getPropertyCount();
for (int i0=0;i0< size;i0++)
{
//if you have compilation error here, please use a ksoap2.jar and ExKsoap2.jar from libs folder (in the generated zip file)
PropertyInfo info=soapObject.getPropertyInfo(i0);
java.lang.Object obj = info.getValue();
if (info.name.equals("CodBarras"))
{
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.CodBarras = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.CodBarras = (String)obj;
}
continue;
}
if (info.name.equals("NewCodBarras"))
{
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.NewCodBarras = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.NewCodBarras = (String)obj;
}
continue;
}
if (info.name.equals("NumSerie"))
{
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.NumSerie = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.NumSerie = (String)obj;
}
continue;
}
if (info.name.equals("Lote"))
{
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.Lote = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.Lote = (String)obj;
}
continue;
}
if (info.name.equals("CapaCloro"))
{
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.CapaCloro = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.CapaCloro = (String)obj;
}
continue;
}
if (info.name.equals("TaraReal"))
{
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.TaraReal = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.TaraReal = (String)obj;
}
continue;
}
if (info.name.equals("TipoRecipi"))
{
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.TipoRecipi = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.TipoRecipi = (String)obj;
}
continue;
}
if (info.name.equals("TaraImpresa"))
{
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.TaraImpresa = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.TaraImpresa = (String)obj;
}
continue;
}
if (info.name.equals("FchPruHidro"))
{
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.FchPruHidro = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.FchPruHidro = (String)obj;
}
continue;
}
if (info.name.equals("FchNextPrueba"))
{
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.FchNextPrueba = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.FchNextPrueba = (String)obj;
}
continue;
}
if (info.name.equals("TaraNueva"))
{
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.TaraNueva = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.TaraNueva = (String)obj;
}
continue;
}
if (info.name.equals("Estacion"))
{
if (obj != null && obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.Estacion = j.toString();
}
}
else if (obj!= null && obj instanceof String){
this.Estacion = (String)obj;
}
continue;
}
}
}
}
@Override
public java.lang.Object getProperty(int propertyIndex) {
//!!!!! If you have a compilation error here then you are using old version of ksoap2 library. Please upgrade to the latest version.
//!!!!! You can find a correct version in Lib folder from generated zip file!!!!!
if(propertyIndex==0)
{
return CodBarras;
}
if(propertyIndex==1)
{
return NewCodBarras;
}
if(propertyIndex==2)
{
return NumSerie;
}
if(propertyIndex==3)
{
return Lote;
}
if(propertyIndex==4)
{
return CapaCloro;
}
if(propertyIndex==5)
{
return TaraReal;
}
if(propertyIndex==6)
{
return TipoRecipi;
}
if(propertyIndex==7)
{
return TaraImpresa;
}
if(propertyIndex==8)
{
return FchPruHidro;
}
if(propertyIndex==9)
{
return FchNextPrueba;
}
if(propertyIndex==10)
{
return TaraNueva;
}
if(propertyIndex==11)
{
return Estacion;
}
return null;
}
@Override
public int getPropertyCount() {
return 12;
}
@Override
public void getPropertyInfo(int propertyIndex, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo info)
{
if(propertyIndex==0)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "CodBarras";
info.namespace= "";
}
if(propertyIndex==1)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "NewCodBarras";
info.namespace= "";
}
if(propertyIndex==2)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "NumSerie";
info.namespace= "";
}
if(propertyIndex==3)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "Lote";
info.namespace= "";
}
if(propertyIndex==4)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "CapaCloro";
info.namespace= "";
}
if(propertyIndex==5)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "TaraReal";
info.namespace= "";
}
if(propertyIndex==6)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "TipoRecipi";
info.namespace= "";
}
if(propertyIndex==7)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "TaraImpresa";
info.namespace= "";
}
if(propertyIndex==8)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "FchPruHidro";
info.namespace= "";
}
if(propertyIndex==9)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "FchNextPrueba";
info.namespace= "";
}
if(propertyIndex==10)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "TaraNueva";
info.namespace= "";
}
if(propertyIndex==11)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "Estacion";
info.namespace= "";
}
}
@Override
public void setProperty(int arg0, java.lang.Object arg1)
{
}
}
| true |
a4f9efa513ccae888bb8ea55fd0c14c8c719af25 | Java | ibnuwm/demo-api | /src/main/java/com/domain/models/repos/RekeningRepo.java | UTF-8 | 261 | 1.90625 | 2 | [] | no_license | package com.domain.models.repos;
import com.domain.models.entities.Rekening;
import org.springframework.data.repository.CrudRepository;
public interface RekeningRepo extends CrudRepository<Rekening, Long> {
public Rekening findByNorek(String norek);
}
| true |
66451a688755e0aa1dc7a66c95732f3046a4ce72 | Java | xkohou14/tictactoe-ai | /src/tictactoe_ai/gui/IBoard.java | UTF-8 | 283 | 2.375 | 2 | [] | no_license | package tictactoe_ai.gui;
import tictactoe_ai.game.IGameState;
import tictactoe_ai.game.IPlayer;
public interface IBoard {
public void setState(IGameState state);
public void setFirstPlayer(IPlayer player);
public void setSecondPlayer(IPlayer player);
public void run();
}
| true |
547a9136ccf3bd074c6784e71e339d0365a7d3d1 | Java | rochamc/ProjetoWebCadastroNotas | /src/br/com/fiap/aplicacao/Util.java | UTF-8 | 372 | 2.359375 | 2 | [] | no_license | package br.com.fiap.aplicacao;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Util {
public static Date stringToDate(String data)
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try {
return sdf.parse(data);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}
| true |
f2b1e5988c0e5957f8f6b38926951536a8b10231 | Java | LukasVyhlidka/vocards-android | /Vocards/src/cz/cvut/fit/vyhliluk/vocards/util/StorageUtil.java | UTF-8 | 2,151 | 2.59375 | 3 | [] | no_license | package cz.cvut.fit.vyhliluk.vocards.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Context;
import android.os.Environment;
public class StorageUtil {
//================= STATIC ATTRIBUTES ======================
public static final String SD_CARD_ROOT_DIR = "/Android/data/";
public static final String SD_CARD_TMP = "/tmp";
//================= INSTANCE ATTRIBUTES ====================
//================= STATIC METHODS =========================
public static File getExternalTempDir(Context ctx) {
String packageName = ctx.getPackageName();
File externalPath = Environment.getExternalStorageDirectory();
return new File(externalPath.getAbsolutePath() + SD_CARD_ROOT_DIR
+ packageName + SD_CARD_TMP);
}
public static String readEntireFile(File f) throws IOException {
FileReader in = new FileReader(f);
StringBuilder contents = new StringBuilder();
char[] buffer = new char[4096];
int read = 0;
do {
contents.append(buffer, 0, read);
read = in.read(buffer);
} while (read >= 0);
return contents.toString();
}
public static String readStream(InputStream is) throws IOException {
InputStreamReader isr = new InputStreamReader(is);
StringBuilder contents = new StringBuilder();
char[] buffer = new char[4096];
int read = 0;
do {
contents.append(buffer, 0, read);
read = isr.read(buffer);
} while (read >= 0);
isr.close();
return contents.toString();
}
//================= CONSTRUCTORS ===========================
//================= OVERRIDEN METHODS ======================
//================= INSTANCE METHODS =======================
//================= PRIVATE METHODS ========================
//================= GETTERS/SETTERS ========================
//================= INNER CLASSES ==========================
}
| true |
204df7cee0663ac3f7c0e148027b5235a79e315f | Java | AmadorFernandez/SegundoDAM | /ACDAC/relaciones/RelacionFicheros/app/src/main/java/com/amador/relacionficheros/SerialiceFriend.java | UTF-8 | 3,151 | 3.21875 | 3 | [] | no_license | package com.amador.relacionficheros;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
//Clase para serializar los amigos y guardarlos en el fichero
public class SerialiceFriend {
//Campos
private String path;
private String filename;
//Const
public final static String ERROR_IO_MSG = "Error en la escritura";
public final static String SAVE_OK_MSG = "Tu amiguete ha sido guardado";
public final static int SAVE_OK_CODE = 0;
public final static int ERROR_IO_CODE = 1;
//Getters and setters
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
//Constructor
public SerialiceFriend(String path, String filename) {
this.path = path;
this.filename = filename;
}
//Métodos
public int saveFriend(){
int result = SAVE_OK_CODE;
File file = new File(this.path, this.filename);
ObjectOutputStream outputStream = null;
try {
outputStream = new ObjectOutputStream(new FileOutputStream(file));
//Guarda todos los objetos que esten en la lista
for (int i = 0; i < Diary.getDiary().size(); i++){
outputStream.writeObject(Diary.getDiary().get(i));
}
} catch (IOException e) {
result = ERROR_IO_CODE;
}finally {
if(outputStream != null){
try {
outputStream.close();
} catch (IOException e) {
}
}
}
return result;
}
public void extractDiary(){
File file = new File(this.path, this.filename);
ObjectInputStream objectInputStream = null;
boolean flag = false;
Diary.getDiary().clear(); //Limpia la lista para evitar repeticiones
try {
//Si es la primera vez que se ha iniciado la app en el dispositivo creamos el fichero
if(!file.exists()){
file.createNewFile();
flag = true; //La bandera nos avisa de si es la primera vez que se inicio la app
}
//Si no es la primera vez ya podemos intentar una lectura
if(!flag) {
objectInputStream = new ObjectInputStream(new FileInputStream(file));
//Saldrá del bucle cuando se produzca la excepcion
while (true) {
//Añade objetos a la lista
Diary.getDiary().add((Friend) objectInputStream.readObject());
}
}
} catch (Exception e) {
try {
//Cierra el flujo y de estar a null se controla en el catch
objectInputStream.close();
} catch (Exception e1) {
}
}
}
}
| true |
a6b2f46ac055e132d6c4840ac14b32ea12c3a00a | Java | EloyGutierrez/MediCit | /app/src/main/java/moviles/aplicaciones/medicit/utilidades/ListAdapterCita.java | UTF-8 | 1,879 | 2.078125 | 2 | [] | no_license | package moviles.aplicaciones.medicit.utilidades;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import moviles.aplicaciones.medicit.R;
import moviles.aplicaciones.medicit.SpidetucitaActivity;
import moviles.aplicaciones.medicit.entidades.Cita;
import moviles.aplicaciones.medicit.entidades.Medicos;
public class ListAdapterCita extends ArrayAdapter<Cita> {
private List<Cita> myList;
private Context myContext;
private int resourceLayout;
public ListAdapterCita(@NonNull Context context, int resource,List<Cita> objects) {
super(context, resource, objects);
this.myList= objects;
this.myContext= context;
this.resourceLayout =resource;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View view= convertView;
if (view==null)
view= LayoutInflater.from(myContext).inflate(resourceLayout,null);
Cita cita= myList.get(position);
TextView medico = view.findViewById(R.id.EDTMEDICO);
medico.setText("Detalles");
TextView precio = view.findViewById(R.id.EDTPRECIO);
precio.setText(cita.getPrecio());
TextView especialidad = view.findViewById(R.id.EDTESPECIALIDAD1);
especialidad.setText(cita.getEspecialidad());
TextView fecha = view.findViewById(R.id.EDTFECHA);
fecha.setText(cita.getFecha());
return view;
}
}
| true |
bce9737695758e14168f84521716547c19fe0a10 | Java | karlchan-cn/scaffold | /scaffold/service/src/test/java/com/scaffold/hzm/service/TicketServiceImplTest.java | UTF-8 | 1,430 | 1.992188 | 2 | [
"Apache-2.0"
] | permissive | package com.scaffold.hzm.service;
import com.alibaba.fastjson.JSON;
import com.scaffold.hzm.domain.*;
import org.junit.Test;
import static org.junit.Assert.*;
public class TicketServiceImplTest {
TicketService service = new TicketServiceImpl();
@Test
public void login() {
getLoginUser();
}
private LoginUser getLoginUser() {
LoginUserReq loginUser = JSON.parseObject("{\"webUserid\":\"277588464@qq.com\",\"passWord\":\"Karl1234\",\"code\":\"\",\"appId\":\"HZMBWEB_HK\",\"joinType\":\"WEB\",\"version\":\"2.7.202204.1115\",\"equipment\":\"PC\"}"
, LoginUserReq.class);
ResultDto<LoginUser> userResultDto = service.login(loginUser);
assertNotNull(userResultDto);
assertNotNull(userResultDto.getResponseData());
assertNotNull(ResultDto.CODE_SUCCESS.equals(userResultDto.getCode()));
userResultDto.getResponseData().setJwt(userResultDto.getJwt());
return userResultDto.getResponseData();
}
@Test
public void bookInfo() {
LoginUser loginUser = getLoginUser();
BookInfoReq bookinfoReq = JSON.parseObject("{\"bookDate\":\"2022-06-19\",\"lineCode\":\"HKGZHO\",\"appId\":\"HZMBWEB_HK\",\"joinType\":\"WEB\",\"version\":\"2.7.202206.1121\",\"equipment\":\"PC\"}"
, BookInfoReq.class);
assertNotNull(service.getBookInfo(bookinfoReq, loginUser));
}
} | true |
202aa99f433031f39a526e0cc0e7311dc6fa558e | Java | satishrwadde/HybridMavenAndroid | /Hybrid_Maven/src/test/java/ecommerce/hybrid/testrunner/HybridTestRunner.java | UTF-8 | 3,241 | 2.1875 | 2 | [] | no_license | package ecommerce.hybrid.testrunner;
import org.testng.annotations.Test;
import ecommerce.hybrid.actions.Capabilities;
import ecommerce.hybrid.beans.LoginPOM;
import ecommerce.hybrid.beans.ProductsPOM;
import ecommerce.hybrid.beans.ShoppingCartPOM;
import ecommerce.hybrid.utils.CaptureScreenshot;
import ecommerce.hybrid.utils.Ecommerce_Utils;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import org.testng.Assert;
import java.net.MalformedURLException;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public class HybridTestRunner extends Capabilities{
public static AndroidDriver <AndroidElement> driver=null;
public static LoginPOM loginPom=null;
public static ProductsPOM productsPom=null;
public static ShoppingCartPOM shoppingCartPom=null;
public static Ecommerce_Utils eUtils=null;
public static CaptureScreenshot captureScreenshot=null;
@BeforeMethod
public void beforeTest() throws MalformedURLException {
System.out.println("***************** In BeforeTest *************");
driver=Capabilities.capability();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
captureScreenshot=new CaptureScreenshot(driver);
eUtils=new Ecommerce_Utils(driver);
loginPom=new LoginPOM(driver);
productsPom=new ProductsPOM(driver);
shoppingCartPom=new ShoppingCartPOM(driver);
}
@Test(enabled=false)
public void TC01() {
try {
String product="Air Jordan 9 Retro";
loginPom.sendCountry("Angola").click();
loginPom.sendName().sendKeys("Shilpa Wadde");
loginPom.sendGender().click();
loginPom.sendButton().click();
productsPom.scrollToProduct(product);
String Actual=productsPom.sendAddToCart(product);
Assert.assertEquals(Actual, "ADDED TO CART");
productsPom.sendCartButton().click();
} catch (Exception e) {
// e.printStackTrace();
captureScreenshot.screenshot();
}
}
@Test
public void TC03(){
try {
loginPom.sendCountry("Angola").click();
loginPom.sendName().sendKeys("Shilpa Wadde");
loginPom.sendGender().click();
loginPom.sendButton().click();
productsPom.sendAddToCart2Products();
productsPom.sendCartButton().click();
List<Float> list=shoppingCartPom.validatePrices();
System.out.println("Final price on screen : "+list.get(0)+" Sum of price of products : "+list.get(1));
Assert.assertEquals(list.get(0), list.get(1));
eUtils.tapElement();
// eUtils.longPressElement();
} catch (Exception e) {
e.printStackTrace();
// captureScreenshot.screenshot();
}
}
@Test(enabled=false)
public void TC02() {
try {
loginPom.sendCountry("Bhutan").click();
loginPom.sendGender().click();
loginPom.sendButton().click();
String error=productsPom.sendAndroidWidget(1).getAttribute("name");
System.out.println(error);
Assert.assertEquals(error,"Please enter your name");
} catch (Exception e) {
// e.printStackTrace();
captureScreenshot.screenshot();
}
}
@AfterMethod
public void afterTest() {
System.out.println("***************** In AfterTest *************");
}
}
| true |
abfc822c9cf2bc16a7bc7f789161279b5502c72a | Java | test-q/June2020HubSpot | /src/main/java/com/qa/hubspot/base/BasePage.java | UTF-8 | 4,006 | 2.515625 | 3 | [] | no_license | package com.qa.hubspot.base;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.qa.hubspot.utils.OptionsManager;
import io.github.bonigarcia.wdm.WebDriverManager;
/**
*
* @author rupal
*
*/
public class BasePage {
WebDriver driver;
Properties prop;
OptionsManager optionsManager;
public static String flashElement;
public static ThreadLocal<WebDriver> tlDriver = new ThreadLocal<WebDriver>();
/**
* This method is used to initialize the WebDriver on the basis of given browser name
* @param Pass Properties
* @return This method return driver
*/
public WebDriver init_driver(Properties prop) {
flashElement = prop.getProperty("highlights").trim();
String browserName = prop.getProperty("browser");
System.out.println("Browser Name is: " + browserName);
optionsManager = new OptionsManager(prop);
if (browserName.equalsIgnoreCase("chrome")) {
WebDriverManager.chromedriver().setup();
//driver = new ChromeDriver(optionsManager.getChromeOptions());
tlDriver.set(new ChromeDriver(optionsManager.getChromeOptions()));;
}
else if (browserName.equalsIgnoreCase("firefox")) {
WebDriverManager.firefoxdriver().setup();
//driver = new FirefoxDriver(optionsManager.getFirefoxOptions());
tlDriver.set(new FirefoxDriver(optionsManager.getFirefoxOptions()));
}
else {
System.out.println("Please Pass The Correct Browser Name : " + browserName);
}
getDriver().manage().deleteAllCookies();
getDriver().manage().window().maximize();
getDriver().manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
getDriver().get("https://app.hubspot.com/login");
return getDriver();
}
/**
*
* @return This method written synchronized ThreadLocal WebDriver
*/
public static synchronized WebDriver getDriver() {
return tlDriver.get();
}
/**
* This method is used to get properties value form Config.properties file
* @return it return prop
*/
public Properties init_prop() {
prop = new Properties();
String path = null;
String env = null;
try {
env = System.getProperty("env");
System.out.println("Running on Envirnment: " + env);
if(env == null) {
System.out.println("Running on Envirnment: " + "PROD");
path = "D:\\Rupali\\Workspace\\June2020HubSpot\\src\\main\\java\\com\\qa\\hubspot\\config\\Config.prod.properties";
}else {
switch (env) {
case "qa":
path = "D:\\Rupali\\Workspace\\June2020HubSpot\\src\\main\\java\\com\\qa\\hubspot\\config\\Config.qa.properties";
break;
case "dev":
path = "D:\\Rupali\\Workspace\\June2020HubSpot\\src\\main\\java\\com\\qa\\hubspot\\config\\Config.dev.properties";
break;
case "stage":
path = "D:\\Rupali\\Workspace\\June2020HubSpot\\src\\main\\java\\com\\qa\\hubspot\\config\\Config.stage.properties";
break;
default:
System.out.println("Please Pass the Correct Env Value...");
break;
}
}
FileInputStream finput = new FileInputStream(path);
prop.load(finput);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return prop;
}
/**
* This method take screenshot
* @return path of screenshot
*/
public String getScreenshot() {
File src = ((TakesScreenshot) getDriver()).getScreenshotAs(OutputType.FILE);
String path = System.getProperty("user.dir")+"/screenshots/"+System.currentTimeMillis()+".png";
File destination = new File(path);
try {
FileUtils.copyFile(src, destination);
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
}
| true |
296ebeced3e0c0ca9ccda6911ce2c8c35a3e3c13 | Java | mauromontano/Compilador | /src/etapa4/AccesoEstatico.java | UTF-8 | 315 | 2.078125 | 2 | [] | no_license | package etapa4;
import etapa1.Token;
public class AccesoEstatico extends Acceso{
private AccesoMetodo actMet;
public AccesoEstatico(Token t) {
super(t);
}
public AccesoMetodo getAccesoMet() {
return actMet;
}
public void setAccesoMet(AccesoMetodo actMet) {
this.actMet = actMet;
}
}
| true |
11e79423149ff01b37fd40e4f149e35e72ac7ea4 | Java | hgvanpariya/IPXact-ECore-Object | /IPXACT-ECore/src/org/spiritconsortium/xml/schema/spirit/_1685/_2009/FileSetRefGroupType.java | UTF-8 | 2,629 | 1.671875 | 2 | [] | no_license | /**
*/
package org.spiritconsortium.xml.schema.spirit._1685._2009;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>File Set Ref Group Type</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.spiritconsortium.xml.schema.spirit._1685._2009.FileSetRefGroupType#getGroup <em>Group</em>}</li>
* <li>{@link org.spiritconsortium.xml.schema.spirit._1685._2009.FileSetRefGroupType#getFileSetRef <em>File Set Ref</em>}</li>
* </ul>
* </p>
*
* @see org.spiritconsortium.xml.schema.spirit._1685._2009._2009Package#getFileSetRefGroupType()
* @model extendedMetaData="name='fileSetRefGroup_._1_._type' kind='elementOnly'"
* @generated
*/
public interface FileSetRefGroupType extends EObject {
/**
* Returns the value of the '<em><b>Group</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* Abritray name assigned to the collections of fileSets.
* <!-- end-model-doc -->
* @return the value of the '<em>Group</em>' attribute.
* @see #setGroup(String)
* @see org.spiritconsortium.xml.schema.spirit._1685._2009._2009Package#getFileSetRefGroupType_Group()
* @model dataType="org.eclipse.emf.ecore.xml.type.Name"
* extendedMetaData="kind='element' name='group' namespace='##targetNamespace'"
* @generated
*/
String getGroup();
/**
* Sets the value of the '{@link org.spiritconsortium.xml.schema.spirit._1685._2009.FileSetRefGroupType#getGroup <em>Group</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Group</em>' attribute.
* @see #getGroup()
* @generated
*/
void setGroup(String value);
/**
* Returns the value of the '<em><b>File Set Ref</b></em>' containment reference list.
* The list contents are of type {@link org.spiritconsortium.xml.schema.spirit._1685._2009.FileSetRefType}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* <!-- begin-model-doc -->
* A reference to a fileSet.
* <!-- end-model-doc -->
* @return the value of the '<em>File Set Ref</em>' containment reference list.
* @see org.spiritconsortium.xml.schema.spirit._1685._2009._2009Package#getFileSetRefGroupType_FileSetRef()
* @model containment="true"
* extendedMetaData="kind='element' name='fileSetRef' namespace='##targetNamespace'"
* @generated
*/
EList<FileSetRefType> getFileSetRef();
} // FileSetRefGroupType
| true |
904edc321a4a1c2df7ba399a84fa1013bbad5762 | Java | danstiner/college-assignments | /meetingpoints/src/com/danielstiner/meetingpoints/NodeExploreVisitor.java | UTF-8 | 612 | 2.890625 | 3 | [] | no_license | package com.danielstiner.meetingpoints;
import java.util.Collection;
import java.util.HashSet;
public class NodeExploreVisitor implements INodeExploreVisitor {
private boolean mTravelReversed = false;
private HashSet<INode> mExplored;
@Override
public boolean visit(Node junction) {
return mExplored.add(junction);
}
@Override
public boolean travelReversed() {
return mTravelReversed;
}
@Override
public Collection<INode> explore(INode node, boolean travelReversed) {
mExplored = new HashSet<INode>();
mTravelReversed = travelReversed;
node.accept(this);
return mExplored;
}
}
| true |
a7efeb3728030a6241579f379c14af2b6719b790 | Java | maru-pork/ExpenseManager | /app/src/main/java/com/nnayram/expensemanager/activity/BudgetDetailActivity.java | UTF-8 | 9,712 | 2.09375 | 2 | [] | no_license | package com.nnayram.expensemanager.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.nnayram.expensemanager.R;
import com.nnayram.expensemanager.core.ExpenseApplication;
import com.nnayram.expensemanager.core.Pageable;
import com.nnayram.expensemanager.model.Budget;
import com.nnayram.expensemanager.model.BudgetDetail;
import com.nnayram.expensemanager.util.DateUtil;
import com.nnayram.expensemanager.view.DialogAddBudgetDetail;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Rufo on 1/23/2017.
*/
public class BudgetDetailActivity extends BaseActivity implements View.OnClickListener {
private Budget budget;
private TextView tvBalance;
private TextView tvPageCount;
private TableLayout tblMain;
private TableRow trTranHeader, trTranRow;
private TextView tvTranRowID, tvTranRow;
private LinearLayout lytLineSeparator;
private Pageable<BudgetDetail> pageableBudgetDetail;
private List<BudgetDetail> budgetDetailList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_budget_detail);
Long budgetId = getIntent().getLongExtra("BUDGET_ID", 0L);
budget = ExpenseApplication.getInstance().getDbReader().getBudget(Long.valueOf(budgetId));
setTitle(budget.getDescription().toUpperCase());
super.initializeToolbar();
super.setCurrentContext(this);
init();
}
private void init() {
tblMain = (TableLayout) findViewById(R.id.tbl_budget_details);
trTranHeader = (TableRow) findViewById(R.id.tr_budget_tranHeader);
tvTranRowID = (TextView) findViewById(R.id.tv_budget_tranRow);
tvBalance = (TextView) findViewById(R.id.tv_budget_balance);
tvPageCount = (TextView) findViewById(R.id.tv_budget_tranPageCount);
findViewById(R.id.btn_budget_delete).setOnClickListener(this);
findViewById(R.id.btn_budget_add_detail).setOnClickListener(this);
findViewById(R.id.btn_next).setOnClickListener(this);
findViewById(R.id.btn_previous).setOnClickListener(this);
refreshDisplay();
}
private void refreshDisplay() {
budget = ExpenseApplication.getInstance().getDbReader().getBudget(Long.valueOf(budget.getId()));
tvBalance.setText(budget.getFormattedTotalAmount());
budgetDetailList = new ArrayList<>();
budgetDetailList.addAll(ExpenseApplication.getInstance().getDbReader().getBudgetDetails(budget.getId()));
pageableBudgetDetail = new Pageable<>(budgetDetailList);
pageableBudgetDetail.setPageSize(10);
pageableBudgetDetail.setPage(1);
tvPageCount.setText(getString(R.string.page_of, pageableBudgetDetail.getPage(), pageableBudgetDetail.getMaxPages()));
refreshMainTable();
}
private void refreshMainTable() {
tblMain.removeAllViews();
tblMain.addView(trTranHeader);
for (final BudgetDetail budgetDetail : pageableBudgetDetail.getListForPage()) {
trTranRow = new TableRow(this);
trTranRow.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT));
trTranRow.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(BudgetDetailActivity.this);
alertDialogBuilder.setMessage("Are you sure you want to delete detail? " + budgetDetail.getDescription() + "["+ budgetDetail.getFormattedAmount() +"]");
alertDialogBuilder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ExpenseApplication.getInstance().getDbReader().deleteBudgetDetail(budgetDetail.getId());
refreshDisplay();
}
});
alertDialogBuilder.setNegativeButton("Close", null);
alertDialogBuilder.show();
return false;
}
});
// Transaction Date
tvTranRow = new TextView(this);
tvTranRow.setLayoutParams(tvTranRowID.getLayoutParams());
tvTranRow.setGravity(Gravity.CENTER_HORIZONTAL);
tvTranRow.setText(DateFormat.format(DateUtil.DATE_PATTERN, budgetDetail.getDate()));
trTranRow.addView(tvTranRow);
// Transaction Type
tvTranRow = new TextView(this);
tvTranRow.setLayoutParams(tvTranRowID.getLayoutParams());
tvTranRow.setGravity(Gravity.CENTER_HORIZONTAL);
tvTranRow.setText(budgetDetail.getType());
trTranRow.addView(tvTranRow);
// Description
tvTranRow = new TextView(this);
tvTranRow.setLayoutParams(tvTranRowID.getLayoutParams());
tvTranRow.setGravity(Gravity.LEFT);
tvTranRow.setText(budgetDetail.getDescription());
trTranRow.addView(tvTranRow);
// Amount
tvTranRow = new TextView(this);
tvTranRow.setLayoutParams(tvTranRowID.getLayoutParams());
tvTranRow.setGravity(Gravity.RIGHT);
tvTranRow.setText(budgetDetail.getFormattedAmount());
trTranRow.addView(tvTranRow);
// Line Separator
lytLineSeparator = new LinearLayout(this);
lytLineSeparator.setOrientation(LinearLayout.VERTICAL);
lytLineSeparator.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 2));
lytLineSeparator.setBackgroundColor(Color.parseColor("#5e7974"));
tblMain.addView(trTranRow);
tblMain.addView(lytLineSeparator);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_next:
pageableBudgetDetail.setPage(pageableBudgetDetail.getNextPage());
if (!budgetDetailList.isEmpty()) {
trTranRow.removeAllViews();
}
refreshMainTable();
tvPageCount.setText(getString(R.string.page_of, pageableBudgetDetail.getPage(), pageableBudgetDetail.getMaxPages()));
break;
case R.id.btn_previous:
pageableBudgetDetail.setPage(pageableBudgetDetail.getPreviousPage());
if (!budgetDetailList.isEmpty()) {
trTranRow.removeAllViews();
}
refreshMainTable();
tvPageCount.setText(getString(R.string.page_of, pageableBudgetDetail.getPage(), pageableBudgetDetail.getMaxPages()));
break;
case R.id.btn_budget_delete:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to remove budget: " + budget.getDescription() +"?");
alertDialogBuilder.setCancelable(false);
alertDialogBuilder.setPositiveButton("Remove", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ExpenseApplication.getInstance().getDbReader().deleteBudget(budget.getId());
Intent intent = new Intent(BudgetDetailActivity.this, BudgetActivity.class);
startActivity(intent);
}
});
alertDialogBuilder.setNegativeButton("Close", null);
alertDialogBuilder.show();
break;
case R.id.btn_budget_add_detail:
new DialogAddBudgetDetail(this) {
@Override
public void setAddOnClickAction(BudgetDetail budgetDetail) {
try {
if (StringUtils.isEmpty(budgetDetail.getType())
|| StringUtils.isEmpty(budgetDetail.getDescription())
|| budgetDetail.getAmount().compareTo(BigDecimal.ZERO) == 0)
throw new IllegalArgumentException("Invalid input.");
ExpenseApplication.getInstance().getDbReader().addBudgetDetail(
budget.getId(),
budgetDetail.getDate(),
budgetDetail.getType(),
budgetDetail.getDescription(),
budgetDetail.getAmount());
refreshDisplay();
dismiss();
} catch (Exception e) {
Toast.makeText(BudgetDetailActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}.show();
break;
}
}
}
| true |
cf67d8daba16b99f3a605ad75323513c34ba6b74 | Java | dotcompany/SISTEMA-ERP-EM-JAVA-GWT-VAADIN | /src/main/java/dc/servicos/dao/suprimentos/estoque/INFeFaturaDAO.java | UTF-8 | 307 | 1.578125 | 2 | [] | no_license | package dc.servicos.dao.suprimentos.estoque;
import dc.entidade.suprimentos.NfeFatura;
import dc.entidade.suprimentos.estoque.NotaFiscal;
import dc.model.dao.AbstractDAO;
public interface INFeFaturaDAO extends AbstractDAO<NfeFatura> {
NfeFatura buscaFaturaPorNota(NotaFiscal currentBean);
}
| true |
a7bfe206d1243f518b03a66c5bc7498714b5c1b9 | Java | DrawBlack/Think-in-java | /src/com/fengshan/Thread/DeamonThreadFactory.java | UTF-8 | 338 | 2.40625 | 2 | [] | no_license | package com.fengshan.Thread;
import java.util.concurrent.ThreadFactory;
/**
* Created by macbookpro on 2016/9/12.
*/
public class DeamonThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread thread=new Thread(r);
thread.setDaemon(true);
return thread;
}
}
| true |
69831a1c320ba7fa403aa437c860e51c145c2f4e | Java | Ritesh616/Final_Website | /Bootcampp/src/main/java/com/Bootcampp/service/EmailService.java | UTF-8 | 221 | 1.585938 | 2 | [] | no_license | package com.Bootcampp.service;
import com.Bootcampp.model.Email;
public interface EmailService {
boolean saveEmail(Email email);
static Object getEmails() {
// TODO Auto-generated method stub
return null;
}
}
| true |
fb2a254d10613b38ca1a8d42ab2e1675e258d073 | Java | lixiao1k/Lexical-Analyzer | /src/LogicHelper.java | UTF-8 | 5,092 | 3.015625 | 3 | [] | no_license | import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
/**
* Created by shelton on 2017/10/26.
*/
public class LogicHelper {
DataHelper dataHelper;
private char pro[],token[];//pro数组持有程序,token用于暂存词素
private int p = 0, syn = 0, pro_len=0,m;//p是遍历指针,syn持有状态值,pro_len是程序的长度
public LogicHelper(){
dataHelper = new DataHelper();
token = new char[50];
initToken();
initPro();
}
private void initPro(){
try {
ArrayList<String> pro_String_list= dataHelper.readFile("input/Input.txt");
int list_len = pro_String_list.size();
String pro_string = "";
for(int i=0;i<list_len;i++){
pro_string += pro_String_list.get(i);
}
pro = pro_string.toCharArray();
pro_len = pro.length;
} catch (IOException e) {
e.printStackTrace();
}
}
private void initToken(){
for(int i=0;i<50;i++){
token[i]=' ';
}
}
private String charToString(char[] charArray){
String result = "";
for(int i=0;i < charArray.length;i++){
if(charArray[i]!=' '){
result += String.valueOf(charArray[i]);
}
}
return result;
}
private void scanner(){
initToken();
char ch;
ch = pro[p++];
while((ch == ' ')||(ch == '\n')||(ch == '\t')){
ch = pro[p++];
}
if((ch >= 'a' && ch <= 'z')||(ch >= 'A' && ch <= 'Z')){//判断标识符
m=0;
while((ch >= 'a' && ch<='z')||(ch >= 'A' && ch <= 'Z')||(ch >='0' && ch <= '9')){
token[m++] = ch;
if(p == pro_len){
break;
}
ch = pro[p++];
}
p--;
String candidate = charToString(token);
syn = 1;
int tag = dataHelper.isKeyWord(candidate);//判断关键字
if(tag > 0){
syn = tag;
}
}
else if(ch >= '0' && ch <= '9'){//判断数字
m = 0;
while(ch >= '0' && ch <= '9'){
token[m++] = ch;
if(p == pro_len){
break;
}
ch = pro[p++];
}
if(ch == '.'){//double
token[m++] = ch;
ch = pro[p++];
while(ch >= '0' && ch <= '9'){
if(p == pro_len){
break;
}
token[m++] = ch;
ch = pro[p++];
}
p--;
syn = 2;//double
}else{
p--;
syn =3;//int
}
}
else{
if(p == pro_len && dataHelper.isToken(ch) == -1){
syn = -1;//如果程序结尾不是界符的话,就报错。
return;
}
m = 0;
int tag = dataHelper.isToken(ch);
if(tag > 0){
syn = tag;
token[m++] = ch;
if(p!=pro_len){
ch = pro[p++];
int tag1 = dataHelper.transState(tag,ch);//双目操作符状态转换
if(tag1 > 0){
syn = tag1;
token[m++] = ch;
}else{
p--;
}
}
}else{
syn = -1;
}
}
}
private void output(FileWriter fileWriter,String style,char[] token){
String s = "";
s = "<" + style + "," + charToString(token) + ">\n";
try {
fileWriter.write(s);
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(s);
}
public void run() throws IOException {
File resultFile = new File("result/Output.txt");
FileWriter fileWriter = new FileWriter(resultFile);
while(p!=pro_len){
scanner();
if(syn == 1){
output(fileWriter,"ID",token);
}else if(syn == 2){
output(fileWriter,"DOUBLE",token);
}else if(syn == 3){
output(fileWriter,"INT",token);
}else if(syn >= 4 && syn <= 51){
output(fileWriter,"KEYWORD",token);
}else if((syn>=64 && syn<=70)||syn == 73||syn==74||syn==77){
output(fileWriter,"DELIMITER",token);
}else if(syn != -1){
output(fileWriter,"OPERATOR",token);
}else{
fileWriter.write("error\n");
System.out.println("error");
}
}
fileWriter.close();
}
//======for test=========
public char[] getPro(){
return pro;
}
public int getPro_len(){
return pro_len;
}
}
| true |
aa640f150fd6efb32d3bd92b654e4478f024d015 | Java | Yuva11/hb_admin | /src/newservice/RoadRunnerLoginVo.java | UTF-8 | 756 | 2.078125 | 2 | [] | no_license | package newservice;
public class RoadRunnerLoginVo {
private String expires_at;
private String token_type;
private String access_token;
public String getExpires_at() {
return expires_at;
}
public void setExpires_at(String expires_at) {
this.expires_at = expires_at;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
@Override
public String toString() {
return "ClassPojo [expires_at = " + expires_at + ", token_type = "
+ token_type + ", access_token = " + access_token + "]";
}
}
| true |
38bc95a34936fb1cc5b8c2d8810907968d3c5a3f | Java | martinMamani/cursojavase | /src/ar/com/eduit/curso/java/entities/ClienteEmpresa.java | UTF-8 | 1,320 | 2.59375 | 3 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ar.com.eduit.curso.java.entities;
import java.util.ArrayList;
/**
*
* @author EducaciónIT
*/
public class ClienteEmpresa {
private int nro;
private String razonSocial;
private String direccin;
private ArrayList<Cuenta> cuentas;
//Cuenta[] cuentas= new Cuenta[10];//cuando definimos un vector tenemos que decir la longitud
public ClienteEmpresa(int nro, String razonSocial, String direccin) {
this.nro = nro;
this.razonSocial = razonSocial;
this.direccin = direccin;
this.cuentas= new ArrayList();
}
@Override
public String toString() {
return "ClienteEmpresa{" + "nro=" + nro + ", razonSocial=" + razonSocial + ", direccin=" + direccin + '}';
}
public int getNro() {
return nro;
}
public String getRazonSocial() {
return razonSocial;
}
public String getDireccin() {
return direccin;
}
public ArrayList<Cuenta> getCuentas() {
return cuentas;
}
}
| true |
f15b05adcebe0a44dab935f3f1f7560797f3a804 | Java | tusharupadhyay/BansiMarutiService | /src/main/java/com/bmsm/jpa/repositories/EmployeeRepository.java | UTF-8 | 387 | 2.015625 | 2 | [] | no_license | package com.bmsm.jpa.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.bmsm.common.entities.Employee;
public interface EmployeeRepository extends JpaRepository<Employee, Integer>{
public List<Employee> findByFirstNameIgnoreCase(String firstName);
public List<Employee> findByLastNameIgnoreCase(String lastName);
}
| true |
a9f1fbed5823a22c0bd7a66e4ac0a9a6c1b12da7 | Java | P79N6A/icse_20_user_study | /methods/Method_8414.java | UTF-8 | 709 | 1.921875 | 2 | [] | no_license | @Override public void dismiss(){
super.dismiss();
NotificationCenter.getInstance(currentAccount).removeObserver(this,NotificationCenter.messagePlayingDidReset);
NotificationCenter.getInstance(currentAccount).removeObserver(this,NotificationCenter.messagePlayingPlayStateChanged);
NotificationCenter.getInstance(currentAccount).removeObserver(this,NotificationCenter.messagePlayingDidStart);
NotificationCenter.getInstance(currentAccount).removeObserver(this,NotificationCenter.messagePlayingProgressDidChanged);
NotificationCenter.getInstance(currentAccount).removeObserver(this,NotificationCenter.musicDidLoad);
DownloadController.getInstance(currentAccount).removeLoadingFileObserver(this);
}
| true |
e2ada3e8a674f2853709f2a025b11f8dbb9db57f | Java | MoritzGoeckel/Algorithms | /src/main/java/Sorting/InsertionSort.java | UTF-8 | 499 | 3.265625 | 3 | [] | no_license | package Sorting;
public class InsertionSort<T extends Comparable> implements SortingAlgorithm<T> {
public void sort(T[] input) {
for(int i = 1; i < input.length; i++) {
for (int switchIndex = i; switchIndex > 0 && input[switchIndex].compareTo(input[switchIndex - 1]) < 0; switchIndex--) {
T tmp = input[switchIndex - 1];
input[switchIndex - 1] = input[switchIndex];
input[switchIndex] = tmp;
}
}
}
}
| true |
d52b18d9f3c48a40d19cda0447c2e435de0fd994 | Java | RyanTech/WalkFun_android | /src/com/G5432/WalkFun/User/UserMainActivity.java | UTF-8 | 7,246 | 1.992188 | 2 | [] | no_license | package com.G5432.WalkFun.User;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.*;
import com.G5432.DBUtils.DatabaseHelper;
import com.G5432.Entity.PM25DetailInfo;
import com.G5432.Entity.UserBase;
import com.G5432.Entity.WeatherDetailInfo;
import com.G5432.HttpClient.SystemHandler;
import com.G5432.HttpClient.UserHandler;
import com.G5432.Utils.*;
import com.G5432.WalkFun.History.HistoryRunMainActivity;
import com.G5432.WalkFun.R;
import com.G5432.WalkFun.WalkFunBaseActivity;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import java.text.MessageFormat;
import java.util.Date;
/**
* Created with IntelliJ IDEA.
* User: p
* Date: 14-3-25
* Time: 下午12:50
* To change this template use File | Settings | File Templates.
*/
public class UserMainActivity extends WalkFunBaseActivity {
//init UI control
private Button btnTraffic;
private ImageView imgUserInfo;
private TextView txtUserName;
private TextView txtLevel;
public MyLocationListener myListener = new MyLocationListener();
private WalkFunApplication bMapApp = null;
private UserHandler userHandler;
private SystemHandler systemHandler;
private UserBase userBase;
private Integer weatherStatus = 0; //0 获取中 -1天气获取失败。
private String weatherInformation = "天气信息获取中...";
private Integer index = -1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bMapApp = (WalkFunApplication) this.getApplication();
bMapApp.mLocationClient.registerLocationListener(myListener);
setContentView(R.layout.user_main);
Date now = new Date();
long hours = (now.getTime() - UserUtil.getWeatherTime().getTime()) / (60 * 60 * 1000);
if (hours > 1) {
bMapApp.setWeatherLocationOption();
bMapApp.mLocationClient.start();
bMapApp.mLocationClient.requestLocation();
} else {
weatherHandler.sendEmptyMessageDelayed(3, 1000);
}
userHandler = new UserHandler(getHelper());
systemHandler = new SystemHandler(getHelper());
userBase = userHandler.fetchUser(UserUtil.getUserId());
initPageUIControl();
}
private void initPageUIControl() {
btnTraffic = (Button) findViewById(R.id.userMainBtnTrafficlight);
imgUserInfo = (ImageView) findViewById(R.id.userMainImgUserInfo);
txtUserName = (TextView) findViewById(R.id.userMainTxtName);
txtLevel = (TextView) findViewById(R.id.userMainTxtLevel);
txtUserName.setText(userBase.getNickName());
txtLevel.setText("Lv." + userBase.getUserInfo().getLevel().intValue());
imgUserInfo.setOnClickListener(userInfoListener);
btnTraffic.setOnClickListener(trafficLightListener);
}
private View.OnClickListener userInfoListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setClass(UserMainActivity.this, HistoryRunMainActivity.class);
startActivity(intent);
}
};
private View.OnClickListener trafficLightListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
if (weatherStatus == -1) {
ToastUtil.showMessage(getApplicationContext(), "天气信息获取失败");
} else {
ToastUtil.showMessageLong(getApplicationContext(), weatherInformation);
}
}
};
/**
* 监听函数,有更新位置的时候,格式化成字符串,输出到屏幕中
*/
public class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
if (location == null)
return;
if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
String cityName = location.getCity();
String districtName = location.getDistrict();
if (cityName != null || districtName != null) {
if (bMapApp.mLocationClient.isStarted()) bMapApp.mLocationClient.stop();
systemHandler.syncPM25Info(districtName, cityName, weatherHandler);
systemHandler.syncWeatherInfo(CommonUtil.getCityCode(cityName, districtName), weatherHandler);
}
}
}
public void onReceivePoi(BDLocation poiLocation) {
//do nothing
}
}
// 定义Handler
Handler weatherHandler = new Handler() {
WeatherDetailInfo weatherDetailInfo = null;
PM25DetailInfo pm25DetailInfo = null;
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == 1) {
weatherDetailInfo = (WeatherDetailInfo) msg.obj;
} else if (msg.what == 2) {
pm25DetailInfo = (PM25DetailInfo) msg.obj;
} else if (msg.what == 3) {
weatherInformation = UserUtil.getWeatherInfo();
index = UserUtil.getWeatherIndex();
} else {
weatherStatus = 0;
}
if (weatherDetailInfo != null && pm25DetailInfo != null) {
Integer temp = weatherDetailInfo.getTemp();
Integer pm25 = pm25DetailInfo.getAqi();
if (temp != Integer.MIN_VALUE && temp != Integer.MAX_VALUE) {
if (temp < 38 && pm25 < 300) {
index = (int) ((100 - pm25 / 3) * 0.6 + (100 - Math.abs(temp - 22) * 5) * 0.4);
} else {
index = 0;
}
weatherInformation = MessageFormat.format("{0} {1}℃ {2}{3} PM2.5: {4} {5}",
weatherDetailInfo.getCity(), temp, weatherDetailInfo.getWindDirection(), weatherDetailInfo.getWindSpeed(),
pm25, pm25DetailInfo.getQuality());
UserUtil.initWeatherInfo(index, weatherInformation);
}
}
if (index >= 0) {
if (index > 75) {
Drawable drawableBg = getResources().getDrawable(R.drawable.main_trafficlight_green);
btnTraffic.setBackgroundDrawable(drawableBg);
} else if (index < 50) {
Drawable drawableBg = getResources().getDrawable(R.drawable.main_trafficlight_red);
btnTraffic.setBackgroundDrawable(drawableBg);
} else if (index <= 75 && index >= 50) {
Drawable drawableBg = getResources().getDrawable(R.drawable.main_trafficlight_yellow);
btnTraffic.setBackgroundDrawable(drawableBg);
}
}
}
};
@Override
public void onBackPressed() {
//todo::do nothing now
}
}
| true |
e7a3703495236ddc6bd78a5f5569a7861cb06047 | Java | Jeet97/Latest-News-App | /NewsApp/app/src/main/java/com/example/android/newsapp/MainActivity.java | UTF-8 | 1,734 | 1.851563 | 2 | [] | no_license | package com.example.android.newsapp;
import android.annotation.TargetApi;
import android.app.SearchManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
Toolbar tb;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
tb = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(tb);
fragadapter fg = new fragadapter(getSupportFragmentManager());
ViewPager vp = (ViewPager) findViewById(R.id.viewpager);
vp.setAdapter(fg);
TabLayout tb = (TabLayout) findViewById(R.id.tabs);
tb.setupWithViewPager(vp);
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main_drawer, menu);
SearchManager sc = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView shc= (SearchView) menu.findItem(R.id.searchit).getActionView();
shc.setSearchableInfo(sc.getSearchableInfo(getComponentName()));
return true;
}
/*
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
*/
}
| true |
76141ba7629c67fcb3f6728d5f98e418888e823e | Java | Westins/Holiday_WarehouseSystem | /src/main/java/com/sw/sys/controller/MainController.java | UTF-8 | 4,105 | 2.421875 | 2 | [] | no_license | package com.sw.sys.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sw.bus.service.SalesBackService;
import com.sw.bus.service.SalesService;
import com.sw.sys.common.*;
import com.sw.bus.service.ExportService;
import com.sw.bus.service.ImportService;
import com.sw.sys.pojo.Notice;
import com.sw.sys.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
/**
* @author :单威
* @description: 工作台数据
* @date :Created in 2020/2/23 13:11
*/
@RestController
@RequestMapping(value = "/main")
@Transactional(rollbackFor = Exception.class)
public class MainController {
/**
* 系统公告Service注入
*/
@Autowired
private NoticeService noticeService;
/**
* 进货service 注入
*/
@Autowired
private ImportService importService;
/**
* 退货Service 注入
*/
@Autowired
private ExportService exportService;
/**
* 商品销售Service 注入
*/
@Autowired
private SalesService salesService;
/**
* 商品销售退货Service 注入
*/
@Autowired
private SalesBackService salesBackService;
/**
* 加载 最新三条系统公告
*
* @return
*/
@RequestMapping(value = "/loadMainNotice")
public DataGridView loadMainNotice() {
QueryWrapper<Notice> wrapper = new QueryWrapper<>();
wrapper.orderByDesc("createTime");
IPage<Notice> page = new Page<>(1, 3);
this.noticeService.page(page, wrapper);
return new DataGridView(page.getTotal(), page.getRecords());
}
/**
* 查询当月进货 退货数量
*
* @return
*/
@RequestMapping(value = "/loadImportExportByNow")
public Map<String, Object> loadImportExportByNow() {
Map<String, Object> map = new HashMap<>(16);
Integer importNumber = this.importService.loadImportByNow();
Integer exportNumber = this.exportService.loadExportByNow();
map.put("importNumber", importNumber == null ? 0 : importNumber);
map.put("exportNumber", exportNumber == null ? 0 : exportNumber);
return map;
}
/**
* 查询 近期一年各商品的销售情况
* 并返回Examples 需要的数据格式
*
* @return
*/
@RequestMapping(value = "loadSalesGoodsByYear")
public DataGridView loadSalesGoodsByYear() {
List<EchartsView> list = this.salesService.loadGoodsSalesByYear();
return new DataGridView(list);
}
/**
* 加载今月商品进货占比
*
* @return
*/
@RequestMapping(value = "loadImportGoodsByMonth")
public DataGridView loadImportGoodsByMonth() {
List<Proportion> importList = this.importService.loadImportGoodsByMonth();
return new DataGridView(importList);
}
/**
* 加载今月商品出售占比
*
* @return
*/
@RequestMapping(value = "loadSalesGoodsByMonth")
public DataGridView loadSalesGoodsByMonth() {
List<Proportion> salesList = this.salesService.loadSalesGoodsByMonth();
return new DataGridView(salesList);
}
/**
* 加载本月商品销售和退货数量
*
* @return
*/
@RequestMapping(value = "loadSalesAndBackNumberByMonth")
public Map<String, Object> loadSalesAndBackNumberByMonth() {
Map<String, Object> map = new HashMap<>(16);
Integer salesNumber = this.salesService.loadSalesByMonth();
Integer salesBackNumber = this.salesBackService.loadSalesBackGoodsByMonth();
map.put("salesNumber", salesNumber == null ? 0 : salesNumber);
map.put("salesBackNumber", salesBackNumber == null ? 0 : salesBackNumber);
return map;
}
}
| true |
f138ae45cfe50cdb01a8ee7f4f59350fb5f407be | Java | RyanTech/12306-Android-Decompile | /12306/src/com/tl/uic/util/ScreenReceiver.java | UTF-8 | 1,946 | 2.0625 | 2 | [] | no_license | package com.tl.uic.util;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.Display;
import android.view.WindowManager;
import com.tl.uic.EnvironmentalData;
import com.tl.uic.TLFCache;
import com.tl.uic.Tealeaf;
public class ScreenReceiver extends BroadcastReceiver
{
private static final int ROTATION_18O = 180;
private static final int ROTATION_9O = 90;
private static final int ROTATION_NEGATIVE_9O = -90;
private static final int ROTATION_O;
private int height;
private int rotation = 0;
private int width;
public ScreenReceiver()
{
screenUpdate();
}
private Display screenUpdate()
{
Display localDisplay = ((WindowManager)Tealeaf.getApplication().getApplicationContext().getSystemService("window")).getDefaultDisplay();
this.height = localDisplay.getHeight();
this.width = localDisplay.getWidth();
LogInternal.log("Screen height:" + this.height + " Screen width" + this.width);
return localDisplay;
}
public final int getHeight()
{
return this.height;
}
public final int getRotation()
{
return this.rotation;
}
public final int getWidth()
{
return this.width;
}
public final void onReceive(Context paramContext, Intent paramIntent)
{
if ("android.intent.action.CONFIGURATION_CHANGED".equalsIgnoreCase(paramIntent.getAction()))
switch (screenUpdate().getOrientation())
{
default:
case 0:
case 1:
case 2:
case 3:
}
while (true)
{
LogInternal.log("Screen change:" + this.rotation);
if (TLFCache.getEnvironmentalData() != null)
TLFCache.getEnvironmentalData().hasClientStateChanged();
return;
this.rotation = 0;
continue;
this.rotation = 90;
continue;
this.rotation = 180;
continue;
this.rotation = -90;
}
}
}
| true |
c76cf483fed251506533485640550d5b061d7cc8 | Java | gangseokseo/javaworkspacePractice | /src/main/java/template/ManualCar.java | UTF-8 | 602 | 2.875 | 3 | [] | no_license | package template;
public class ManualCar extends Car {
//사람이 운전하는 차
@Override
public void drive() {
System.out.println("사람이 운전합니다");
System.out.println("사람이 핸들을 조작합니다");
}
@Override
public void stop() {
System.out.println("사람이 브레이크로 정지합니다");
}
@Override
public void wiper() {
System.out.println("사람이 수동으로 와이퍼를 조작합니다");
}
//public void run(){} - final 이 걸린 메서드는 오버라이딩 할 수 없다
}
| true |
7688d95a58b12bfadaa1d4be09783bf3c51d7f0d | Java | duongminhkiet/Spring-MultiMybatisJPA-JDBC | /src/main/java/com/zmk/spring/test/rd/multidb/mybatisjpa1/p2/config/DBConfig2.java | UTF-8 | 2,462 | 1.890625 | 2 | [] | no_license | package com.zmk.spring.test.rd.multidb.mybatisjpa1.p2.config;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "e2EntityManagerFactory",
transactionManagerRef = "e2TransactionManager",
basePackages = {"com.zmk.spring.test.rd.multidb.mybatisjpa1.p2.repository"}
)
public class DBConfig2 {
private static final String DATASOURCE2 = "datasource2";
// @Primary
@Bean(name = DATASOURCE2)
@ConfigurationProperties(prefix = "spring.datasource2")
public DataSource customerDataSource() {
return DataSourceBuilder.create().build();
}
// @Primary
@Bean(name = "e2EntityManagerFactory")
public LocalContainerEntityManagerFactoryBean
entityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier(DATASOURCE2) DataSource dataSource
) {
return builder
.dataSource(dataSource)
.packages("com.zmk.spring.test.rd.multidb.mybatisjpa1.p2.model")
.persistenceUnit("db2")
.build();
}
@Bean(name = "e2TransactionManager")
@Autowired
// @Primary
DataSourceTransactionManager e1TransactionManager(@Qualifier(DATASOURCE2) final DataSource datasource) {
DataSourceTransactionManager e1TransactionManager = new DataSourceTransactionManager(datasource);
return e1TransactionManager;
}
@Bean(name = "sqlServerJPAMybatisJdbcTemplate2")
public JdbcTemplate sqlServer1JdbcTemplate(@Qualifier(DATASOURCE2) DataSource datasource1) {
return new JdbcTemplate(datasource1);
}
}
| true |
45edb30e12166ff78ad8de2e248cd0473d36f87e | Java | zgdkik/springcloud-g | /demo/src/main/java/com/example/demo/netty/TimeDecode.java | UTF-8 | 668 | 2.171875 | 2 | [
"Apache-2.0"
] | permissive | package com.example.demo.netty;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.util.List;
/**
* @author lee
*/
public class TimeDecode extends ByteToMessageDecoder {
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
if (byteBuf.readByte() < 4) {
return;
}
int i = byteBuf.readInt();
if (byteBuf.readByte() < i) {
return;
}
ByteBuf byteBuf2 = byteBuf.readBytes(i);
list.add(byteBuf2);
}
}
| true |
ade3137d425dfb506e583e53bc872c3381e8f6e4 | Java | keshavkaanthkumar/webapp-service | /src/main/java/com/neu/webapp/model/Message.java | UTF-8 | 244 | 2.171875 | 2 | [] | no_license | package com.neu.webapp.model;
/**
* @author Keshav
*
*/
public class Message {
private String msg;
public Message(String msg){
this.msg=msg;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
| true |
4af6b1eb19034f8bf17e0cb507bc621e7ff9603c | Java | romariomkk/HtmlWebParser | /src/main/MainServlet.java | UTF-8 | 2,671 | 2.390625 | 2 | [] | no_license | package main;
import db_handler.DBInsertionThread;
import db_handler.MongoDBHandler;
import parser.Parser;
import parser.custom_entity.TagValuePair;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by romariomkk on 14.12.2016.
*/
//@WebServlet(".mainServlet")
public class MainServlet extends HttpServlet {
Logger logger = Logger.getLogger(MainServlet.class.getSimpleName());
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
MongoDBHandler dbHandler = new MongoDBHandler();
URL[] url = retrieveURLParams(request);
ExecutorService pool = Executors.newFixedThreadPool(url.length);
List<Future<List<TagValuePair>>> futures = new ArrayList<>();
for (URL urlElem : url) {
futures.add(pool.submit(new Parser(urlElem)));
}
try {
for (Future<List<TagValuePair>> future : futures) {
//dbHandler.executeInsertion(future.get());
pool.execute(new DBInsertionThread(dbHandler, future.get()));
}
} catch (InterruptedException | ExecutionException e) {
logger.log(Level.WARNING, "Execution error occurred", e);
}
if (!pool.isTerminated()) {
pool.shutdownNow();
}
List<List<TagValuePair>> forwardList = new ArrayList<>();
for (URL urlElem : url) {
forwardList.add(dbHandler.retrieveCollection(urlElem.toString()));
}
request.setAttribute("listOfLists", forwardList);
request.getRequestDispatcher("result.jsp").forward(request, response);
}
private URL[] retrieveURLParams(HttpServletRequest request) throws MalformedURLException {
return new URL[]{new URL(request.getParameter("urlN1")),
new URL(request.getParameter("urlN2")),
new URL(request.getParameter("urlN3"))};
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}
| true |
3ae1102b407922cd3ded688d8ae13a87f39346af | Java | kurchiedzaid/BookStore | /main/java/com/example/zaidk/bookstore/SingleLoggedInAdmin.java | UTF-8 | 499 | 2.390625 | 2 | [] | no_license | package com.example.zaidk.bookstore;
/**
* Created by zaidkurchied on 11/03/2016.
*/
public class SingleLoggedInAdmin {
private static SingleLoggedInAdmin instance = new SingleLoggedInAdmin();
private SingleLoggedInAdmin(){}
public static SingleLoggedInAdmin getInstance(){
return instance;
}
public void showMessage(String name){
System.out.println("Hello World!"+name);
Admin a= new Admin();
a.setName(name);
}
} | true |
f3c7b8de750be72051789b3b3080c602fdb03625 | Java | halo-ddd/hummingbird-framework | /hummingbird-runtime/src/main/java/com/hczhang/hummingbird/serializer/SimpleSerializer.java | UTF-8 | 1,526 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | package com.hczhang.hummingbird.serializer;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
/**
* Created by steven on 4/16/14.
*/
public class SimpleSerializer implements Serializer {
private static Logger logger = LoggerFactory.getLogger(SimpleSerializer.class);
@Override
public byte[] serialize(Object object) {
Validate.notNull(object, "Object is null");
byte[] blob = null;
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bytes);
out.writeObject(object);
blob = bytes.toByteArray();
bytes.close();
out.close();
} catch (IOException e) {
logger.error("Serialize throw IOException.", e);
}
return blob;
}
@Override
public <T> T deserialize(byte[] blob, Class<T> tClass) {
Validate.notNull(blob, "Data content is null");
Validate.notNull(tClass, "Class is null");
T instance = null;
try {
ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(blob));
instance = (T) in.readObject();
} catch (IOException e) {
logger.error("De-serialize throw IOException.", e);
} catch (ClassNotFoundException e) {
logger.error("De-serialize throw ClassNotFoundException.", e);
}
return instance;
}
}
| true |
f1ba87b25823dcfd83c08ea80d27b7dfec1afe14 | Java | lucagrammer/Ing-Sw-2020-Leoni-Locarno-Minotti | /src/main/java/client/gui/components/PLabel.java | UTF-8 | 1,034 | 3.328125 | 3 | [] | no_license | package client.gui.components;
import javax.swing.*;
import java.awt.*;
/**
* A customized centered label with Santorini Font
*/
public class PLabel extends JLabel {
/**
* Constructor: build a customized centered label with Santorini Font
*
* @param labelText labelText The text of the label
*/
public PLabel(String labelText) {
int defaultSize = 40;
super.setText("<HTML>"+labelText+"</HTML>");
setHorizontalAlignment(CENTER);
setVerticalAlignment(JLabel.CENTER);
setForeground(Color.WHITE);
setFont(new Font("LeGourmetScript", Font.PLAIN, defaultSize));
}
/**
* Sets the text of the label
* @param text The text to be shown
*/
public void setText(String text) {
super.setText("<HTML>"+text+"</HTML>");
}
/**
* Sets the font size
*
* @param fontSize The font size
*/
public void setFontSize(int fontSize) {
setFont(new Font("LeGourmetScript", Font.PLAIN, fontSize));
}
} | true |
f2e6c8e4b0f692681db1c54db7af89f2227e28b7 | Java | suzan-1515/Adversify-Merchant | /app/src/main/java/com/nepal/adversify/data/entity/OpeningEntity.java | UTF-8 | 400 | 1.96875 | 2 | [
"Apache-2.0"
] | permissive | package com.nepal.adversify.data.entity;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
@Entity(tableName = "opening_info")
public class OpeningEntity {
@PrimaryKey
public int id;
public String sunday;
public String monday;
public String tuesday;
public String wednesday;
public String thursday;
public String friday;
public String saturday;
}
| true |
251211260092bc321dd7b8fdec6240a71b55e245 | Java | iesilder/projectNewsRoom | /src/com/webjjang/util/MemManageUtil.java | UTF-8 | 5,658 | 2.453125 | 2 | [] | no_license | package com.webjjang.util;
import java.util.regex.Pattern;
import com.webjjang.board.dto.MemBoardCommDTO;
import com.webjjang.board.dto.MemBoardDTO;
import com.webjjang.board.dto.MemberDTO;
public class MemManageUtil {
public String update(String menu, String field, MemberDTO userDTO) {
String str = InUtil.getMenu(menu);
switch (field) {
case "pw":
if (str.trim().equals(""))
str = userDTO.getPw();
break;
case "name":
if (str.trim().equals(""))
str = userDTO.getName();
break;
case "nick":
if (str.trim().equals(""))
str = userDTO.getNick();
break;
case "tel":
if (str.trim().equals(""))
str = userDTO.getTel();
break;
case "email":
if (str.trim().equals(""))
str = userDTO.getEmail();
break;
}
return str;
}
public String updateBoard(String menu, String field) {
String str = InUtil.getMenu(menu);
MemBoardDTO memBoardDTO = new MemBoardDTO();
switch (field) {
case "title":
if (str.trim().equals(""))
str = memBoardDTO.getTitle();
break;
case "content":
if (str.trim().equals(""))
str = memBoardDTO.getContent();
break;
}
return str;
}
// public String updatePw(String menu, MemberDTO userDTO) {
// String updatePw = InUtil.getMenu(menu);
// if (updatePw.trim().equals(""))
// updatePw = userDTO.getPw();
// return updatePw;
// }
//
// public String updateName(String menu, MemberDTO userDTO) {
// String updateName = InUtil.getMenu("이름 ");
// if (updateName.trim().equals(""))
// updateName = userDTO.getName();
// return updateName;
// }
//
// public String updateNick(String menu, MemberDTO userDTO) {
// String updateNick = InUtil.getMenu("닉네임 ");
// if (updateNick.trim().equals(""))
// updateNick = userDTO.getNick();
// return updateNick;
// }
//
// public String updateTel(String menu, MemberDTO userDTO) {
// String updateTel = InUtil.getMenu("전화번호 ");
// if (updateTel.trim().equals(""))
// updateTel = userDTO.getTel();
// return updateTel;
// }
//
// public String updateEmail(String menu, MemberDTO userDTO) {
// String updateEmail = InUtil.getMenu("이메일 ");
// if (updateEmail.trim().equals(""))
// updateEmail = userDTO.getEmail();
// return updateEmail;
// }
public String patternCheck(String pattern, String str, String err) {
String info = InUtil.getMenu(str);
// id를 검사하기 위한 프로그램
// id에 영소문자와 숫자만 입력하도록 하기 위한 처리
String p = pattern;
boolean check = Pattern.matches(p, info);
if (check == true) {
} else {
info = null;
System.out.println(err);
}
return info;
}
public String rePatternCheck(String pattern, String str, String err) {
String info = InUtil.getMenu(str);
// id를 검사하기 위한 프로그램
// id에 영소문자와 숫자만 입력하도록 하기 위한 처리
String p = pattern;
boolean check = Pattern.matches(p, info);
if (check != true) {
} else {
info = null;
System.out.println(err);
}
return info;
}
// public boolean checkId(String str) {
// boolean check = true;
// if (str == null)
// check = false;
// if (str.length() < 6) {
// System.out.println("아이디는 6자리 이상이어야 합니다. ");
// check = false;
// }
// if (str.length() > 11) {
// System.out.println("아이디는 10자리를 넘어서는 안됩니다. ");
// check = false;
// }
// return check;
// }
//
// public boolean checkPw(String str) {
// boolean check = true;
// if (str == null)
// check = false;
// if (str.length() < 6) {
// System.out.println("비밀번호는 비밀번호는 최소 6자리가 넘어야 합니다.");
// check = false;
// }
// if (str.length() > 17) {
// System.out.println("비밀번호는 16자리를 넘을 수 없습니다.");
// check = false;
// }
// return check;
// }
public boolean nullCheck(String s) {
boolean check = true;
if (s == null)
check = false;
return check;
}
public void printUserInfo(MemberDTO userDTO) {
OutUtil.repeatChar("*", 30);
System.out.println("ID:\t" + userDTO.getId() + "\n" + "이름:\t" + userDTO.getName() + "\n" + "닉네임:\t"
+ userDTO.getNick() + "\n" + "전화번호:\t" + userDTO.getTel() + "\n" + "이메일:\t" + userDTO.getEmail() + "\n"
+ "회원등급:\t" + userDTO.getGrade());
OutUtil.repeatChar("*", 30);
}
public void printBoardInfo(MemBoardDTO memBoardDTO) {
OutUtil.repeatChar("*", 30);
System.out.println("글번호:\t" + memBoardDTO.getNo() + "\n" + "제목:\t" + memBoardDTO.getTitle() + "\n" + "글내용:\t"
+ memBoardDTO.getContent() + "\n" + "ID:\t" + memBoardDTO.getId() + "\n" + "작성일:\t"
+ memBoardDTO.getWritedate() + "\n");
OutUtil.repeatChar("*", 30);
}
public void printBoardSimpleInfo(MemBoardDTO memBoardDTO) {
OutUtil.repeatChar("*", 30);
System.out.println("글번호:\t" + memBoardDTO.getNo() + "\n" + "제목:\t" + memBoardDTO.getTitle() + "\n" + "ID:\t"
+ memBoardDTO.getId() + "\n" + "작성일:\t" + memBoardDTO.getWritedate() + "\n");
OutUtil.repeatChar("*", 30);
}
public void printBoardInfo(MemBoardCommDTO memBoardDTO) {
OutUtil.repeatChar("*", 30);
System.out.println("댓글번호:\t" + memBoardDTO.getCommno() + "\n" + "글내용:\t" + memBoardDTO.getContent() + "\n"
+ "ID:\t" + memBoardDTO.getId() + "\n" + "작성일:\t" + memBoardDTO.getWritedate() + "\n");
OutUtil.repeatChar("*", 30);
}
}// end of class MemManageUtil
| true |
773b06f5e4e23618c5b8fd976d54cf17c30708eb | Java | amusa/entitlement | /cosm-entitlement/src/main/java/com/nnpcgroup/cosm/ejb/production/jv/impl/JvProductionServicesImpl.java | UTF-8 | 1,244 | 1.976563 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.nnpcgroup.cosm.ejb.production.jv.impl;
import com.nnpcgroup.cosm.ejb.production.jv.JvProductionServices;
import java.util.logging.Logger;
import com.nnpcgroup.cosm.entity.production.jv.JvProduction;
import com.nnpcgroup.cosm.util.COSMPersistence;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
/**
*
* @author 18359
*/
@Stateless
@Local(JvProductionServices.class)
public class JvProductionServicesImpl extends ProductionServicesImpl<JvProduction> implements JvProductionServices {
private static final Logger LOG = Logger.getLogger(JvProductionServicesImpl.class.getName());
@Inject
@COSMPersistence
private EntityManager em;
public JvProductionServicesImpl() {
super(JvProduction.class);
}
public JvProductionServicesImpl(Class<JvProduction> entityClass) {
super(entityClass);
}
@Override
protected EntityManager getEntityManager() {
return em;
}
}
| true |
740f81cce938e86179804a49230b3a267cab7df9 | Java | pujav65/RyaAdapters | /rya.adapter.web/src/main/java/org/apache/rya/adapter/rest/reasoner/types/pellet/PelletReasonerRunner.java | UTF-8 | 7,447 | 1.570313 | 2 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.rya.adapter.rest.reasoner.types.pellet;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.apache.rya.adapter.rest.reasoner.types.ReasonerResult;
import org.apache.rya.adapter.rest.reasoner.types.ReasonerRunner;
import org.apache.rya.api.domain.RyaStatement;
import org.apache.rya.api.domain.RyaStatement.RyaStatementBuilder;
import org.apache.rya.api.domain.RyaType;
import org.apache.rya.api.domain.RyaURI;
import org.apache.rya.api.resolver.RyaToRdfConversions;
import org.apache.rya.jena.jenasesame.JenaSesame;
import org.mindswap.pellet.jena.PelletReasonerFactory;
import org.openrdf.model.URI;
import org.openrdf.model.vocabulary.XMLSchema;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.sail.SailRepository;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.query.Dataset;
import com.hp.hpl.jena.rdf.model.InfModel;
import com.hp.hpl.jena.rdf.model.Literal;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Property;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.StmtIterator;
import com.hp.hpl.jena.reasoner.Reasoner;
/**
* Handles running the Pellet reasoner.
*/
public class PelletReasonerRunner implements ReasonerRunner {
private static final Logger log = Logger.getLogger(PelletReasonerRunner.class);
@Override
public ReasonerResult runReasoner(final SailRepository repo, final String filename) throws Exception {
final List<RyaStatement> ryaStatements = new ArrayList<>();
RepositoryConnection conn = null;
try {
conn = repo.getConnection();
final Dataset dataset = JenaSesame.createDataset(conn);
final Model adapterModel = dataset.getDefaultModel();
// create an empty ontology model using Pellet spec
final OntModel model = ModelFactory.createOntologyModel(PelletReasonerFactory.THE_SPEC, null);
adapterModel.add(model);
final File file = new File(filename);
// read the file
model.read("file:///" + file.getAbsolutePath());
model.prepare();
final Reasoner reasoner = PelletReasonerFactory.theInstance().create();
final InfModel infModel = ModelFactory.createInfModel(reasoner, model);
final StmtIterator iterator = infModel.listStatements();
int count = 0;
while (iterator.hasNext()) {
final com.hp.hpl.jena.rdf.model.Statement stmt = iterator.nextStatement();
final Resource subject = stmt.getSubject();
final Property predicate = stmt.getPredicate();
final RDFNode object = stmt.getObject();
final RyaStatement ryaStatement = convertJenaStatementToRyaStatement(stmt);
log.info(subject.toString() + " " + predicate.toString() + " " + object.toString());
model.add(stmt);
// TODO: figure out why the infModel doesn't make its way back to the Sail repo connection automatically
conn.add(RyaToRdfConversions.convertStatement(ryaStatement));
ryaStatements.add(ryaStatement);
count++;
}
log.info("Result count : " + count);
} finally {
if (conn != null) {
conn.close();
}
}
final ReasonerResult reasonerResult = new ReasonerResult(ryaStatements);
return reasonerResult;
}
private static RyaStatement convertJenaStatementToRyaStatement(final com.hp.hpl.jena.rdf.model.Statement statement) {
final Resource subject = statement.getSubject();
final Property predicate = statement.getPredicate();
final RDFNode object = statement.getObject();
final RyaStatementBuilder builder = new RyaStatementBuilder();
if (subject != null) {
String uri = null;
if (subject.isURIResource()) {
uri = subject.asResource().getURI();
} else if (subject.isAnon()) {
uri = subject.asNode().getBlankNodeId().toString();
} else if (object.isResource()) {
uri = subject.asResource().getId().toString();
}
builder.setSubject(new RyaURI(uri));
}
if (predicate != null && predicate.getURI() != null) {
builder.setPredicate(new RyaURI(predicate.getURI()));
}
if (object != null) {
RyaType ryaType = null;
if (object.isLiteral()) {
final Literal literal = object.asLiteral();
final Class<?> clazz = literal.getValue().getClass();
final URI uriType = determineClassTypeUri(clazz);
ryaType = new RyaType(uriType, literal.toString());
} else if (object.isURIResource()) {
final String uri = object.asResource().getURI();
ryaType = new RyaType(XMLSchema.ANYURI, uri);
} else if (object.isAnon()) {
final String data = object.asNode().getBlankNodeId().toString();
ryaType = new RyaType(XMLSchema.STRING, data);
} else if (object.isResource()) {
final String data = object.asResource().getId().toString();
ryaType = new RyaType(XMLSchema.ANYURI, data);
}
builder.setObject(ryaType);
}
final RyaStatement ryaStatement = builder.build();
return ryaStatement;
}
private static URI determineClassTypeUri(final Class<?> classType) {
if (classType.equals(Integer.class)) {
return XMLSchema.INTEGER;
} else if (classType.equals(Double.class)) {
return XMLSchema.DOUBLE;
} else if (classType.equals(Float.class)) {
return XMLSchema.FLOAT;
} else if (classType.equals(Short.class)) {
return XMLSchema.SHORT;
} else if (classType.equals(Long.class)) {
return XMLSchema.LONG;
} if (classType.equals(Boolean.class)) {
return XMLSchema.BOOLEAN;
} else if (classType.equals(Byte.class)) {
return XMLSchema.BYTE;
} else if (classType.equals(Date.class)) {
return XMLSchema.DATETIME;
} else if (classType.equals(URI.class)) {
return XMLSchema.ANYURI;
}
return XMLSchema.STRING;
}
} | true |
6e1ba758d0999345326c69e8f872fd0f2575b543 | Java | WUWWUW/myLeetCode | /src/easy/TwoZero.java | UTF-8 | 2,706 | 4.0625 | 4 | [] | no_license | package easy;
import java.util.Stack;
/**
* All rights Reserved, Designed By www.freemud.cn
*
* @version V1.0
* @Title: TwoZero
* @Package easy
* @Description:
* @author: WW
* @date: 2019/4/17 16:26
*/
/**
* 给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
*
* 有效字符串需满足:
*
* 左括号必须用相同类型的右括号闭合。
* 左括号必须以正确的顺序闭合。
* 注意空字符串可被认为是有效字符串。
*
* 示例 1:
*
* 输入: "()"
* 输出: true
* 示例 2:
*
* 输入: "()[]{}"
* 输出: true
* 示例 3:
*
* 输入: "(]"
* 输出: false
* 示例 4:
*
* 输入: "([)]"
* 输出: false
* 示例 5:
*
* 输入: "{[]}"
* 输出: true
*/
//解题思路:括号匹配一定要用栈 ,括号的匹配就是出栈和入栈的操作,需要考虑栈是否为空等,括号匹配不难,
// 这个套路要记住,这应该是第三或者第四次做这个题目 还是花了挺久的,下次要将思路先理清楚
public class TwoZero {
public static boolean isValid(String s) {
Stack<Character> stack=new Stack();
boolean flag=true;
int n=s.length();
if(s.equals("")){
return true;
}else if(n<2){
return false;
}
for(int i=0;i<n;i++){
char c=s.charAt(i);
switch (c){
case '(':stack.push(c);break;
case '[':stack.push(c);break;
case '{':stack.push(c);break;
case ')':
if(stack.size()==0){
flag=false;
break;
}
if('('!=stack.pop()){
flag=false;
}
break;
case ']':
if(stack.size()==0){
flag=false;
break;
}
if('['!=stack.pop()){
flag=false;
}
break;
case '}':
if(stack.size()==0){
flag=false;
break;
}
if('{'!=stack.pop()){
flag=false;
}
break;
default:flag=false;break;
}
if(flag==false){
break;
}
}
if(stack.size()>0){
flag=false;
}
return flag;
}
public static void main(String[] args) {
String s="()";
System.out.println(isValid(s));
}
}
| true |
2dea44ec187cffa3663596e2bb989816049270b9 | Java | calvinjhchan/Happy-Clown-Lazer-Maze | /ISP/Main/toburn/All Versions/D2K Games Studio June 1 (Version 3)/Version 3/PauseMenu.java | UTF-8 | 3,850 | 3.015625 | 3 | [] | no_license | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
/**
* PauseMenu that fades in.
* @author Calvin Chan, JunHee Cho
* @version 3 May 31st, 2012
*/
public class PauseMenu extends JPanel implements ActionListener
{
/**
* Reference variable to the parent;
*/
private MainMenu parent;
/**
* Stores the Serial Version UID.
*/
private static final long serialVersionUID = 1L;
/**
* Holds the transparency value of the jpanel
*/
private float alpha=0.00f;
/**
* The timer to create Fadingclown objects.
*/
private javax.swing.Timer timer;
/**
* Holds 4 clown images
*/
private ImageIcon[]images;
/**
* Holds the number of clowns on the screen.
*/
private int numClowns;
/**
* Sets up the jpanel, images, buttons, and starts the timer.
* @param parent the parent program
*/
public PauseMenu(MainMenu parent)
{
setLayout(null);
setOpaque(false);
this.parent=parent;
images=new ImageIcon[4];
for(int x=1;x<=4;x++)
{
images[x-1]=new ImageIcon("images/clowns/clown"+x+".png");
}
JPanel buttons=new JPanel();
buttons.setLayout(new BoxLayout(buttons,BoxLayout.PAGE_AXIS));
buttons.setOpaque(false);
JLabel temp=new JLabel(new ImageIcon("images/pausemenu/pausemenu.png"));
temp.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton resume=ButtonMaker.makeButton("resumegame",parent);
resume.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton restart=ButtonMaker.makeButton("restartlevel",parent);
restart.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton quit2main=ButtonMaker.makeButton("quittomain",parent);
quit2main.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton quit2desk=ButtonMaker.makeButton("quittodesk",parent);
quit2desk.setAlignmentX(Component.CENTER_ALIGNMENT);
buttons.add(temp);
buttons.add(resume);
buttons.add(restart);
buttons.add(quit2main);
buttons.add(quit2desk);
buttons.setBounds(0,0,700,550);
add(buttons);
validate();
timer=new javax.swing.Timer(2000,this);
timer.start();
}
/**
* Removes temp from the screen
* @param temp FadingClown to remove.
*/
public void removeClown(FadingClown temp)
{
remove(temp);
temp=null;
numClowns--;
}
/**
* Sets up to fade in the jpanel.
*/
public void run()
{
alpha=0.0f;
setVisible(true);
timer.restart();
}
/**
* Sets up to hide the jpanel.
*/
public void stop()
{
setVisible(false);
timer.stop();
}
/**
* Overrides the drawing method to draw the fading jpanel instead.
* @param g The graphics object to draw on.
* <PRE>Name Type Description</PRE>
* <PRE>g2d Graphics2D Allows extra features to draw the image (transparency)
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
repaint();
if(alpha<0.5f)
{
alpha+=0.01f;
try
{
Thread.sleep(10);
}
catch(InterruptedException ie)
{
}
repaint();
}
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
g2d.setColor(Color.BLACK);
g.fillRect (0, 0, 700, 550);
}
/**
* Called every few seconds to create a fadingclown object
* @param ae Holds extra information on the actionevent.
*/
public void actionPerformed(ActionEvent ae)
{
if(numClowns<2)
{
numClowns++;
FadingClown temp=new FadingClown(this,images[(int)(Math.random()*4)]);
temp.setBounds((int)(Math.random()*440),(int)(Math.random()*300),200,200);
add(temp);
repaint();
}
}
} | true |
e4db7f9f68377f3960c9999bfd5006cd07a7fa77 | Java | anilkumary/3rd_june_10-30-AM | /Project169/src/switchcommands/AlertHandling_With_Try_Catch.java | UTF-8 | 1,445 | 2.765625 | 3 | [] | no_license | package switchcommands;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class AlertHandling_With_Try_Catch {
public static void main(String[] args) throws Exception
{
/*
* Scenario:-->
* Verify search job without enter selectcourse and keyword enter
* Steps:-->
* => Given url https://www.firstnaukri.com/
* => When click search button without enter Select courst and Keyword Enter
* => Then receive Alert with expected text.
*/
//Set Runtime environment variable for chrome driver
String chrome_path="D:\\sunill\\3rd_June_10-30_AM_2019\\drivers\\chromedriver.exe";
System.setProperty("webdriver.chrome.driver", chrome_path);
WebDriver driver=new ChromeDriver();
driver.get("https://www.firstnaukri.com/");
driver.manage().window().maximize();
//Identify Search button
WebElement Search_btn=driver.findElement(By.xpath("//input[@value='Search']"));
Search_btn.click();
Thread.sleep(5000);
try {
driver.switchTo().alert().accept();
System.out.println("Alert presented");
} catch (NoAlertPresentException e) {
System.out.println("Alert not presented");
}
System.out.println("Script Continued");
}
}
| true |
c96710333a41b019ba70e9d7004d74be234cdeee | Java | ygayypov/JDBC_Project_B20 | /src/test/java/utility/DB_Utility.java | UTF-8 | 3,072 | 3.375 | 3 | [] | no_license | package utility;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class DB_Utility {
static Connection conn ; // make it static field so we can reuse in every methods we write
static Statement stmnt ;
static ResultSet rs ;
public static void createConnection(){
String connectionStr = "jdbc:oracle:thin:@3.86.188.174:1521:XE";
String username = "hr" ;
String password = "hr" ;
try {
conn = DriverManager.getConnection(connectionStr,username,password) ;
System.out.println("CONNECTION SUCCESSFUL !! ");
} catch (SQLException e) {
System.out.println("CONNECTION HAS FAILED !!! " + e.getMessage() );
}
}
// Create a method called runQuery that accept a SQL Query
// and return ResultSet Object
public static ResultSet runQuery(String query){
// ResultSet rs = null;
// reusing the connection built from previous method
try {
stmnt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = stmnt.executeQuery(query) ;
} catch (SQLException e) {
System.out.println("Error while getting resultset " + e.getMessage());
}
return rs ;
}
// create a method to clean up all the connection statemnet and resultset
public static void destroy(){
try {
rs.close();
stmnt.close();
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static int getRowCount () {
int rowCount = 0;
try {
rs.last();
rowCount = rs.getRow();
//move the cursor back to beforeFirst location to avoid accident
rs.beforeFirst();
}catch (SQLException e){
System.out.println("ERROR WHILE GETTING ROW COUNT " + e.getMessage());
}
return rowCount;
}
//get the column count
//return count of column the result set have
public static int getColumnCount(){
int columnCount = 0;
try{
ResultSetMetaData rsmd = rs.getMetaData();
columnCount = rsmd.getColumnCount();
}catch (SQLException e){
System.out.println("ERROR WHILE GETTING COLUMN COUNT " + e.getMessage());
}
return columnCount;
}
//create a method that return all the column name as List<String>
public static List<String> getColumnNames (){
List<String> columnList = new ArrayList<>();
try {
ResultSetMetaData rsmd = rs.getMetaData();
for (int colNum = 1 ; colNum <= getColumnCount(); colNum++){
String columnName = rsmd.getColumnLabel(colNum);
columnList.add(columnName);
}
} catch (SQLException e) {
System.out.println("ERROR WHILE GETTING ALL COLUMN NAMES " + e.getMessage());
}
return columnList;
}
} | true |
5eaa58fe7392c58be91777c2532c9f228e2a0ce5 | Java | rhj0970/C343-Data-Structure | /C343hyryu-master/src/lab9/GreedyDriver.java | UTF-8 | 1,418 | 3.34375 | 3 | [] | no_license | package lab9;
import java.util.PriorityQueue;
import java.util.Scanner;
public class GreedyDriver {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
PriorityQueue<Greedy> prior = new PriorityQueue<Greedy>();
int count = sc.nextInt();
for (int i=0; i<count; i++) {
String classroom = sc.next();
double time = sc.nextDouble();
double end = sc.nextDouble();
prior.add(new Greedy(classroom, time, end));
}
Greedy prior2 = null;
while(!prior.isEmpty()) {
Greedy current = prior.poll();
// System.out.println("current" + " " +current.getTime());
//if (prior2 != null) {
// System.out.println("prior2" + " " + prior2.getSecondTime());
//}
if (prior2 != null && (current.getTime() > prior2.getSecondTime())) {
System.out.println(current);
prior2 = current;
}
if (prior2 == null) {
System.out.println(current);
prior2 = current;
}
}
}
} | true |
187ed599fc9defdc0b0151bd42774cb78cc77894 | Java | agkee/Java-Programming | /Problems/RemoveMin.java | UTF-8 | 528 | 2.921875 | 3 | [] | no_license | package listnode;
import listnode.ListNode;
public class RemoveMin {
public ListNode remove (ListNode list) {
ListNode dummy = new ListNode(0, list);
ListNode minBefore = dummy;
ListNode min = list;
while (dummy.next != null) {
if (dummy.next.info < min.info) {
min = dummy.next;
minBefore = dummy;
}
dummy = dummy.next;
}
minBefore.next = min.next;
if (list == min) {
list = list.next;
}
return list;
}
}
| true |
eef219e24e689fb04ec2712e8ed539d79180b1b7 | Java | evalle-mx/dhr-clientRest | /src/net/dothr/test/SimpleTester.java | UTF-8 | 379 | 2.3125 | 2 | [] | no_license | package net.dothr.test;
import net.utils.ClientRestUtily;
public class SimpleTester {
public static void main(String[] args) {
numerador(127, 504);
}
/**
* Simple numerador para lineas en archivo
* @param inicio
* @param fin
*/
public static void numerador(long inicio, long fin){
for(;inicio<=fin;inicio++){
System.out.println(inicio);
}
}
}
| true |
ab5e62753ca544986596c358db7367c140124509 | Java | EKolyshkin/Fundamentals-of-Computer-Science | /Chapter0/src/DownRockets.java | UTF-8 | 904 | 3.578125 | 4 | [] | no_license | /* Egor Kolyshkin, CS 210, 09/30/2020,
* This program prints two upside-down rockets. */
public class DownRockets
{
public static void main(String[] args)
{
// Prints two upside-down rockets
printVs();
printBoxes();
printLabels();
printBoxes();
printVs();
}
public static void printVs()
{
// Prints two V shapes
System.out.println(" \\ / \\ / ");
System.out.println(" \\ / \\ / ");
System.out.println(" \\/ \\/ ");
}
public static void printBoxes()
{
// Prints two box shapes
System.out.println("+------+ +------+");
System.out.println("| | | |");
System.out.println("| | | |");
System.out.println("+------+ +------+");
}
public static void printLabels()
{
// Prints two box shapes
System.out.println("|\"show\"| |\"show\"|");
System.out.println("|quotes| |quotes|");
}
}
| true |
2957f4137e0e7c9c548bbcbf7b0fae285c0c910c | Java | Arbonkeep/SSM-Frame | /SpringMVC/springmvc/springmvc_01_start/src/main/java/com/arbonkeep/utils/StringToDateConverter.java | UTF-8 | 906 | 2.984375 | 3 | [] | no_license | package com.arbonkeep.utils;
import org.springframework.core.convert.converter.Converter;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
/**
* @author arbonkeep
* @date 2019/12/3 - 12:45
*将字符串转换为日期类型
*/
public class StringToDateConverter implements Converter<String, Date> {
/**
* 转换的方法
* @param source 需要转换的字符串
* @return
*/
@Override
public Date convert(String source) {
//判断
if(source == null) {
throw new RuntimeException("数据为null");
}
//获取格式化对象
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
try {
return df.parse(source);
} catch (ParseException e) {
throw new RuntimeException("类型转换出错");
}
}
}
| true |
4be197a7b5cfe9c588d2e9ae91db048b5bfbdfad | Java | hncboy/LeetCode | /src/com/hncboy/MaximumNumberOfAchievableTransferRequests.java | UTF-8 | 1,333 | 3.171875 | 3 | [
"Apache-2.0"
] | permissive | package com.hncboy;
import java.util.Arrays;
/**
* @author hncboy
* @date 2022/2/28 8:50
* 1601.最多可达成的换楼请求数目
*/
public class MaximumNumberOfAchievableTransferRequests {
public static void main(String[] args) {
MaximumNumberOfAchievableTransferRequests m = new MaximumNumberOfAchievableTransferRequests();
System.out.println(m.maximumRequests(5, new int[][]{{0, 1}, {1, 0}, {0, 1}, {1, 2}, {2, 0}, {3, 4}}));
}
public int maximumRequests(int n, int[][] requests) {
int[] delta = new int[n];
int result = 0;
for (int mask = 0; mask < (1 << requests.length); mask++) {
int count = Integer.bitCount(mask);
if (count <= result) {
continue;
}
Arrays.fill(delta, 0);
for (int i = 0; i < requests.length; i++) {
if ((mask & (1 << i)) != 0) {
delta[requests[i][0]]++;
delta[requests[i][1]]--;
}
}
boolean flag = true;
for (int x : delta) {
if (x != 0) {
flag = false;
break;
}
}
if (flag) {
result = count;
}
}
return result;
}
}
| true |
9808a75f72fd72fd4d89d77ae9c69691bb7cefa0 | Java | cckmit/health | /health-support/src/main/java/com/dachen/util/JsoupUtil.java | UTF-8 | 690 | 2.4375 | 2 | [] | no_license | package com.dachen.util;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class JsoupUtil {
public static String getBody(String url){
return "";
}
public static String getAllHtml(String url){
return "";
}
public static Document getDocument(String url){
Document doc = null;
if(!url.startsWith("https://") && !url.startsWith("http://") ){
return doc;
}
try {
doc = Jsoup.connect(url).get();
} catch (IOException e) {
doc = null;
}
return doc;
}
public static void main(String[] args) {
Document doc = getDocument("baidu.com");
System.err.println("doc");
}
}
| true |
795d57c2119485c6aabd4b68d5122f959c70154a | Java | JordanKPark/FrequentFlyerRedeemer | /Assignment-8/src/MileRedeemerTest.java | UTF-8 | 1,391 | 2.71875 | 3 | [] | no_license | /************************************************************
* *
* CSCI 470/502 Assignment 8 Fall 2018 *
* *
* Programmer(s): Eric Davis (z136652), *
* Michael Simon (z1838011), *
* Jordan Park (z1816715) *
* Section: 1 *
* *
* Date Due: 11:59 PM on Wednesday, 11/28/2018 *
* *
* Purpose: MileRedeemer trigger app. *
* *
* *
***********************************************************/
import javax.swing.JFrame ;
import java.io.IOException;
public class MileRedeemerTest
{
public static void main(String[] args) throws IOException
{
MileRedemptionApp mileRedemptionApp = new MileRedemptionApp();
mileRedemptionApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mileRedemptionApp.setSize(825,400);
mileRedemptionApp.setVisible(true);
}
} | true |
7ee4048955dee5d43cbe53cf973dad2a3a1be7b0 | Java | Waterfox83/algorithms | /src/in/designpatterns/builder/pizzaattributes/Crust.java | UTF-8 | 279 | 2.953125 | 3 | [] | no_license | package in.designpatterns.builder.pizzaattributes;
public enum Crust {
THIN {
public float getCost(){
return 70;
}
} , STUFFED{
public float getCost(){
return 90;
}
};
public abstract float getCost();
}
| true |
9f4374119c27fcda9b5dc7667c223c6e929ffa8e | Java | dneves/gitlab-integration-plugin | /src/main/java/com/neon/intellij/plugins/gitlab/model/EditableView.java | UTF-8 | 152 | 1.539063 | 2 | [
"MIT"
] | permissive | package com.neon.intellij.plugins.gitlab.model;
public interface EditableView< INPUT, OUTPUT > {
void fill( INPUT input );
OUTPUT save();
}
| true |
2af2a52c0a890df0b1ccf83e62ca6347cf36c5c4 | Java | Whale-Storm/Whale | /whale-rdma/src/main/java/org/apache/storm/messaging/ClusterAddressHost.java | UTF-8 | 396 | 1.789063 | 2 | [
"Apache-2.0",
"GPL-1.0-or-later",
"BSD-3-Clause",
"MIT",
"BSD-2-Clause"
] | permissive | package org.apache.storm.messaging;
/**
* locate org.apache.storm.messaging
* Created by MasterTj on 2019/10/12.
* CGCL RDMA Cluster Configuration
*/
public class ClusterAddressHost {
/**
* 网卡地址转换(TCP 转换 RDMA)
* @param host 传统网络IP地址
* @return
*/
public static String resovelAddressHost(String host){
return "i"+host;
}
}
| true |
3390c99c4bf9c2c75df062ec602792053e6f0444 | Java | asuwala/dziennik_treningowy | /app/src/main/java/com/example/ania/projekt/Fitness.java | UTF-8 | 2,601 | 2.78125 | 3 | [] | no_license | package com.example.ania.projekt;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
/**
* Ta klasa zawiera funkcje, kt�re obs�uguj� aktywnosc widoku fitnes.xml
* Pola klasy:
* @p zb zawiera odwolania do metod obsugujacych baze danych.
* @p czasT czas treningu
* @p dataT data treningu
* @p aktywnoscT rodzaj aktywnosci
* @p notatka dodatkowe komentarze u�ytownika
* Created by Kapibara on 2015-06-02.
* @autor Joana W�jcik
*/
public class Fitness extends Activity {
ZarzadcaBazy zb;
String czasT;
String dataT;
String notatka;
String styl;
/**
* Metoda wywolujaca sie po uruchomieniu biezacej instancji. Przelacza na widok
* fitnes.xml oraz steruje jego zachowaniem
*/
protected void onCreate(Bundle savedInstanceState) {
zb=new ZarzadcaBazy(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.fitnes);
String aktywnoscT="fitness";
Bundle extras = getIntent().getExtras();
if (extras != null) {
czasT = extras.getString("czas");
dataT = extras.getString("data");
}
else
{
final EditText czas1=(EditText)findViewById(R.id.Czas);
final EditText data1=(EditText)findViewById(R.id.Data);
czasT=czas1.getText().toString();
dataT=data1.getText().toString();
}
Button b2=(Button)findViewById(R.id.AnulujFitness);
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), rodzaj_Treningu.class);
startActivity(i);
}
});
Button b3=(Button)findViewById(R.id.ZapiszFitness);
styl="";
final double dystans=0;
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText not=(EditText)findViewById(R.id.notatkaFitness);
EditText kat=(EditText)findViewById(R.id.kategoriaFitness);
notatka=not.getText().toString();
String kategoria=kat.getText().toString();
String aktywnoscT="fitness";
zb.dodajTrening(dataT, czasT, aktywnoscT,
dystans, kategoria, notatka, styl);
Intent i = new Intent(getApplicationContext(), rodzaj_Treningu.class);
startActivity(i);
}
});
}
}
| true |
0e43d49fb924758ec341420117fb0d215fbd0178 | Java | mycodefarm/old-memory-code | /java/design-pattern/src/com/jimo/singleton/Test.java | UTF-8 | 693 | 2.71875 | 3 | [] | no_license | package com.jimo.singleton;
/**
* Created by root on 17-5-29.
*/
public class Test {
public static void main(String[] args) {
Singleton1 s1 = Singleton1.getInstance();
Singleton1 s2 = Singleton1.getInstance();
System.out.println(s1 == s2);
Singleton2 s3 = Singleton2.getInstance();
Singleton2 s4 = Singleton2.getInstance();
System.out.println(s3 == s4);
Singleton3 s5 = Singleton3.getInstance();
Singleton3 s6 = Singleton3.getInstance();
System.out.println(s5 == s6);
Singleton4 s7 = Singleton4.getInstance();
Singleton4 s8 = Singleton4.getInstance();
System.out.println(s7 == s8);
}
}
| true |
eaed6b94713e92e9890ffa5c84e3c92bdc5dcffa | Java | 1Eye4all/trust-framework | /dtf-webapp/src/main/java/org/mitre/dtf/model/Dependency.java | UTF-8 | 3,651 | 2.484375 | 2 | [
"Apache-2.0"
] | permissive | package org.mitre.dtf.model;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonBackReference;
@Entity
@Table(name = "Dependency")
@NamedQueries({
@NamedQuery(name = "Dependency.findAll", query = "select d from Dependency d ORDER BY d.id")
})
public class Dependency {
private long id; // unique identifier
private Card card; // the card this dependency belongs to
private String description; // human-readable description to be displayed
private Set<Tag> tags; // tags that are required by this dependency
/**
* Default empty parameter constructor.
*/
public Dependency() {
// left blank intentionally
}
public Dependency(String description) {
this.description = description;
}
/**
*
* @return the id
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public long getId() {
return id;
}
/**
*
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the card
*/
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "cardId", referencedColumnName = "id")
@JsonBackReference
public Card getCard() {
return card;
}
/**
* @param card the card to set
*/
public void setCard(Card card) {
this.card = card;
}
/**
*
* @return the description
*/
@Basic
@Column(name = "description")
public String getDescription() {
return description;
}
/**
*
* @param description the description
*/
public void setDescription(String description) {
this.description = description;
}
/**
* @return the tags
*/
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "DependencyTags",
joinColumns = @JoinColumn(name = "dependencyId", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name = "tagId", referencedColumnName = "id"))
public Set<Tag> getTags() {
return tags;
}
/**
* @param tags the tags to set
*/
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((description == null) ? 0 : description.hashCode());
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((tags == null) ? 0 : tags.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Dependency other = (Dependency) obj;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (id != other.id)
return false;
if (tags == null) {
if (other.tags != null)
return false;
} else if (!tags.equals(other.tags))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Dependency [id=" + id + ", description=" + description
+ ", tags=" + tags + "]";
}
}
| true |
9aba586d6a7bb3a7d8d644cc3943fb072b93114e | Java | AbdullahDmrl/Java_Kurs | /src/Gun10/_04_Soru.java | UTF-8 | 645 | 3.65625 | 4 | [] | no_license | package Gun10;
import java.util.Scanner;
public class _04_Soru {
public static void main(String[] args) {
// Girilen 3 basamaklı bir sayının basamaklarına göre tersini bir sayı olarak
// ekrana yazdırınız.Örneğin 435 -> 534 sayı olarak bulunacak.
Scanner oku=new Scanner(System.in);
System.out.print("3 basamaklı bir sayı giriniz:");
int sayi=oku.nextInt(); // 435
int birler= sayi%10; // 5
int onlar = (sayi/10)%10; // 3
int yuzler= sayi/100; // 4
int tersi = birler*100 + onlar*10 + yuzler;
System.out.println("tersi = " + tersi);
}
}
| true |
2ca1b19f4a26dffc2dc34ebeac1be0893a70691f | Java | AleksandrShcherbakov/sqlServerProject | /src/main/java/com/work/sqlServerProject/controller/CheckingController.java | WINDOWS-1251 | 32,097 | 1.90625 | 2 | [] | no_license | package com.work.sqlServerProject.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.work.sqlServerProject.Helper.ColorHelper;
import com.work.sqlServerProject.Helper.FileScanHelper;
import com.work.sqlServerProject.Helper.NoCarrierException;
import com.work.sqlServerProject.NBFparser.Parser;
import com.work.sqlServerProject.NBFparser.ParserHalper;
import com.work.sqlServerProject.Position.*;
import com.work.sqlServerProject.dao.CellNameDAO;
import com.work.sqlServerProject.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.nio.file.Path;
import java.sql.SQLException;
import java.util.*;
import java.util.stream.Collectors;
/**
* Created by a.shcherbakov on 24.06.2019.
*/
@Controller
public class CheckingController {
File filePoints=null;
public static String[]LTE;
public static String[]UMTS;
@Autowired
private CellNameDAO cellNameDAO;
private Map<Integer, Position> positions = null;
List<Point> points = null;
@Value("${list.filesNMF}")
String[] listPath;
List<String> listWithNmf = null;
List<String> listFilesBts = null;
@Value("${filesBTS}")
String pathToNbf;
boolean useBTSFile = false;
String pathToBts = null;
List<String> btsLines = null;
List<String> alredyLoadedFiles=new ArrayList<>();
@RequestMapping(value = "/reset", method = RequestMethod.GET)
public String reset(Model model){
alredyLoadedFiles.clear();
points.clear();
return "redirect:/inputScan";
}
@RequestMapping(value = "/inputScan", method = RequestMethod.GET)
public String showSelectScanFilePage(Model model){
List<Path>list=new ArrayList<>();
LTE=MainController.LTE;
UMTS=MainController.UMTS;
for (String s : listPath) {
List<Path> nmfs = FileScanHelper.getFiles(s);
list.addAll(nmfs);
}
list.sort(FileScanHelper.comparator);
List<String>listStr=list.stream().map(p->p.toString()).peek(p-> System.out.println(p)).collect(Collectors.toList());
this.listWithNmf=listStr;
PathScanFile pathScanFile = new PathScanFile();
List<String>filesBts = getBtsPaths(pathToNbf).stream().map(p->p.toString()).peek(System.out::println).collect(Collectors.toList());
this.listFilesBts=filesBts;
model.addAttribute("btss",filesBts);
model.addAttribute("listFiles",listStr);
model.addAttribute("pathScanFile", pathScanFile);
model.addAttribute("loaded", alredyLoadedFiles);
if (points!=null){
model.addAttribute("countOfPoints", points.size());
}
return "checking/checkPathFileScan";
}
@RequestMapping(value = "/inputScan", method = RequestMethod.POST)
public String loadScanAndSelectPos(Model model, @ModelAttribute ("pathScanFile") PathScanFile pathScanFile,
@RequestParam (required = false,name = "file") String files,
@RequestParam (required = false, name= "isBTS") String isBts,//
@RequestParam (required = false, name = "bts") String btsPath){
if (isBts==null){
this.useBTSFile=false;
this.pathToBts=null;
this.btsLines=null;
}
else
if (isBts!=null){
this.useBTSFile=true;
if (!pathScanFile.getBtsFile().isEmpty()){
String btsFileName=pathScanFile.getBtsFile().getOriginalFilename();
if ((btsFileName.endsWith(".csv")|| btsFileName.endsWith(".nbf"))&&btsFileName.length()>0){
btsLines=new ArrayList<>();
try {
BufferedReader reader=new BufferedReader(new InputStreamReader(new ByteArrayInputStream(pathScanFile.getBtsFile().getBytes())));
while (reader.ready()){
btsLines.add(reader.readLine());
}
reader.close();
} catch (IOException e) {
System.out.println(" ");
e.printStackTrace();
}
}
else model.addAttribute("wrongBtsFile"," ");
}
else
if (!pathScanFile.getToBts().equals("")){
this.pathToBts=pathScanFile.getToBts();
try {
btsLines=new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(pathToBts)));
String s = reader.readLine();
while (s!=null){
btsLines.add(s);
s=reader.readLine();
}
reader.close();
} catch (IOException e) {
System.out.println(pathToBts+ " BTS ");
model.addAttribute("nobtsread", " "+pathToBts);
}
}
else
if (btsPath!=null){
this.pathToBts=btsPath;
try {
btsLines=new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(pathToBts)));
String s = reader.readLine();
while (s!=null){
btsLines.add(s);
s=reader.readLine();
}
reader.close();
} catch (IOException e) {
System.out.println(pathToBts+ " BTS ");
model.addAttribute("nobtsread", " "+pathToBts);
}
}
else {
model.addAttribute("nobts", " BTS , .");
model.addAttribute("btss",this.listFilesBts);
model.addAttribute("listFiles",this.listWithNmf);
return "checking/checkPathFileScan";
}
}
StringBuilder stringBuilder=new StringBuilder();
if(pathScanFile.getScanFile().length>0) {
for (MultipartFile multipartFile:pathScanFile.getScanFile()) {
if (!multipartFile.isEmpty()) {
String scanFileName = multipartFile.getOriginalFilename().intern();
if (!this.alredyLoadedFiles.contains(scanFileName)) {
if (scanFileName.endsWith(".nmf") && scanFileName.length() > 0) {
stringBuilder.append(readFiles(multipartFile));
this.alredyLoadedFiles.add(scanFileName);
} else model.addAttribute("wrongNmfFile", " ");
} else System.out.println(" " + scanFileName + " ");
}
}
}
if (!pathScanFile.getUrl().equals("")) {
String fullPath=pathScanFile.getUrl();
String nameOfFile=fullPath.substring(fullPath.lastIndexOf("\\")+1,fullPath.length()).intern();
if (alredyLoadedFiles.contains(nameOfFile)) {
System.out.println(pathScanFile.getUrl() + " ");
} else {
stringBuilder.append(readFiles(fullPath));
System.out.println(pathScanFile.getUrl());
System.out.println(nameOfFile);
alredyLoadedFiles.add(nameOfFile);
}
}
if (files!=null) {
String[] file = files.split(",");
for (String s : file) {
String nameOfFile=s.substring(s.lastIndexOf("\\")+1,s.length()).intern();
if (alredyLoadedFiles.contains(nameOfFile)) {
System.out.println(s + " ");
} else {
stringBuilder.append(readFiles(s));
System.out.println(nameOfFile);
alredyLoadedFiles.add(nameOfFile.intern());
}
}
}
if (pathScanFile.getUrl().equals("") && files==null && alredyLoadedFiles.size()==0){
model.addAttribute("nofiles", " .");
model.addAttribute("btss",this.listFilesBts);
model.addAttribute("listFiles",this.listWithNmf);
return "checking/checkPathFileScan";
}
if (points.size()==0){
model.addAttribute("nopoints", " . .");
model.addAttribute("btss",this.listFilesBts);
model.addAttribute("listFiles",this.listWithNmf);
return "checking/checkPathFileScan";
}
return "redirect:/checkPos";
}
@RequestMapping(value = "/checkPos", method = RequestMethod.GET)
public String showSelectPos(Model model){
PosForCheck posForCheck = new PosForCheck();
model.addAttribute("pos", posForCheck);
return "checking/checkPos";
}
public List<Path> getBtsPaths(String pathDir) {
File dir = new File(pathDir); //path
File[] arrFiles = dir.listFiles();
if (arrFiles != null) {
List<Path> files = Arrays.stream(arrFiles).map(p -> p.toPath()).filter(p -> p.toString().endsWith(".csv") || p.toString().endsWith(".nbf")).peek(System.out::println)
.sorted(FileScanHelper.comparator).collect(Collectors.toList());
return files;
}
else return new ArrayList<>();
}
public String readFiles(String path){
List<String> parsered;
try {
parsered = ParserHalper.createinSrtings(path);
}
catch (IOException e){
return " .";
}
int size1=0;
if (points!=null){
size1=points.size();
}
if (points==null) {
points = Parser.getPointsFromScan(parsered);
}
else points.addAll(Parser.getPointsFromScan(parsered));
int size2=points.size();
if (points.size()!=0 && size1!=size2) {
return " " + path + " ";
}
else return " "+ path + " ";
}
public String readFiles(MultipartFile path){
List<String> parsered;
try {
parsered = ParserHalper.createinSrtings(path);
}
catch (IOException e){
return " .";
}
int size1=0;
if (points!=null){
size1=points.size();
}
if (points==null) {
points = Parser.getPointsFromScan(parsered);
}
else points.addAll(Parser.getPointsFromScan(parsered));
int size2=points.size();
if (points.size()!=0 && size1!=size2) {
return " " + path + " ";
}
else return " "+ path + " ";
}
@RequestMapping(value = "/checkPos", method = RequestMethod.POST)
//@ResponseBody
public String selectPN(Model model, @ModelAttribute ("pos") PosForCheck posForCheck) throws IOException {
if (posForCheck.getPosnames().equals("")){
return " ";
}
positions=new HashMap<>();
StringBuilder res=new StringBuilder();
StringBuilder wrangs = new StringBuilder();
String[]poss=posForCheck.getPosnames().split(",");
for (String s : poss){
s=s.trim();
try {
int pos=Integer.parseInt(s);
int i=0;
try{
i=setPosition(pos);
}
catch (NoCarrierException e ){
e.printStackTrace();
int ch = e.getCh();
String wrang="";
if (ch==0){
wrang = e.getPos()+" - . .";
}
else {
wrang = " "+e.getPos()+". " + ch + " application.properties. .<br>";
}
wrangs.append(wrang);
res.append(wrang);
}
if (i==-1) {
if (useBTSFile) {
String wrang = " " + pos + " <br>";
wrangs.append(wrang);
res.append(wrang);
} else {
String wrang =" " + pos + " <br>";
wrangs.append(wrang);
res.append(wrang);
}
}
}
catch (SQLException e){
String wrang = " general, .<br>" +
"<a href='/inputScan'> </a>";
wrangs.append(wrang);
res.append(wrang);
model.addAttribute("wrangs", wrangs.toString());
return "checking/result";
}
catch (Exception e){
e.printStackTrace();
String wrang = " " +
" : "+s+"<br>";
wrangs.append(wrang);
res.append(wrang);
}
}
List<String>toTemplate=new ArrayList<>();
for (Map.Entry p : positions.entrySet()){
toTemplate.add(positions.get(p.getKey()).getInfoForTemplate());
res.append("<b>"+p.getKey()+"</b><br><br>"+
p.getValue().toString()+
positions.get(p.getKey()).printDetailInfo()+"<br>");
res.append("=================================================================<br><br>");
}
model.addAttribute("wrangs", wrangs.toString());
model.addAttribute("allInfo", toTemplate);
//return res.toString();
return "checking/result";
}
public int setPosition(Integer posname) throws SQLException, NullPointerException {
Position position=null;
List<CellInfo> list=null;
if (posname!=null) {
if (useBTSFile){
String param = btsLines.get(0);
String[]parameters=param.split(";");
int i=0;
for (int s=0;s<parameters.length;s++){
if (parameters[s].equals("SITE")) {
i = s;
break;
}
}
int finalI = i;
list = btsLines.stream().filter(p->p.split(";")[finalI].equals(posname+"")).map(p->new CellInfo(param, p)).collect(Collectors.toList());
if (list.size() == 0) {
return -1;
}
}
else {
try {
list = cellNameDAO.getInfoForBS(posname);
}
catch (Exception e){
throw new SQLException();
}
if (list.size() == 0) {
return -1;
}
}
position = new Position(list);
}
position.setPointsInPosition(points);
position.setAllPointsToCells();
position.findBestScan();
this.positions.put(posname,position);
return 1;
}
@RequestMapping(value = "/map", method = RequestMethod.GET)
public String getMap(Model model,
@RequestParam(required = false, name = "about") String about,
@RequestParam(required = false, name = "posName") String number,
@RequestParam(required = false, name = "cell") String cell){
Integer pos = Integer.parseInt(number);
List<Cell>cellList= positions.get(pos).getCells().stream().filter(p->p.getAbout().equals(about)).collect(Collectors.toList());
Map<String, String> paramColor=new HashMap<>();
for (int i=0; i<cellList.size();i++){
if (cellList.get(i).getAbout().startsWith("GSM")){
Cell2G p = (Cell2G) cellList.get(i);
paramColor.put(p.getBcchBsic(), ColorHelper.mColors[i]);
}
else
if (cellList.get(i).getAbout().startsWith("UMTS")) {
Cell3G p = (Cell3G) cellList.get(i);
paramColor.put(p.getScr() + "", ColorHelper.mColors[i]);
}
else
if (cellList.get(i).getAbout().startsWith("LTE")){
Cell4G p = (Cell4G) cellList.get(i);
paramColor.put(p.getPCI()+"", ColorHelper.mColors[i]);
}
}
List<CellToMap> cellToMapList=null;
if (about.startsWith("GSM")) {
cellToMapList = cellList.stream().map(p -> (Cell2G) p).map(p -> new CellToMap(p.getCi(), p.getAzimuth(), paramColor.get(p.getBcchBsic()))).collect(Collectors.toList());
}
else
if (about.startsWith("UMTS")) {
cellToMapList = cellList.stream().map(p -> (Cell3G) p).map(p -> new CellToMap(p.getCi(), p.getAzimuth(), paramColor.get(p.getScr()+""))).collect(Collectors.toList());
}
else
if (about.startsWith("LTE")) {
cellToMapList = cellList.stream().map(p -> (Cell4G) p).map(p -> new CellToMap(p.getCi(), p.getAzimuth(), paramColor.get(p.getPCI()+""))).collect(Collectors.toList());
}
Set<Point> pointsTomap=new HashSet<>();
for (Cell c : cellList){
if (about.startsWith("GSM")) {
Cell2G g = (Cell2G)c;
Set<Point> set = positions.get(pos).getAllPointsInPosition().stream().filter(p -> p.getMainMap().get(about)!=null && p.getMainMap().get(about).get(g.getBcchBsic())!=null).collect(Collectors.toSet());
pointsTomap.addAll(set);
}
else
if (about.startsWith("UMTS")) {
Cell3G g = (Cell3G)c;
Set<Point> set = positions.get(pos).getAllPointsInPosition().stream().filter(p -> p.getMainMap().get(about)!=null && p.getMainMap().get(about).get(g.getScr()+"")!=null).collect(Collectors.toSet());
pointsTomap.addAll(set);
}
else
if (about.startsWith("LTE")) {
Cell4G g = (Cell4G)c;
Set<Point> set = positions.get(pos).getAllPointsInPosition().stream().filter(p -> p.getMainMap().get(about)!=null && p.getMainMap().get(about).get(g.getPCI()+"")!=null).collect(Collectors.toSet());
pointsTomap.addAll(set);
}
}
if (cell!=null){
String param="";
for (Cell c : cellList){
if (c.getCi()==Integer.parseInt(cell)){
param=c.getParam();
model.addAttribute("azimuthOfsector",c.getAzimuth());
}
}
String finalParam = param;
List<PointToMap> listWithLevels = pointsTomap.stream().map(m->new PointToMap(m, about, finalParam)).
peek(p-> System.out.println(p.getLongitude()+" "+p.getLatitude()+" "+p.getColor()+" "+p.getParam())).collect(Collectors.toList());
model.addAttribute("listWithLevels",listWithLevels);
if (about.startsWith("GSM")){
Set<String> set=new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String a=o1.split(" ")[0].split("_")[0];
String b=o2.split(" ")[0].split("_")[0];
double a1=Double.parseDouble(a);
double b1=Double.parseDouble(b);
if (a1>b1){
return 1;
}
else
if (a1<b1){
return -1;
}
else return 0;
}
});
for (Map.Entry s : HelperCell.colerSet2G.entrySet()){
set.add(s.getKey().toString()+" "+s.getValue().toString());
}
model.addAttribute("colorSet",set);
}
else
if (about.startsWith("UMTS")){
Set<String> set=new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String a=o1.split(" ")[0].split("_")[0];
String b=o2.split(" ")[0].split("_")[0];
double a1=Double.parseDouble(a);
double b1=Double.parseDouble(b);
if (a1>b1){
return 1;
}
else
if (a1<b1){
return -1;
}
else return 0;
}
});
for (Map.Entry s : HelperCell.colorSet3G.entrySet()){
set.add(s.getKey().toString()+" "+s.getValue().toString());
}
model.addAttribute("colorSet", set);
}
else
if (about.startsWith("LTE")){
Set<String> set=new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String a=o1.split(" ")[0].split("_")[0];
String b=o2.split(" ")[0].split("_")[0];
double a1=Double.parseDouble(a);
double b1=Double.parseDouble(b);
if (a1>b1){
return 1;
}
else
if (a1<b1){
return -1;
}
else return 0;
}
});
for (Map.Entry s : HelperCell.colorSet4G.entrySet()){
set.add(s.getKey().toString()+" "+s.getValue().toString());
}
model.addAttribute("colorSet",set);
}
}
List<PointToMap> list = pointsTomap.stream().map(p->new PointToMap(p, about, paramColor)).collect(Collectors.toList());
double maxDist=500;
boolean nopoints=false;
try {
maxDist=pointsTomap.stream().mapToDouble(p->p.getDistToPos().get(pos)).max().getAsDouble();
}
catch (NoSuchElementException e){
e.printStackTrace();
nopoints=true;
}
if (nopoints){
model.addAttribute("nopoints", " "+pos+" .");
}
model.addAttribute("pos",pos);
model.addAttribute("about", about);
model.addAttribute("cells", cellToMapList);
model.addAttribute("pointss", list);
model.addAttribute("lon", positions.get(pos).getCells().get(0).getLongitude());
model.addAttribute("lat", positions.get(pos).getCells().get(0).getLalitude());
model.addAttribute("radius",maxDist);
return "map";
}
@RequestMapping(value = "mapCell",method = RequestMethod.GET)
@ResponseBody
public String getMapCell(Model model,
@RequestParam(required = false, name = "about") String about,
@RequestParam(required = false, name = "posName") String number,
@RequestParam(required = false, name = "cell") String cell) {
ToJson toJson= new ToJson();
Integer pos = Integer.parseInt(number);
List<Cell> cellList = positions.get(pos).getCells().stream().filter(p -> p.getAbout().equals(about)).collect(Collectors.toList());
Map<String, String> paramColor = new HashMap<>();
for (int i = 0; i < cellList.size(); i++) {
if (cellList.get(i).getAbout().startsWith("GSM")) {
Cell2G p = (Cell2G) cellList.get(i);
paramColor.put(p.getBcchBsic(), ColorHelper.mColors[i]);
} else if (cellList.get(i).getAbout().startsWith("UMTS")) {
Cell3G p = (Cell3G) cellList.get(i);
paramColor.put(p.getScr() + "", ColorHelper.mColors[i]);
} else if (cellList.get(i).getAbout().startsWith("LTE")) {
Cell4G p = (Cell4G) cellList.get(i);
paramColor.put(p.getPCI() + "", ColorHelper.mColors[i]);
}
}
List<CellToMap> cellToMapList = null;
if (about.startsWith("GSM")) {
cellToMapList = cellList.stream().map(p -> (Cell2G) p).map(p -> new CellToMap(p.getCi(), p.getAzimuth(), paramColor.get(p.getBcchBsic()))).collect(Collectors.toList());
} else if (about.startsWith("UMTS")) {
cellToMapList = cellList.stream().map(p -> (Cell3G) p).map(p -> new CellToMap(p.getCi(), p.getAzimuth(), paramColor.get(p.getScr() + ""))).collect(Collectors.toList());
} else if (about.startsWith("LTE")) {
cellToMapList = cellList.stream().map(p -> (Cell4G) p).map(p -> new CellToMap(p.getCi(), p.getAzimuth(), paramColor.get(p.getPCI() + ""))).collect(Collectors.toList());
}
Set<Point> pointsTomap = new HashSet<>();
for (Cell c : cellList) {
if (about.startsWith("GSM")) {
Cell2G g = (Cell2G) c;
Set<Point> set = positions.get(pos).getAllPointsInPosition().stream().filter(p -> p.getMainMap().get(about) != null && p.getMainMap().get(about).get(g.getBcchBsic()) != null).collect(Collectors.toSet());
pointsTomap.addAll(set);
} else if (about.startsWith("UMTS")) {
Cell3G g = (Cell3G) c;
Set<Point> set = positions.get(pos).getAllPointsInPosition().stream().filter(p -> p.getMainMap().get(about) != null && p.getMainMap().get(about).get(g.getScr() + "") != null).collect(Collectors.toSet());
pointsTomap.addAll(set);
} else if (about.startsWith("LTE")) {
Cell4G g = (Cell4G) c;
Set<Point> set = positions.get(pos).getAllPointsInPosition().stream().filter(p -> p.getMainMap().get(about) != null && p.getMainMap().get(about).get(g.getPCI() + "") != null).collect(Collectors.toSet());
pointsTomap.addAll(set);
}
}
if (cell != null) {
String param = "";
for (Cell c : cellList) {
if (c.getCi() == Integer.parseInt(cell)) {
param = c.getParam();
model.addAttribute("azimuthOfsector", c.getAzimuth());
toJson.setAzimuthOfsector(c.getAzimuth());
}
}
String finalParam = param;
List<PointToMap> listWithLevels = pointsTomap.stream().map(m -> new PointToMap(m, about, finalParam)).
peek(p -> System.out.println(p.getLongitude() + " " + p.getLatitude() + " " + p.getColor() + " " + p.getParam())).collect(Collectors.toList());
model.addAttribute("listWithLevels", listWithLevels);
toJson.setPoints(listWithLevels);
if (about.startsWith("GSM")) {
Set<String> set = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String a = o1.split(" ")[0].split("_")[0];
String b = o2.split(" ")[0].split("_")[0];
double a1 = Double.parseDouble(a);
double b1 = Double.parseDouble(b);
if (a1 > b1) {
return 1;
} else if (a1 < b1) {
return -1;
} else return 0;
}
});
for (Map.Entry s : HelperCell.colerSet2G.entrySet()) {
set.add(s.getKey().toString() + " " + s.getValue().toString());
}
model.addAttribute("colorSet", set);
toJson.setColorset(set);
} else if (about.startsWith("UMTS")) {
Set<String> set = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String a = o1.split(" ")[0].split("_")[0];
String b = o2.split(" ")[0].split("_")[0];
double a1 = Double.parseDouble(a);
double b1 = Double.parseDouble(b);
if (a1 > b1) {
return 1;
} else if (a1 < b1) {
return -1;
} else return 0;
}
});
for (Map.Entry s : HelperCell.colorSet3G.entrySet()) {
set.add(s.getKey().toString() + " " + s.getValue().toString());
}
model.addAttribute("colorSet", set);
toJson.setColorset(set);
} else if (about.startsWith("LTE")) {
Set<String> set = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String a = o1.split(" ")[0].split("_")[0];
String b = o2.split(" ")[0].split("_")[0];
double a1 = Double.parseDouble(a);
double b1 = Double.parseDouble(b);
if (a1 > b1) {
return 1;
} else if (a1 < b1) {
return -1;
} else return 0;
}
});
for (Map.Entry s : HelperCell.colorSet4G.entrySet()) {
set.add(s.getKey().toString() + " " + s.getValue().toString());
}
model.addAttribute("colorSet", set);
toJson.setColorset(set);
}
}
ObjectMapper mapper= new ObjectMapper();
String res=null;
try {
res = mapper.writeValueAsString(toJson);
} catch (JsonProcessingException e) {
e.printStackTrace();
System.out.println("json ");
}
return res;
}
}
| true |
72f0437519c4ba12531e1ac618461cd4a208240b | Java | wucongfight/order1 | /src/main/java/com/yijiupi/service/OrderService.java | UTF-8 | 1,238 | 1.960938 | 2 | [] | no_license | package com.yijiupi.service;
import com.github.pagehelper.PageInfo;
import com.yijiupi.entity.Order;
import java.util.List;
/**
* @Author: WuCong
* @Date: 2019/1/17 11:11
*/
public interface OrderService {
/**
* 分页查询订单基本信息
*
* @param pageNum 当前页码
* @param pageSize 每页条数
* @param cityId 城市id
* @return
*/
PageInfo<Order> selectOrderByCityId(Integer pageNum, Integer pageSize, Integer cityId);
/**
* 根据主键删除订单基本信息
*
* @param id 主键
* @return
*/
int deleteByPrimaryKey(Long id);
/**
* 修改订单基本信息
*
* @param record 订单
* @return
*/
int updateByPrimaryKey(Order record);
/**
* 增加订单基本信息
*
* @param record 订单
* @return
*/
int insert(Order record);
/**
* 按条件查询订单信息
*
* @param cityId 城市id
* @param orderType 订单类型
* @return
*/
List<Order> selectOrder(Integer cityId, Byte orderType);
/**
* 根据主键查询订单基本信息
*
* @param id 主键
* @return
*/
Order selectById( Long id);
}
| true |
402aff6d5cbc252639844d02b50734df8c91b63d | Java | vishnupedireddy/accredilinkApplication | /rates/src/main/java/com/exchange/rates/repository/ExchangeRatesRepository.java | UTF-8 | 326 | 1.515625 | 2 | [] | no_license | package com.exchange.rates.repository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.exchange.rates.entity.ExchangeRatesInfo;
@Repository
public interface ExchangeRatesRepository extends CrudRepository<ExchangeRatesInfo, Long> {
}
| true |
6299198d5b9fd121fd739d9df2a534d4e0e799ef | Java | dansimpson/lillibs | /lilcluster/src/test/java/com/github/dansimpson/lilcluster/ClusterTest.java | UTF-8 | 5,158 | 2.359375 | 2 | [
"Apache-2.0"
] | permissive | package com.github.dansimpson.lilcluster;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.hamcrest.CoreMatchers;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.dansimpson.lilcluster.Peer.RequestTimeout;
public class ClusterTest {
private static final String PING_STR = "ping";
private static final byte[] PING = PING_STR.getBytes();
private static final Logger log = LoggerFactory.getLogger(ClusterTest.class);
private TestCluster cluster1;
private TestCluster cluster2;
private TestCluster cluster3;
@BeforeClass
public static void config() {
// System.setProperty(org.slf4j.impl.SimpleLogger.DEFAULT_LOG_LEVEL_KEY, "TRACE");
}
@Before
public void setup() throws Exception {
cluster1 = new TestCluster(10001, new int[] { 10001, 10002, 10003 });
cluster2 = new TestCluster(10002, new int[] { 10001, 10002, 10003 });
cluster3 = new TestCluster(10003, new int[] { 10001, 10002, 10003 });
cluster1.start();
cluster2.start();
cluster3.start();
}
@After
public void teardown() throws Exception {
cluster1.stop();
cluster2.stop();
cluster3.stop();
}
@Test(timeout = 2000)
public void testClustering() throws Exception {
cluster1.awaitForPeers(2);
cluster2.awaitForPeers(2);
cluster3.awaitForPeers(2);
Assert.assertEquals(2, cluster1.cluster().getActivePeerAddresses().size());
Assert.assertEquals(2, cluster2.cluster().getActivePeerAddresses().size());
Assert.assertEquals(2, cluster3.cluster().getActivePeerAddresses().size());
Assert.assertThat(cluster1.cluster().getActivePeerAddresses(),
CoreMatchers.hasItems(new InetSocketAddress("localhost", 10003), new InetSocketAddress("localhost", 10002)));
Assert.assertThat(cluster2.cluster().getActivePeerAddresses(),
CoreMatchers.hasItems(new InetSocketAddress("localhost", 10003), new InetSocketAddress("localhost", 10001)));
Assert.assertThat(cluster3.cluster().getActivePeerAddresses(),
CoreMatchers.hasItems(new InetSocketAddress("localhost", 10002), new InetSocketAddress("localhost", 10001)));
}
@Test(timeout = 5000)
public void testBroadcast() throws Exception {
cluster1.awaitForPeers(2);
cluster2.cluster().sendData(PING);
while (cluster1.messages.size() < 1) {
Thread.sleep(1);
}
Assert.assertArrayEquals(PING, cluster1.messages.get(0));
}
@Test(timeout = 5000)
public void testRequestSync() throws Exception {
cluster1.awaitForPeers(2);
Optional<Peer> peer = cluster1.cluster().getActivePeersByAttribute("port", "10002").findFirst();
Assert.assertTrue(peer.isPresent());
PeerResponse item = peer.get().requestSync(PING, 1, TimeUnit.SECONDS);
Assert.assertEquals(PING_STR, item.getBufferString().get());
}
@Test(timeout = 5000)
public void testRequestFuture() throws Exception {
cluster1.awaitForPeers(2);
Optional<Peer> peer = cluster1.cluster().getActivePeersByAttribute("port", "10002").findFirst();
Assert.assertTrue(peer.isPresent());
CompletableFuture<PeerResponse> item = peer.get().request(PING, 1, TimeUnit.SECONDS);
Assert.assertEquals(PING_STR, item.get().getBufferString().get());
}
@Test(timeout = 5000)
public void testRequestCallback() throws Exception {
cluster1.awaitForPeers(2);
Optional<Peer> peer = cluster1.cluster().getActivePeersByAttribute("port", "10002").findFirst();
Assert.assertTrue(peer.isPresent());
LinkedBlockingQueue<PeerResponse> queue = new LinkedBlockingQueue<>();
peer.get().request(PING, (r) -> queue.add(r), 1, TimeUnit.SECONDS);
PeerResponse response = queue.take();
Assert.assertEquals(PING_STR, response.getBufferString().get());
}
@Test(timeout = 5000)
public void testRequestMulti() throws Exception {
cluster1.awaitForPeers(2);
CompletableFuture<ClusterResponse> item = cluster1.cluster().sendRequest(PING, 1l, TimeUnit.SECONDS);
item.get().getResponses().forEach((r) -> {
Assert.assertTrue(r.isSuccess());
Assert.assertEquals(PING_STR, r.getBufferString().get());
});
}
@Test(timeout = 5000)
public void testScopeSend() throws Exception {
cluster1.awaitForPeers(2);
PeerScope scope = cluster1.cluster()
.scoped()
.filterAttribute("port", "10002")
.withDefaultTimeout(100, TimeUnit.MILLISECONDS)
.build();
scope.sendData(PING);
while (cluster2.messages.size() < 1) {
Thread.sleep(1);
}
Assert.assertArrayEquals(PING, cluster2.messages.get(0));
}
@Test(timeout = 2000)
public void testTimeout() throws Exception {
cluster1.awaitForPeers(2);
PeerScope scope = cluster1.cluster()
.scoped()
.filterAttribute("port", "10002")
.withDefaultTimeout(0, TimeUnit.MILLISECONDS)
.build();
PeerResponse item = scope.sendRequest(PING).get().getResponses().get(0);
Assert.assertTrue(item.isError());
Assert.assertTrue(item.getError().get() instanceof RequestTimeout);
}
}
| true |
781e1f1efed4281230dd05e6d6d8ae71c114586b | Java | vulonggiao0207/OrderSystem-2.0 | /app/src/main/java/com/giao/ordersystem/Category_Expand_List_Adapter.java | UTF-8 | 3,065 | 2.234375 | 2 | [] | no_license | package com.giao.ordersystem;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.ArrayList;
/**
* Created by Long on 9/13/2016.
*/
public class Category_Expand_List_Adapter extends BaseExpandableListAdapter {
private Context context;
private ArrayList<CategoryBO> groups;
public Category_Expand_List_Adapter(Context context, ArrayList<CategoryBO> groups) {
this.context = context;
this.groups = groups;
}
@Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<DishBO> chList = groups.get(groupPosition)
.getDishes();
return chList.get(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
DishBO child = (DishBO) getChild(groupPosition,
childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.order_details_dish_layout, null);
}
TextView dish = (TextView) convertView.findViewById(R.id.dishButton);
dish.setText(child.getDishName().toString());
return convertView;
}
@Override
public int getChildrenCount(int groupPosition) {
ArrayList<DishBO> chList = groups.get(groupPosition)
.getDishes();
return chList.size();
}
@Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
@Override
public int getGroupCount() {
return groups.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
CategoryBO group = (CategoryBO) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.order_details_category_layout, null);
}
//Button tv = (Button) convertView.findViewById(R.id.categoryButton);
TextView tv = (TextView) convertView.findViewById(R.id.categoryButton);
tv.setText(group.getCategoryName());
return convertView;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
} | true |
ee324c1010d344667c092bf8c1cfb97b7818fd08 | Java | SwapnaPanchomarthi/Maven.Quiz5 | /src/main/java/rocks/zipcode/io/quiz4/objectorientation/PalindromeObject.java | UTF-8 | 878 | 3.359375 | 3 | [] | no_license | package rocks.zipcode.io.quiz4.objectorientation;
/**
* @author leon on 18/12/2018.
*/
public class PalindromeObject {
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
private String string;
public PalindromeObject(String input) {
this.string=input;
}
public String[] getAllPalindromes(){
return null;
}
public Boolean isPalindrome(){
StringBuffer sb1 = new StringBuffer(string);
StringBuffer sb2 = sb1.reverse();
boolean flag = false;
if(sb1.equals(sb2))
flag=true;
else flag=false;
return flag;
}
public String reverseString(){
StringBuffer sb1 = new StringBuffer(string);
StringBuffer sb2 = sb1.reverse();
return sb2.toString();
}
}
| true |
71d596b9c66f64c4e45b615a14953cd8c076a443 | Java | a-cespedes/DigitalContentApp | /DigitalContentWsWeb/src/DigitalContentWsWeb/DigitalContentWebService.java | UTF-8 | 6,417 | 2.328125 | 2 | [] | no_license | package DigitalContentWsWeb;
import javax.enterprise.context.RequestScoped;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import com.ibm.wsdl.util.IOUtils;
import java.awt.PageAttributes.MediaType;
import java.io.IOException;
import java.nio.channels.IllegalSelectorException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import DigitalContentInfo.DigitalContent;
import sun.net.www.content.text.plain;
@RequestScoped
@Path("")
@Produces({ "application/xml", "application/json" })
@Consumes({ "application/xml", "application/json" })
public class DigitalContentWebService {
@Path("/contents/{id}")
@GET
@Produces("application/json")
public Response getContents(@PathParam("id") String key){
try{
Connection connection = getDataSourceConnection();
Statement st = connection.createStatement();
ResultSet r = st.executeQuery("select c.* from public.contents c where c.content_key = '" + key + "'");
DigitalContent dc = new DigitalContent();
if(!r.isBeforeFirst()){
return Response.status(404).entity("Not Found").build();
}
else{
while(r.next()){
dc.setKey(r.getString("content_key"));
dc.setPath(r.getString("path"));
dc.setDescription(r.getString("description"));
dc.setOwner(r.getString("content_owner"));
}
connection.close();
st.close();
return Response.status(200).entity(dc).build();
}
}catch(SQLException ex){
return Response.status(500).entity("SQL error").build();
}catch (IllegalStateException ex){
return Response.status(500).entity("DataSource error.").build();
}
}
@POST
@Path("/contents")
@Consumes("application/json")
@Produces("application/json")
public Response upload(DigitalContent dc){
try{
Connection connection = getDataSourceConnection();
Statement st = connection.createStatement();
st.executeUpdate("INSERT INTO public.contents (content_key,path,description,content_owner) "
+ "VALUES('" + dc.getKey() + "', "
+ " '" + dc.getPath() + "', "
+ " '" + dc.getDescription() + "', "
+ " '" + dc.getOwner() + "')");
connection.close();
st.close();
return Response.status(201).entity(dc.getKey()).build();
}catch(SQLException ex){
return Response.status(500).entity("SQL error").build();
}catch (IllegalStateException ex){
return Response.status(500).entity("DataSource error.").build();
}
}
@Path("/contents/{id}")
@DELETE
@Produces("application/json")
public Response delete(@PathParam("id") String key){
try{
Connection connection = getDataSourceConnection();
Statement st = connection.createStatement();
st.executeUpdate("delete from public.contents c where c.content_key = '" + key + "'");
connection.close();
st.close();
return Response.status(204).build();
}catch(SQLException ex){
return Response.status(500).entity("SQL error").build();
}catch (IllegalStateException ex){
return Response.status(500).entity("DataSource error.").build();
}
}
@Path("/contents/owner/{name}")
@GET
@Produces("application/json")
public Response getContentsByOwner(@PathParam("name") String owner){
try{
Connection connection = getDataSourceConnection();
Statement st = connection.createStatement();
ResultSet r = st.executeQuery("select c.* from public.contents c where c.content_owner = '" + owner + "'");
if(!r.isBeforeFirst()){
return Response.status(404).entity("Not Found").build();
}
else{
Set<DigitalContent> results = new HashSet<>();
while(r.next()){
DigitalContent dc = new DigitalContent();
dc.setKey(r.getString("content_key"));
dc.setPath(r.getString("path"));
dc.setDescription(r.getString("description"));
dc.setOwner(r.getString("content_owner"));
results.add(dc);
}
connection.close();
st.close();
return Response.status(200).entity(results).build();
}
}catch(SQLException ex){
return Response.status(500).entity("SQL error").build();
}catch (IllegalStateException ex){
return Response.status(500).entity("DataSource error.").build();
}
}
@Path("/contents/search/{word}")
@GET
@Produces("application/json")
public Response getContentsBySearch(@PathParam("word") String description){
try{
Connection connection = getDataSourceConnection();
Statement st = connection.createStatement();
ResultSet r = st.executeQuery("select c.* from public.contents c where c.description LIKE '%" + description + "%'");
if(!r.isBeforeFirst()){
return Response.status(404).entity("Not Found").build();
}
else{
Set<DigitalContent> results = new HashSet<>();
while(r.next()){
DigitalContent dc = new DigitalContent();
dc.setKey(r.getString("content_key"));
dc.setPath(r.getString("path"));
dc.setDescription(r.getString("description"));
dc.setOwner(r.getString("content_owner"));
results.add(dc);
}
connection.close();
st.close();
return Response.status(200).entity(results).build();
}
}catch(SQLException ex){
return Response.status(500).entity("SQL error").build();
}catch (IllegalStateException ex){
return Response.status(500).entity("DataSource error.").build();
}
}
@Path("/contents/{id}")
@PUT
@Consumes("application/json")
public Response modifyContent(@PathParam("id") String key, String description){
try{
Connection connection = getDataSourceConnection();
Statement st = connection.createStatement();
st.executeUpdate("update public.contents set description = '" + description + "' where content_key = '" + key + "'");
connection.close();
st.close();
return Response.status(200).build();
}catch(SQLException ex){
return Response.status(500).entity("SQL error").build();
}catch (IllegalStateException ex){
return Response.status(500).entity("DataSource error.").build();
}
}
private Connection getDataSourceConnection() throws IllegalStateException{
try{
InitialContext cxt = new InitialContext();
DataSource ds = (DataSource) cxt.lookup("java:/PostgresXADS");
return ds.getConnection();
}catch(NamingException | SQLException ex){
throw new IllegalStateException();
}
}
}
| true |
4bc7b25e7746b06624172e6bbc3e5bf649566c35 | Java | Lootero4eg/anvlib_java | /anvlib_core/src/anvlib/Data/Database/BasePostgresSQLManager.java | UTF-8 | 604 | 2.5625 | 3 | [] | no_license | package anvlib.Data.Database;
public class BasePostgresSQLManager extends BaseDbManager
{
public BasePostgresSQLManager()
{
_DBDriver = "postgresql";
_defaultPort = 5432;
_connectionStringTemplate = "jdbc:%s://%s:%d/%s?user=%s&password=%s";
}
@Override
protected String GetFullConnectionString(String Server, String Login, String Password, String Database)
{
String res;
res = String.format(_connectionStringTemplate, _DBDriver, Server, _defaultPort, Database, Login, Password);
return res;
}
}
| true |
77388d8e125b0916e1199d59ad6d0df69a411173 | Java | lzz1023/ideal | /src/main/java/com/ideal/test/json2java/JsonLibTest.java | UTF-8 | 1,265 | 2.90625 | 3 | [] | no_license | package com.ideal.test.json2java;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import java.util.List;
/**
* 将json转化为entity
* @author lzz
* @date 2017/12/26
* @version 1.0
*/
public class JsonLibTest {
public static void main(String[] args) {
String jsonStr = "{\"name\":\"三班\",\"students\":[{\"age\":25,\"gender\":\"female\",\"grades\":\"三班\",\"name\":\"露西\",\"score\":{\"网络协议\":98,\"JavaEE\":92,\"计算机基础\":93},\"weight\":51.3},{\"age\":26,\"gender\":\"male\",\"grades\":\"三班\",\"name\":\"杰克\",\"score\":{\"网络安全\":75,\"Linux操作系统\":81,\"计算机基础\":92},\"weight\":66.5},{\"age\":25,\"gender\":\"female\",\"grades\":\"三班\",\"name\":\"莉莉\",\"score\":{\"网络安全\":95,\"Linux操作系统\":98,\"SQL数据库\":88,\"数据结构\":89},\"weight\":55}]}";
JSONObject obj = JSONObject.fromObject(jsonStr);
Grade grade = (Grade) JSONObject.toBean(obj,Grade.class);
JSONArray array = JSONArray.fromObject(grade.getStudents());
// List<Student> students = JSONArray.toList(array,Student.class);
grade.setStudents((List<Student>) JSONArray.toCollection(array,Student.class));
System.out.println(grade);
}
}
| true |
6e7ff84987de903d853e63c2188a06c4f353e82e | Java | AdrianTrejoG97/RSAapiedra | /rsa.java | UTF-8 | 4,475 | 2.609375 | 3 | [] | no_license |
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import static javafx.scene.input.KeyCode.M;
import static javafx.scene.input.KeyCode.N;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Alumno
*/
public class rsa extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@SuppressWarnings("empty-statement")
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String p= request.getParameter("p1");
String q= request.getParameter("q1");
String msg = request.getParameter("msg");
byte[] msgb = msg.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(msgb);
buffer.order(ByteOrder.LITTLE_ENDIAN);
int msgr = buffer.getShort();
int p1 = Integer.parseInt(p);
int q1 = Integer.parseInt(q);
int n=0;
n = p1 * q1;
int fi=0;
fi= (p1-1)*(q1-1);
int r = (1-fi+1)+fi;
int e=1;
int div = 2;
for(int con=1;con==fi;con++)
{
e=con;
if((e%div==1)&&(fi%div==1)) {
con=fi;
}
else{}
}
int d = 1%fi/e;
int cipher = (msgr^e)%n;
int mcipher= (cipher^d)%n;
String mciphers = ""+mcipher;
int len = mciphers.length();
byte[] descipher;
//ByteBuffer buf = ByteBuffer.allocate(len);
//buf.order(ByteOrder.BIG_ENDIAN);
//buf.putInt(mcipher);
//buf.flip();
//descipher = new byte[len];
//for(int c=0; c<len ;c++){
// descipher[c] = buf.array()[c];
//}
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Encriptacion RSA</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>La P es: " + p +"</h1>");
out.println("<h1>La Q es: " + q +"</h1>");
out.println("<h1>La N es: " + n +"</h1>");
out.println("<h1>La E es: " + e +"</h1>");
out.println("<h1>Phi es: " + fi +"</h1>");
out.println("<h1>La D es:" + d +"</h1>");
out.println("<h1>Mensaje cifrado es:" + cipher +"</h1>");
out.println("<h1>Mensaje descifrado es:" + mcipher +"</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| true |
38e4794d8dccc9349f5c641deb1f38fedb1eaf3a | Java | HalitGrpnr/ShoppingCart | /src/test/java/org/project/DisctountCalculationFactoryTest.java | UTF-8 | 1,130 | 2.28125 | 2 | [] | no_license | package org.project;
import org.junit.jupiter.api.Test;
import org.project.service.AmountCalculationImpl;
import org.project.service.DiscountCalculationService;
import org.project.service.RateCalculationImpl;
import static org.junit.jupiter.api.Assertions.*;
class DisctountCalculationFactoryTest {
@Test
void getService_forRate() {
DisctountCalculationFactory factory = new DisctountCalculationFactory();
DiscountCalculationService rateService = factory.getService(DiscountType.RATE);
assertTrue(rateService instanceof RateCalculationImpl);
}
@Test
void getService_forAmount() {
DisctountCalculationFactory factory = new DisctountCalculationFactory();
DiscountCalculationService amountService = factory.getService(DiscountType.AMOUNT);
assertTrue(amountService instanceof AmountCalculationImpl);
}
@Test
void getService_forNullType() {
DisctountCalculationFactory factory = new DisctountCalculationFactory();
DiscountCalculationService nullService = factory.getService(null);
assertEquals(null, nullService);
}
} | true |
8a65eb382d9075cbda42b15d31077874a6bc2982 | Java | 354976595/my_demo | /springdemo/src/test/java/com/example/springdemo/SpringdemoApplicationTests.java | UTF-8 | 1,050 | 1.914063 | 2 | [] | no_license | package com.example.springdemo;
import com.example.springdemo.cnf.BeanSetting;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.test.context.ActiveProfiles;
@SpringBootTest(classes = SpringdemoApplication.class)
@ActiveProfiles("dev")
public class SpringdemoApplicationTests {
@Autowired
private BeanSetting beanSetting;
@Autowired
private JavaMailSenderImpl
javaMailSender;
@Test
public void contextLoads() {
System.out.println(beanSetting);
}
@Test
public void testMail(){
SimpleMailMessage message = new SimpleMailMessage();
message.setSubject("11111通知-明天来狂神这听课");
message.setText("今晚7:30开会");
message.setTo("354976595.love@163.com");
message.setFrom("354976595.love@163.com");
javaMailSender.send(message);
}
}
| true |
b9c697f357431746b269e763a2b2a41ba761d20d | Java | frc-88/2017-Robot | /src/org/usfirst/frc/team88/robot/commands/AutoHopperHitRed.java | UTF-8 | 667 | 2.25 | 2 | [] | no_license | package org.usfirst.frc.team88.robot.commands;
import edu.wpi.first.wpilibj.command.CommandGroup;
/**
*
*/
public class AutoHopperHitRed extends CommandGroup {
public AutoHopperHitRed() {
addSequential(new DriveZeroYaw());
addParallel(new ShooterSetHood(.42));
addParallel(new FuelFlapOut());
addSequential(new DriveDistance(-6));
addSequential(new DriveRotateToAngle(-90));
addSequential(new Delay(0.1));
addSequential(new DriveDistance(2));
addSequential(new Delay(2.0));
addSequential(new DriveDistance(-1.0));
addSequential(new DriveRotateToAngle(-18.0));
addSequential(new AutoShoot(10.0));
}
}
| true |
32839f1b83501e1b4731e3f49c45122b0b1848f5 | Java | muirurikin/WeatherApp | /WeatherApp/app/src/main/java/Util/Utils.java | UTF-8 | 1,107 | 2.390625 | 2 | [
"MIT"
] | permissive | package Util;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by alexona on 10/13/16.
*/
public class Utils {
public static final String BASE_URL = "http://api.openweathermap.org/data/2.5/weather?q=";
public static final String ICON_URL ="http://openweathermap.org/img/w/";
public static JSONObject getObject(String tagName, JSONObject jsonObject) throws JSONException {
JSONObject jObj = jsonObject.getJSONObject(tagName);
return jObj;
}
public static String getString(String tagName, JSONObject jsonObject) throws JSONException {
return jsonObject.getString(tagName);
}
public static float getFloat(String tagName, JSONObject jsonObject) throws JSONException {
return (float) jsonObject.getDouble(tagName);
}
public static double getDouble(String tagName, JSONObject jsonObject) throws JSONException {
return (float) jsonObject.getDouble(tagName);
}
public static int getInt(String tagName, JSONObject jsonObject) throws JSONException {
return jsonObject.getInt(tagName);
}
}
| true |
92fed23aaef218b034ace7d5f9db24f30cadf871 | Java | galaxynetworkmain/galaxy_network_node | /gn-blockchain-node/src/main/java/org/gn/blockchain/facade/PendingState.java | UTF-8 | 370 | 2.015625 | 2 | [] | no_license | package org.gn.blockchain.facade;
import java.util.List;
import java.util.Set;
import org.gn.blockchain.core.*;
public interface PendingState {
/**
* @return pending state repository
*/
org.gn.blockchain.core.Repository getRepository();
/**
* @return list of pending transactions
*/
List<Transaction> getPendingTransactions();
}
| true |
2343b421b5910e9a377b6ff3e7c1676091ad0fe7 | Java | seasarorg/s2buri | /buri-core-test/src/test/java/org/escafe/buri/common/participantprovider/impl/ExcelBaseParticipantProvider_getAuthorizedUserIds_nameなし_Test.java | UTF-8 | 5,921 | 2.1875 | 2 | [] | no_license | package org.escafe.buri.common.participantprovider.impl;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.escafe.buri.engine.IdentityInfo;
import org.escafe.buri.engine.ParticipantContext;
import org.seasar.extension.unit.S2TestCase;
/**
* ExcelBaseParticipantProviderのテスト。
*/
public class ExcelBaseParticipantProvider_getAuthorizedUserIds_nameなし_Test
extends S2TestCase {
private ExcelBaseParticipantProvider participantProvider;
private UserDto ユーザ1;
private UserDto ユーザ2;
private UserDto ユーザ3;
private UserDto ユーザ4;
private UserDto ユーザ5;
private UserDto ゲスト;
private ParticipantContext context;
@Override
protected void setUp() throws Exception {
include("ExcelBaseParticipantProviderTest_nameなし.dicon");
ユーザ1 = new UserDto(1, "ユーザ1@ロールA");
ユーザ2 = new UserDto(2, "ユーザ2@ロールB");
ユーザ3 = new UserDto(3, "ユーザ3@ロールA");
ユーザ4 = new UserDto(4, "ユーザ4@ロールB");
ユーザ5 = new UserDto(5, "ユーザ5@ロールB");
ゲスト = new UserDto(99, "ゲスト");
context = new ParticipantContext();
}
public void testGetAuthorizedUserIds_ユーザ1_ロールA() throws Exception {
context.setParticipantName("ロールA");
context.setUserId(participantProvider.getUserId(ユーザ1));
List<IdentityInfo> ids =
participantProvider.getAuthorizedUserIds(context);
assertEquals(new IdentityInfo(1L), ids.get(0));
assertEquals(1, ids.size()); // 本人も含まれる
System.out.println(ids);
}
public void testGetAuthorizedUserIds_ユーザ2_ロールA() throws Exception {
context.setParticipantName("ロールA");
context.setUserId(participantProvider.getUserId(ユーザ2));
List<IdentityInfo> ids =
participantProvider.getAuthorizedUserIds(context);
assertEquals(new IdentityInfo(1L), ids.get(0));
assertEquals(1, ids.size());
System.out.println(ids);
}
public void testGetAuthorizedUserIds_ユーザ3_ロールA() throws Exception {
context.setParticipantName("ロールA");
context.setUserId(participantProvider.getUserId(ユーザ3));
List<IdentityInfo> ids =
participantProvider.getAuthorizedUserIds(context);
assertEquals(new IdentityInfo(3L), ids.get(0));
assertEquals(1, ids.size()); // 本人も含まれる
System.out.println(ids);
}
public void testGetAuthorizedUserIds_ユーザ4_ロールA() throws Exception {
context.setParticipantName("ロールA");
context.setUserId(participantProvider.getUserId(ユーザ4));
List<IdentityInfo> ids =
participantProvider.getAuthorizedUserIds(context);
assertEquals(new IdentityInfo(3L), ids.get(0));
assertEquals(1, ids.size());
System.out.println(ids);
}
public void testGetAuthorizedUserIds_ユーザ5_ロールA() throws Exception {
context.setParticipantName("ロールA");
context.setUserId(participantProvider.getUserId(ユーザ5));
List<IdentityInfo> ids =
participantProvider.getAuthorizedUserIds(context);
assertEquals(new IdentityInfo(3L), ids.get(0));
assertEquals(1, ids.size());
System.out.println(ids);
}
public void testGetAuthorizedUserIds_ゲスト_ロールA() throws Exception {
context.setParticipantName("ロールA");
context.setUserId(participantProvider.getUserId(ゲスト));
List<IdentityInfo> ids =
participantProvider.getAuthorizedUserIds(context);
assertEquals(0, ids.size());
System.out.println(ids);
}
public void testGetAuthorizedUserIds_ユーザ1_ロールB() throws Exception {
context.setParticipantName("ロールB");
context.setUserId(participantProvider.getUserId(ユーザ1));
List<IdentityInfo> ids =
participantProvider.getAuthorizedUserIds(context);
assertEquals(new IdentityInfo(2L), ids.get(0));
assertEquals(1, ids.size());
System.out.println(ids);
}
public void testGetAuthorizedUserIds_ユーザ2_ロールB() throws Exception {
context.setParticipantName("ロールB");
context.setUserId(participantProvider.getUserId(ユーザ2));
List<IdentityInfo> ids =
participantProvider.getAuthorizedUserIds(context);
assertEquals(new IdentityInfo(2L), ids.get(0));
assertEquals(1, ids.size());
System.out.println(ids);
}
public void testGetAuthorizedUserIds_ユーザ3_ロールB() throws Exception {
context.setParticipantName("ロールB");
context.setUserId(participantProvider.getUserId(ユーザ3));
List<IdentityInfo> ids =
participantProvider.getAuthorizedUserIds(context);
Set<IdentityInfo> expected = new HashSet<IdentityInfo>();
expected.add(new IdentityInfo(4L));
expected.add(new IdentityInfo(5L));
for (IdentityInfo id : ids) {
assertTrue(expected.contains(id));
}
assertEquals(2, ids.size());
System.out.println(ids);
}
public void testGetAuthorizedUserIds_ユーザ4_ロールB() throws Exception {
context.setParticipantName("ロールB");
context.setUserId(participantProvider.getUserId(ユーザ4));
List<IdentityInfo> ids =
participantProvider.getAuthorizedUserIds(context);
assertEquals(new IdentityInfo(4L), ids.get(0));
assertEquals(1, ids.size());
System.out.println(ids);
}
public void testGetAuthorizedUserIds_ユーザ5_ロールB() throws Exception {
context.setParticipantName("ロールB");
context.setUserId(participantProvider.getUserId(ユーザ5));
List<IdentityInfo> ids =
participantProvider.getAuthorizedUserIds(context);
assertEquals(new IdentityInfo(5L), ids.get(0));
assertEquals(1, ids.size());
System.out.println(ids);
}
public void testGetAuthorizedUserIds_ゲスト_ロールB() throws Exception {
context.setParticipantName("ロールB");
context.setUserId(participantProvider.getUserId(ゲスト));
List<IdentityInfo> ids =
participantProvider.getAuthorizedUserIds(context);
assertEquals(0, ids.size());
System.out.println(ids);
}
}
| true |
91bd003f7e68c1ea9548c5fcd68f151599c46bae | Java | P79N6A/icse_20_user_study | /methods/Method_21477.java | UTF-8 | 2,033 | 2.171875 | 2 | [] | no_license | private void handleAggregations(Aggregations aggregations,List<String> headers,List<List<String>> lines) throws CsvExtractorException {
if (allNumericAggregations(aggregations)) {
lines.get(this.currentLineIndex).addAll(fillHeaderAndCreateLineForNumericAggregations(aggregations,headers));
return;
}
List<Aggregation> aggregationList=aggregations.asList();
if (aggregationList.size() > 1) {
throw new CsvExtractorException("currently support only one aggregation at same level (Except for numeric metrics)");
}
Aggregation aggregation=aggregationList.get(0);
if (aggregation instanceof SingleBucketAggregation) {
Aggregations singleBucketAggs=((SingleBucketAggregation)aggregation).getAggregations();
handleAggregations(singleBucketAggs,headers,lines);
return;
}
if (aggregation instanceof NumericMetricsAggregation) {
handleNumericMetricAggregation(headers,lines.get(currentLineIndex),aggregation);
return;
}
if (aggregation instanceof GeoBounds) {
handleGeoBoundsAggregation(headers,lines,(GeoBounds)aggregation);
return;
}
if (aggregation instanceof TopHits) {
}
if (aggregation instanceof MultiBucketsAggregation) {
MultiBucketsAggregation bucketsAggregation=(MultiBucketsAggregation)aggregation;
String name=bucketsAggregation.getName();
if (!headers.contains(name)) {
headers.add(name);
}
Collection<? extends MultiBucketsAggregation.Bucket> buckets=bucketsAggregation.getBuckets();
List<String> currentLine=lines.get(this.currentLineIndex);
List<String> clonedLine=new ArrayList<>(currentLine);
boolean firstLine=true;
for ( MultiBucketsAggregation.Bucket bucket : buckets) {
String key=bucket.getKeyAsString();
if (firstLine) {
firstLine=false;
}
else {
currentLineIndex++;
currentLine=new ArrayList<String>(clonedLine);
lines.add(currentLine);
}
currentLine.add(key);
handleAggregations(bucket.getAggregations(),headers,lines);
}
}
}
| true |
ffa3c11e63c60fb669b326ef1fd5759a51ffe258 | Java | RichardSeverich/java-codewars | /src/main/java/codewars/com/micky/solid/interfacesegregation/bad/Trabajo.java | UTF-8 | 661 | 2.53125 | 3 | [] | no_license | package codewars.com.micky.solid.interfacesegregation.bad;
/**
* Interface.
*/
public interface Trabajo {
/**
* @return String.
*/
String getImprimir();
/**
* @return String.
*/
String getEngranpar();
/**
* @return String.
*/
String getCopiar();
/**
* @return String.
*/
String getEnviarFax();
/**
* @return String.
*/
String getSubirInternet();
/**
* @return String.
*/
String getImprimirLaser();
/**
* @return String.
*/
String getImprimirColores();
/**
* @return String.
*/
String getImprimirNegro();
}
| true |
8e4b9f3d34dc27e2efe8941004878ffb8d8fd785 | Java | bbblu/camping-backend | /modules/camping-database-config/src/main/java/tw/edu/ntub/imd/camping/databaseconfig/dao/criteria/restriction/ExpressionSupplier.java | UTF-8 | 397 | 1.8125 | 2 | [] | no_license | package tw.edu.ntub.imd.camping.databaseconfig.dao.criteria.restriction;
import javax.annotation.Nonnull;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.From;
public interface ExpressionSupplier<J, V> {
@Nonnull
Expression<V> getExpression(@Nonnull CriteriaBuilder builder, @Nonnull From<?, J> from);
}
| true |
01afcc97758e108eefcc02c2a660f3125d01dbc5 | Java | grazianiborcai/Agenda_WS | /src/br/com/mind5/business/employeeList/model/action/EmplisVisiMergePerarch.java | UTF-8 | 1,397 | 2.0625 | 2 | [] | no_license | package br.com.mind5.business.employeeList.model.action;
import java.util.List;
import br.com.mind5.business.employeeList.info.EmplisInfo;
import br.com.mind5.business.employeeList.info.EmplisMerger;
import br.com.mind5.business.personSearch.info.PerarchCopier;
import br.com.mind5.business.personSearch.info.PerarchInfo;
import br.com.mind5.business.personSearch.model.decisionTree.PerarchRootSelectEmp;
import br.com.mind5.model.action.ActionVisitorTemplateMerge;
import br.com.mind5.model.decisionTree.DeciTree;
import br.com.mind5.model.decisionTree.DeciTreeOption;
public final class EmplisVisiMergePerarch extends ActionVisitorTemplateMerge<EmplisInfo, PerarchInfo> {
public EmplisVisiMergePerarch(DeciTreeOption<EmplisInfo> option) {
super(option, PerarchInfo.class);
}
@Override protected Class<? extends DeciTree<PerarchInfo>> getTreeClassHook() {
return PerarchRootSelectEmp.class;
}
@Override protected List<PerarchInfo> toActionClassHook(List<EmplisInfo> baseInfos) {
return PerarchCopier.copyFromEmplis(baseInfos);
}
@Override protected List<EmplisInfo> mergeHook(List<EmplisInfo> baseInfos, List<PerarchInfo> selectedInfos) {
return EmplisMerger.mergeWithPerarch(baseInfos, selectedInfos);
}
@Override protected boolean shouldMergeWhenEmptyHook() {
return super.DONT_MERGE_WHEN_EMPTY;
}
}
| true |
01aad5903b0ac961a12ad4e09af76792f1d21974 | Java | Speight1/Mini5 | /src/Network/Security.java | UTF-8 | 2,964 | 2.40625 | 2 | [
"Apache-2.0"
] | permissive | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Network;
import Misc.Print;
import java.util.Random;
/**
*
* @author mathew
*/
public class Security {
private static int clientLimit = 150;
private static String[] AUTHENTICATED = new String[clientLimit];
private static int amountAuthenticated = 0;
public static void processHeader(RequestHeader h){
switch(h.REQUEST_TYPE){
case RequestHeader.AUTHENTICATE:
processNewSession(h);
break;
case RequestHeader.COMMAND:
if(cookieIsValid(h.COOKIE)){
Tools.parseCommand(h);
}
else{
}
break;
}
}
private static boolean cookieIsValid(String cookie){
for(int i = 0; i<amountAuthenticated; i++){
if(AUTHENTICATED[i].equals(cookie)) return true;
}
return false;
}
private static void processNewSession(RequestHeader h){
Print.print("Authenticating...");
if(authenticate(h.PARAMETERS[0],h.PARAMETERS[1])&&(amountAuthenticated<clientLimit)){
Object[] assets = new Object[1];
assets[0] = genCookie(Settings.cookieLength);
try{
Thread.sleep(100);
Network.send(h.IP, Settings.port, new ResponceHeader(ResponceHeader.SUCCESSFUL,assets));
}
catch(Exception e){
Print.print("Failed to send back");
}
}
else{
Print.print("NOT AUTHED!");
try{
Network.send(h.IP, Settings.port, new ResponceHeader(ResponceHeader.FAILED,null));
}
catch(Exception e){Print.print("Thief!");}
}
}
private static boolean authenticate(String username, String password){
if(username.equalsIgnoreCase(Settings.userName)&&password.equals(Settings.password)){
return true;
}
else{
return false;
}
}
private static String genCookie(int length){
String str = "";
String seed = "qwertyuiopasdfghjk1234567890QWERTYUIOPASDFGHJKLZXCVBNM";
for(int i =0; i<length;i++){
str += seed.charAt(new Random().nextInt(seed.length()));
}
Print.print("New Cookie "+str);
AUTHENTICATED[amountAuthenticated] = str;
amountAuthenticated++;
return str;
}
}
| true |
03d2b775fa3a4e7e6c7babb81b6d74e562671574 | Java | bazhenov/whisperer | /whisperer-activation/src/main/java/me/bazhenov/whisperer/QueueAppender.java | UTF-8 | 612 | 2.515625 | 3 | [] | no_license | package me.bazhenov.whisperer;
import ch.qos.logback.core.AppenderBase;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.LongAdder;
public class QueueAppender<T> extends AppenderBase<T> {
private final BlockingQueue<T> queue;
private final LongAdder failedCounter = new LongAdder();
public QueueAppender(int size) {
queue = new ArrayBlockingQueue<>(size);
}
@Override
protected void append(T event) {
if (!queue.offer(event))
failedCounter.increment();
}
public BlockingQueue<T> getQueue() {
return queue;
}
}
| true |
1e123af4e718a3bb4cf679510399c5fd49e0f019 | Java | zcc888/Java9Source | /jdk.rmic/sun/tools/java/SyntaxError.java | UTF-8 | 631 | 1.601563 | 2 | [] | no_license | /*
* Copyright (c) 1994, 2014, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package sun.tools.java;
/**
* Syntax errors, should always be caught inside the
* parser for error recovery.
*
* WARNING: The contents of this source file are not part of any
* supported API. Code that depends on them does so at its own risk:
* they are subject to change or removal without notice.
*/
@SuppressWarnings("serial") // JDK implementation class
public
class SyntaxError extends Exception {
}
| true |
92bc71d3c59bb3feb9ce0f4cd5fa33f9b05ecf3b | Java | OrvilleX/Bortus | /bortus-manager/src/test/java/com/orvillex/bortus/scheduler/JobGroupControllerTest.java | UTF-8 | 3,022 | 2.140625 | 2 | [] | no_license | package com.orvillex.bortus.scheduler;
import java.util.HashSet;
import com.orvillex.bortus.base.AbstractSpringMvcTest;
import com.orvillex.bortus.manager.entity.BasePage;
import com.orvillex.bortus.manager.exception.BadRequestException;
import com.orvillex.bortus.manager.modules.scheduler.domain.JobGroup;
import com.orvillex.bortus.manager.modules.scheduler.rest.JobGroupController;
import com.orvillex.bortus.manager.modules.scheduler.service.dto.JobGroupCriteria;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
public class JobGroupControllerTest extends AbstractSpringMvcTest {
@Autowired
private JobGroupController jobGroupController;
@Test
public void testPageList() throws Exception {
ResponseEntity<BasePage<JobGroup>> result = jobGroupController.pageList(new JobGroupCriteria(), PageRequest.of(0, 10));
Assert.assertNotNull(result.getBody().getContent());
}
@Test
public void testSave() throws Exception {
JobGroup jobGroup = new JobGroup();
jobGroup.setAppName("bortus-job-test");
jobGroup.setTitle("bortus-job-title");
jobGroup.setAddressType(1);
jobGroup.setAddressList("192.168.1.1,192.168.1.2");
ResponseEntity<Object> result = jobGroupController.create(jobGroup);
Assert.assertEquals(result.getStatusCode(), HttpStatus.CREATED);
}
@Test(expected = BadRequestException.class)
public void testCreateAppNameError() {
JobGroup jobGroup = new JobGroup();
jobGroup.setAppName("low");
jobGroupController.create(jobGroup);
}
@Test(expected = BadRequestException.class)
public void testCreateAddressListError() {
JobGroup jobGroup = new JobGroup();
jobGroup.setAppName("test");
jobGroup.setAddressType(1);
jobGroup.setAddressList("192, , ");
jobGroupController.create(jobGroup);
}
@Test
public void testUpdate() {
JobGroup jobGroup = new JobGroup();
jobGroup.setId(1l);
jobGroup.setAppName("bortus-job-test");
jobGroup.setTitle("bortus-job-title");
jobGroup.setAddressType(1);
jobGroup.setAddressList("192.168.1.5,165.15.12.1");
jobGroupController.update(jobGroup);
}
@Test
public void testRemove() {
jobGroupController.remove(new HashSet<Long>() {{
add(2l);
}});
}
@Test
public void testloadById() {
ResponseEntity<JobGroup> result = jobGroupController.loadById(1l);
JobGroup jobGroup = result.getBody();
Assert.assertNotNull(jobGroup);
Assert.assertEquals(jobGroup.getId(), Long.valueOf(1));
Assert.assertEquals(jobGroup.getAppName(), "job-executor-sample1");
Assert.assertEquals(jobGroup.getTitle(), "示例执行器1");
}
}
| true |
7fb476c72d67a724cce272da67c0a77ad6ca583f | Java | XiaoRenPing/Java_Univweb | /Code/univweb-rpym-dao/src/main/java/com/rpym/univweb/entity/BiAuditlogsExample.java | UTF-8 | 32,559 | 2.109375 | 2 | [] | no_license | package com.rpym.univweb.entity;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class BiAuditlogsExample {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
public BiAuditlogsExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andIdIsNull() {
addCriterion("Id is null");
return (Criteria) this;
}
public Criteria andIdIsNotNull() {
addCriterion("Id is not null");
return (Criteria) this;
}
public Criteria andIdEqualTo(Long value) {
addCriterion("Id =", value, "id");
return (Criteria) this;
}
public Criteria andIdNotEqualTo(Long value) {
addCriterion("Id <>", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThan(Long value) {
addCriterion("Id >", value, "id");
return (Criteria) this;
}
public Criteria andIdGreaterThanOrEqualTo(Long value) {
addCriterion("Id >=", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThan(Long value) {
addCriterion("Id <", value, "id");
return (Criteria) this;
}
public Criteria andIdLessThanOrEqualTo(Long value) {
addCriterion("Id <=", value, "id");
return (Criteria) this;
}
public Criteria andIdIn(List<Long> values) {
addCriterion("Id in", values, "id");
return (Criteria) this;
}
public Criteria andIdNotIn(List<Long> values) {
addCriterion("Id not in", values, "id");
return (Criteria) this;
}
public Criteria andIdBetween(Long value1, Long value2) {
addCriterion("Id between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andIdNotBetween(Long value1, Long value2) {
addCriterion("Id not between", value1, value2, "id");
return (Criteria) this;
}
public Criteria andUseridIsNull() {
addCriterion("UserId is null");
return (Criteria) this;
}
public Criteria andUseridIsNotNull() {
addCriterion("UserId is not null");
return (Criteria) this;
}
public Criteria andUseridEqualTo(Long value) {
addCriterion("UserId =", value, "userid");
return (Criteria) this;
}
public Criteria andUseridNotEqualTo(Long value) {
addCriterion("UserId <>", value, "userid");
return (Criteria) this;
}
public Criteria andUseridGreaterThan(Long value) {
addCriterion("UserId >", value, "userid");
return (Criteria) this;
}
public Criteria andUseridGreaterThanOrEqualTo(Long value) {
addCriterion("UserId >=", value, "userid");
return (Criteria) this;
}
public Criteria andUseridLessThan(Long value) {
addCriterion("UserId <", value, "userid");
return (Criteria) this;
}
public Criteria andUseridLessThanOrEqualTo(Long value) {
addCriterion("UserId <=", value, "userid");
return (Criteria) this;
}
public Criteria andUseridIn(List<Long> values) {
addCriterion("UserId in", values, "userid");
return (Criteria) this;
}
public Criteria andUseridNotIn(List<Long> values) {
addCriterion("UserId not in", values, "userid");
return (Criteria) this;
}
public Criteria andUseridBetween(Long value1, Long value2) {
addCriterion("UserId between", value1, value2, "userid");
return (Criteria) this;
}
public Criteria andUseridNotBetween(Long value1, Long value2) {
addCriterion("UserId not between", value1, value2, "userid");
return (Criteria) this;
}
public Criteria andMethodnameIsNull() {
addCriterion("MethodName is null");
return (Criteria) this;
}
public Criteria andMethodnameIsNotNull() {
addCriterion("MethodName is not null");
return (Criteria) this;
}
public Criteria andMethodnameEqualTo(String value) {
addCriterion("MethodName =", value, "methodname");
return (Criteria) this;
}
public Criteria andMethodnameNotEqualTo(String value) {
addCriterion("MethodName <>", value, "methodname");
return (Criteria) this;
}
public Criteria andMethodnameGreaterThan(String value) {
addCriterion("MethodName >", value, "methodname");
return (Criteria) this;
}
public Criteria andMethodnameGreaterThanOrEqualTo(String value) {
addCriterion("MethodName >=", value, "methodname");
return (Criteria) this;
}
public Criteria andMethodnameLessThan(String value) {
addCriterion("MethodName <", value, "methodname");
return (Criteria) this;
}
public Criteria andMethodnameLessThanOrEqualTo(String value) {
addCriterion("MethodName <=", value, "methodname");
return (Criteria) this;
}
public Criteria andMethodnameLike(String value) {
addCriterion("MethodName like", value, "methodname");
return (Criteria) this;
}
public Criteria andMethodnameNotLike(String value) {
addCriterion("MethodName not like", value, "methodname");
return (Criteria) this;
}
public Criteria andMethodnameIn(List<String> values) {
addCriterion("MethodName in", values, "methodname");
return (Criteria) this;
}
public Criteria andMethodnameNotIn(List<String> values) {
addCriterion("MethodName not in", values, "methodname");
return (Criteria) this;
}
public Criteria andMethodnameBetween(String value1, String value2) {
addCriterion("MethodName between", value1, value2, "methodname");
return (Criteria) this;
}
public Criteria andMethodnameNotBetween(String value1, String value2) {
addCriterion("MethodName not between", value1, value2, "methodname");
return (Criteria) this;
}
public Criteria andParametersIsNull() {
addCriterion("Parameters is null");
return (Criteria) this;
}
public Criteria andParametersIsNotNull() {
addCriterion("Parameters is not null");
return (Criteria) this;
}
public Criteria andParametersEqualTo(String value) {
addCriterion("Parameters =", value, "parameters");
return (Criteria) this;
}
public Criteria andParametersNotEqualTo(String value) {
addCriterion("Parameters <>", value, "parameters");
return (Criteria) this;
}
public Criteria andParametersGreaterThan(String value) {
addCriterion("Parameters >", value, "parameters");
return (Criteria) this;
}
public Criteria andParametersGreaterThanOrEqualTo(String value) {
addCriterion("Parameters >=", value, "parameters");
return (Criteria) this;
}
public Criteria andParametersLessThan(String value) {
addCriterion("Parameters <", value, "parameters");
return (Criteria) this;
}
public Criteria andParametersLessThanOrEqualTo(String value) {
addCriterion("Parameters <=", value, "parameters");
return (Criteria) this;
}
public Criteria andParametersLike(String value) {
addCriterion("Parameters like", value, "parameters");
return (Criteria) this;
}
public Criteria andParametersNotLike(String value) {
addCriterion("Parameters not like", value, "parameters");
return (Criteria) this;
}
public Criteria andParametersIn(List<String> values) {
addCriterion("Parameters in", values, "parameters");
return (Criteria) this;
}
public Criteria andParametersNotIn(List<String> values) {
addCriterion("Parameters not in", values, "parameters");
return (Criteria) this;
}
public Criteria andParametersBetween(String value1, String value2) {
addCriterion("Parameters between", value1, value2, "parameters");
return (Criteria) this;
}
public Criteria andParametersNotBetween(String value1, String value2) {
addCriterion("Parameters not between", value1, value2, "parameters");
return (Criteria) this;
}
public Criteria andExecutiontimeIsNull() {
addCriterion("ExecutionTime is null");
return (Criteria) this;
}
public Criteria andExecutiontimeIsNotNull() {
addCriterion("ExecutionTime is not null");
return (Criteria) this;
}
public Criteria andExecutiontimeEqualTo(Date value) {
addCriterion("ExecutionTime =", value, "executiontime");
return (Criteria) this;
}
public Criteria andExecutiontimeNotEqualTo(Date value) {
addCriterion("ExecutionTime <>", value, "executiontime");
return (Criteria) this;
}
public Criteria andExecutiontimeGreaterThan(Date value) {
addCriterion("ExecutionTime >", value, "executiontime");
return (Criteria) this;
}
public Criteria andExecutiontimeGreaterThanOrEqualTo(Date value) {
addCriterion("ExecutionTime >=", value, "executiontime");
return (Criteria) this;
}
public Criteria andExecutiontimeLessThan(Date value) {
addCriterion("ExecutionTime <", value, "executiontime");
return (Criteria) this;
}
public Criteria andExecutiontimeLessThanOrEqualTo(Date value) {
addCriterion("ExecutionTime <=", value, "executiontime");
return (Criteria) this;
}
public Criteria andExecutiontimeIn(List<Date> values) {
addCriterion("ExecutionTime in", values, "executiontime");
return (Criteria) this;
}
public Criteria andExecutiontimeNotIn(List<Date> values) {
addCriterion("ExecutionTime not in", values, "executiontime");
return (Criteria) this;
}
public Criteria andExecutiontimeBetween(Date value1, Date value2) {
addCriterion("ExecutionTime between", value1, value2, "executiontime");
return (Criteria) this;
}
public Criteria andExecutiontimeNotBetween(Date value1, Date value2) {
addCriterion("ExecutionTime not between", value1, value2, "executiontime");
return (Criteria) this;
}
public Criteria andExecutiondurationIsNull() {
addCriterion("ExecutionDuration is null");
return (Criteria) this;
}
public Criteria andExecutiondurationIsNotNull() {
addCriterion("ExecutionDuration is not null");
return (Criteria) this;
}
public Criteria andExecutiondurationEqualTo(Integer value) {
addCriterion("ExecutionDuration =", value, "executionduration");
return (Criteria) this;
}
public Criteria andExecutiondurationNotEqualTo(Integer value) {
addCriterion("ExecutionDuration <>", value, "executionduration");
return (Criteria) this;
}
public Criteria andExecutiondurationGreaterThan(Integer value) {
addCriterion("ExecutionDuration >", value, "executionduration");
return (Criteria) this;
}
public Criteria andExecutiondurationGreaterThanOrEqualTo(Integer value) {
addCriterion("ExecutionDuration >=", value, "executionduration");
return (Criteria) this;
}
public Criteria andExecutiondurationLessThan(Integer value) {
addCriterion("ExecutionDuration <", value, "executionduration");
return (Criteria) this;
}
public Criteria andExecutiondurationLessThanOrEqualTo(Integer value) {
addCriterion("ExecutionDuration <=", value, "executionduration");
return (Criteria) this;
}
public Criteria andExecutiondurationIn(List<Integer> values) {
addCriterion("ExecutionDuration in", values, "executionduration");
return (Criteria) this;
}
public Criteria andExecutiondurationNotIn(List<Integer> values) {
addCriterion("ExecutionDuration not in", values, "executionduration");
return (Criteria) this;
}
public Criteria andExecutiondurationBetween(Integer value1, Integer value2) {
addCriterion("ExecutionDuration between", value1, value2, "executionduration");
return (Criteria) this;
}
public Criteria andExecutiondurationNotBetween(Integer value1, Integer value2) {
addCriterion("ExecutionDuration not between", value1, value2, "executionduration");
return (Criteria) this;
}
public Criteria andClientipaddressIsNull() {
addCriterion("ClientIpAddress is null");
return (Criteria) this;
}
public Criteria andClientipaddressIsNotNull() {
addCriterion("ClientIpAddress is not null");
return (Criteria) this;
}
public Criteria andClientipaddressEqualTo(String value) {
addCriterion("ClientIpAddress =", value, "clientipaddress");
return (Criteria) this;
}
public Criteria andClientipaddressNotEqualTo(String value) {
addCriterion("ClientIpAddress <>", value, "clientipaddress");
return (Criteria) this;
}
public Criteria andClientipaddressGreaterThan(String value) {
addCriterion("ClientIpAddress >", value, "clientipaddress");
return (Criteria) this;
}
public Criteria andClientipaddressGreaterThanOrEqualTo(String value) {
addCriterion("ClientIpAddress >=", value, "clientipaddress");
return (Criteria) this;
}
public Criteria andClientipaddressLessThan(String value) {
addCriterion("ClientIpAddress <", value, "clientipaddress");
return (Criteria) this;
}
public Criteria andClientipaddressLessThanOrEqualTo(String value) {
addCriterion("ClientIpAddress <=", value, "clientipaddress");
return (Criteria) this;
}
public Criteria andClientipaddressLike(String value) {
addCriterion("ClientIpAddress like", value, "clientipaddress");
return (Criteria) this;
}
public Criteria andClientipaddressNotLike(String value) {
addCriterion("ClientIpAddress not like", value, "clientipaddress");
return (Criteria) this;
}
public Criteria andClientipaddressIn(List<String> values) {
addCriterion("ClientIpAddress in", values, "clientipaddress");
return (Criteria) this;
}
public Criteria andClientipaddressNotIn(List<String> values) {
addCriterion("ClientIpAddress not in", values, "clientipaddress");
return (Criteria) this;
}
public Criteria andClientipaddressBetween(String value1, String value2) {
addCriterion("ClientIpAddress between", value1, value2, "clientipaddress");
return (Criteria) this;
}
public Criteria andClientipaddressNotBetween(String value1, String value2) {
addCriterion("ClientIpAddress not between", value1, value2, "clientipaddress");
return (Criteria) this;
}
public Criteria andClientnameIsNull() {
addCriterion("ClientName is null");
return (Criteria) this;
}
public Criteria andClientnameIsNotNull() {
addCriterion("ClientName is not null");
return (Criteria) this;
}
public Criteria andClientnameEqualTo(String value) {
addCriterion("ClientName =", value, "clientname");
return (Criteria) this;
}
public Criteria andClientnameNotEqualTo(String value) {
addCriterion("ClientName <>", value, "clientname");
return (Criteria) this;
}
public Criteria andClientnameGreaterThan(String value) {
addCriterion("ClientName >", value, "clientname");
return (Criteria) this;
}
public Criteria andClientnameGreaterThanOrEqualTo(String value) {
addCriterion("ClientName >=", value, "clientname");
return (Criteria) this;
}
public Criteria andClientnameLessThan(String value) {
addCriterion("ClientName <", value, "clientname");
return (Criteria) this;
}
public Criteria andClientnameLessThanOrEqualTo(String value) {
addCriterion("ClientName <=", value, "clientname");
return (Criteria) this;
}
public Criteria andClientnameLike(String value) {
addCriterion("ClientName like", value, "clientname");
return (Criteria) this;
}
public Criteria andClientnameNotLike(String value) {
addCriterion("ClientName not like", value, "clientname");
return (Criteria) this;
}
public Criteria andClientnameIn(List<String> values) {
addCriterion("ClientName in", values, "clientname");
return (Criteria) this;
}
public Criteria andClientnameNotIn(List<String> values) {
addCriterion("ClientName not in", values, "clientname");
return (Criteria) this;
}
public Criteria andClientnameBetween(String value1, String value2) {
addCriterion("ClientName between", value1, value2, "clientname");
return (Criteria) this;
}
public Criteria andClientnameNotBetween(String value1, String value2) {
addCriterion("ClientName not between", value1, value2, "clientname");
return (Criteria) this;
}
public Criteria andResponseIsNull() {
addCriterion("Response is null");
return (Criteria) this;
}
public Criteria andResponseIsNotNull() {
addCriterion("Response is not null");
return (Criteria) this;
}
public Criteria andResponseEqualTo(String value) {
addCriterion("Response =", value, "response");
return (Criteria) this;
}
public Criteria andResponseNotEqualTo(String value) {
addCriterion("Response <>", value, "response");
return (Criteria) this;
}
public Criteria andResponseGreaterThan(String value) {
addCriterion("Response >", value, "response");
return (Criteria) this;
}
public Criteria andResponseGreaterThanOrEqualTo(String value) {
addCriterion("Response >=", value, "response");
return (Criteria) this;
}
public Criteria andResponseLessThan(String value) {
addCriterion("Response <", value, "response");
return (Criteria) this;
}
public Criteria andResponseLessThanOrEqualTo(String value) {
addCriterion("Response <=", value, "response");
return (Criteria) this;
}
public Criteria andResponseLike(String value) {
addCriterion("Response like", value, "response");
return (Criteria) this;
}
public Criteria andResponseNotLike(String value) {
addCriterion("Response not like", value, "response");
return (Criteria) this;
}
public Criteria andResponseIn(List<String> values) {
addCriterion("Response in", values, "response");
return (Criteria) this;
}
public Criteria andResponseNotIn(List<String> values) {
addCriterion("Response not in", values, "response");
return (Criteria) this;
}
public Criteria andResponseBetween(String value1, String value2) {
addCriterion("Response between", value1, value2, "response");
return (Criteria) this;
}
public Criteria andResponseNotBetween(String value1, String value2) {
addCriterion("Response not between", value1, value2, "response");
return (Criteria) this;
}
public Criteria andApioperationIsNull() {
addCriterion("ApiOperation is null");
return (Criteria) this;
}
public Criteria andApioperationIsNotNull() {
addCriterion("ApiOperation is not null");
return (Criteria) this;
}
public Criteria andApioperationEqualTo(String value) {
addCriterion("ApiOperation =", value, "apioperation");
return (Criteria) this;
}
public Criteria andApioperationNotEqualTo(String value) {
addCriterion("ApiOperation <>", value, "apioperation");
return (Criteria) this;
}
public Criteria andApioperationGreaterThan(String value) {
addCriterion("ApiOperation >", value, "apioperation");
return (Criteria) this;
}
public Criteria andApioperationGreaterThanOrEqualTo(String value) {
addCriterion("ApiOperation >=", value, "apioperation");
return (Criteria) this;
}
public Criteria andApioperationLessThan(String value) {
addCriterion("ApiOperation <", value, "apioperation");
return (Criteria) this;
}
public Criteria andApioperationLessThanOrEqualTo(String value) {
addCriterion("ApiOperation <=", value, "apioperation");
return (Criteria) this;
}
public Criteria andApioperationLike(String value) {
addCriterion("ApiOperation like", value, "apioperation");
return (Criteria) this;
}
public Criteria andApioperationNotLike(String value) {
addCriterion("ApiOperation not like", value, "apioperation");
return (Criteria) this;
}
public Criteria andApioperationIn(List<String> values) {
addCriterion("ApiOperation in", values, "apioperation");
return (Criteria) this;
}
public Criteria andApioperationNotIn(List<String> values) {
addCriterion("ApiOperation not in", values, "apioperation");
return (Criteria) this;
}
public Criteria andApioperationBetween(String value1, String value2) {
addCriterion("ApiOperation between", value1, value2, "apioperation");
return (Criteria) this;
}
public Criteria andApioperationNotBetween(String value1, String value2) {
addCriterion("ApiOperation not between", value1, value2, "apioperation");
return (Criteria) this;
}
public Criteria andUrlidIsNull() {
addCriterion("UrlId is null");
return (Criteria) this;
}
public Criteria andUrlidIsNotNull() {
addCriterion("UrlId is not null");
return (Criteria) this;
}
public Criteria andUrlidEqualTo(Long value) {
addCriterion("UrlId =", value, "urlid");
return (Criteria) this;
}
public Criteria andUrlidNotEqualTo(Long value) {
addCriterion("UrlId <>", value, "urlid");
return (Criteria) this;
}
public Criteria andUrlidGreaterThan(Long value) {
addCriterion("UrlId >", value, "urlid");
return (Criteria) this;
}
public Criteria andUrlidGreaterThanOrEqualTo(Long value) {
addCriterion("UrlId >=", value, "urlid");
return (Criteria) this;
}
public Criteria andUrlidLessThan(Long value) {
addCriterion("UrlId <", value, "urlid");
return (Criteria) this;
}
public Criteria andUrlidLessThanOrEqualTo(Long value) {
addCriterion("UrlId <=", value, "urlid");
return (Criteria) this;
}
public Criteria andUrlidIn(List<Long> values) {
addCriterion("UrlId in", values, "urlid");
return (Criteria) this;
}
public Criteria andUrlidNotIn(List<Long> values) {
addCriterion("UrlId not in", values, "urlid");
return (Criteria) this;
}
public Criteria andUrlidBetween(Long value1, Long value2) {
addCriterion("UrlId between", value1, value2, "urlid");
return (Criteria) this;
}
public Criteria andUrlidNotBetween(Long value1, Long value2) {
addCriterion("UrlId not between", value1, value2, "urlid");
return (Criteria) this;
}
public Criteria andUseragentidIsNull() {
addCriterion("UserAgentId is null");
return (Criteria) this;
}
public Criteria andUseragentidIsNotNull() {
addCriterion("UserAgentId is not null");
return (Criteria) this;
}
public Criteria andUseragentidEqualTo(Long value) {
addCriterion("UserAgentId =", value, "useragentid");
return (Criteria) this;
}
public Criteria andUseragentidNotEqualTo(Long value) {
addCriterion("UserAgentId <>", value, "useragentid");
return (Criteria) this;
}
public Criteria andUseragentidGreaterThan(Long value) {
addCriterion("UserAgentId >", value, "useragentid");
return (Criteria) this;
}
public Criteria andUseragentidGreaterThanOrEqualTo(Long value) {
addCriterion("UserAgentId >=", value, "useragentid");
return (Criteria) this;
}
public Criteria andUseragentidLessThan(Long value) {
addCriterion("UserAgentId <", value, "useragentid");
return (Criteria) this;
}
public Criteria andUseragentidLessThanOrEqualTo(Long value) {
addCriterion("UserAgentId <=", value, "useragentid");
return (Criteria) this;
}
public Criteria andUseragentidIn(List<Long> values) {
addCriterion("UserAgentId in", values, "useragentid");
return (Criteria) this;
}
public Criteria andUseragentidNotIn(List<Long> values) {
addCriterion("UserAgentId not in", values, "useragentid");
return (Criteria) this;
}
public Criteria andUseragentidBetween(Long value1, Long value2) {
addCriterion("UserAgentId between", value1, value2, "useragentid");
return (Criteria) this;
}
public Criteria andUseragentidNotBetween(Long value1, Long value2) {
addCriterion("UserAgentId not between", value1, value2, "useragentid");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | true |
d5c219e9e9e487a5966ce8e3a742e51b3a72a4fa | Java | jacobpa/BowlBuddy | /app/src/main/java/com/cse5236/bowlbuddy/ProfileActivity.java | UTF-8 | 884 | 2.046875 | 2 | [] | no_license | package com.cse5236.bowlbuddy;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
public class ProfileActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
FragmentManager fm = getSupportFragmentManager();
Toolbar tb = findViewById(R.id.profile_toolbar);
tb.setTitle("User Profile");
Fragment f = fm.findFragmentById(R.id.profiler_container);
if(f == null) {
f = new ProfileFragment();
fm.beginTransaction()
.add(R.id.profiler_container, f)
.commit();
}
}
}
| true |
eb6695c2666eef075161dde79f9e54574f0630a6 | Java | Talend/apache-camel | /components/camel-grok/src/test/java/org/apache/camel/component/grok/GrokOptionalOptionsTest.java | UTF-8 | 6,112 | 1.9375 | 2 | [
"Apache-2.0"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.grok;
import java.util.List;
import java.util.Map;
import io.krakens.grok.api.exception.GrokException;
import org.apache.camel.CamelExecutionException;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.spi.DataFormat;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import static org.apache.camel.test.junit5.TestSupport.assertIsInstanceOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class GrokOptionalOptionsTest extends CamelTestSupport {
@Override
protected RoutesBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
DataFormat grokFlattenedTrue = new GrokDataFormat("%{INT:i} %{INT:i}")
.setFlattened(true);
DataFormat grokFlattenedFalse = new GrokDataFormat("%{INT:i} %{INT:i}")
.setFlattened(false);
DataFormat grokNamedOnlyTrue = new GrokDataFormat("%{URI:website}")
.setNamedOnly(true);
DataFormat grokNamedOnlyFalse = new GrokDataFormat("%{URI:website}")
.setNamedOnly(false);
DataFormat grokAllowMultipleMatchesPerLineTrue = new GrokDataFormat("%{INT:i}")
.setAllowMultipleMatchesPerLine(true);
DataFormat grokAllowMultipleMatchesPerLineFalse = new GrokDataFormat("%{INT:i}")
.setAllowMultipleMatchesPerLine(false);
from("direct:flattenedTrue").unmarshal(grokFlattenedTrue);
from("direct:flattenedFalse").unmarshal(grokFlattenedFalse);
from("direct:namedOnlyTrue").unmarshal(grokNamedOnlyTrue);
from("direct:namedOnlyFalse").unmarshal(grokNamedOnlyFalse);
from("direct:allowMultipleMatchesPerLineTrue").unmarshal(grokAllowMultipleMatchesPerLineTrue);
from("direct:allowMultipleMatchesPerLineFalse").unmarshal(grokAllowMultipleMatchesPerLineFalse);
}
};
}
@Test
@SuppressWarnings("unchecked")
public void testFlattened() {
Map<String, Object> flattenedFalse = template.requestBody("direct:flattenedFalse", "123 456", Map.class);
assertNotNull(flattenedFalse);
assertTrue(flattenedFalse.containsKey("i"));
assertTrue(flattenedFalse.get("i") instanceof List);
assertEquals("123", ((List) flattenedFalse.get("i")).get(0));
assertEquals("456", ((List) flattenedFalse.get("i")).get(1));
CamelExecutionException e = assertThrows(CamelExecutionException.class,
() -> template.requestBody("direct:flattenedTrue", "1 2"));
assertIsInstanceOf(GrokException.class, e.getCause());
}
@Test
@SuppressWarnings("unchecked")
public void testNamedOnly() {
Map<String, Object> namedOnlyTrue
= template.requestBody("direct:namedOnlyTrue", "https://github.com/apache/camel", Map.class);
assertNotNull(namedOnlyTrue);
assertEquals("https://github.com/apache/camel", namedOnlyTrue.get("website"));
assertFalse(namedOnlyTrue.containsKey("URIPROTO"));
assertFalse(namedOnlyTrue.containsKey("URIHOST"));
assertFalse(namedOnlyTrue.containsKey("URIPATHPARAM"));
Map<String, Object> namedOnlyFalse
= template.requestBody("direct:namedOnlyFalse", "https://github.com/apache/camel", Map.class);
assertNotNull(namedOnlyFalse);
assertEquals("https://github.com/apache/camel", namedOnlyFalse.get("website"));
assertEquals("https", namedOnlyFalse.get("URIPROTO"));
assertEquals("github.com", namedOnlyFalse.get("URIHOST"));
assertEquals("/apache/camel", namedOnlyFalse.get("URIPATHPARAM"));
}
@Test
@SuppressWarnings("unchecked")
public void testAllowMultipleMatchesPerLine() {
List<Map<String, Object>> allowMultipleMatchesPerLineTrue = template.requestBody(
"direct:allowMultipleMatchesPerLineTrue",
"1 2 \n 3",
List.class);
assertNotNull(allowMultipleMatchesPerLineTrue);
assertEquals(3, allowMultipleMatchesPerLineTrue.size());
assertEquals("1", allowMultipleMatchesPerLineTrue.get(0).get("i"));
assertEquals("2", allowMultipleMatchesPerLineTrue.get(1).get("i"));
assertEquals("3", allowMultipleMatchesPerLineTrue.get(2).get("i"));
List<Map<String, Object>> allowMultipleMatchesPerLineFalse = template.requestBody(
"direct:allowMultipleMatchesPerLineFalse",
"1 2 \n 3",
List.class);
assertNotNull(allowMultipleMatchesPerLineFalse);
assertEquals(2, allowMultipleMatchesPerLineFalse.size());
assertEquals("1", allowMultipleMatchesPerLineFalse.get(0).get("i"));
assertEquals("3", allowMultipleMatchesPerLineFalse.get(1).get("i"));
}
}
| true |
43d2a03fb48837a7d0d6a25cde58f2b81e4abeb2 | Java | VEuPathDB/WDK | /Model/src/main/java/org/gusdb/wdk/model/record/CountReference.java | UTF-8 | 1,950 | 2.140625 | 2 | [
"Apache-2.0"
] | permissive | package org.gusdb.wdk.model.record;
import java.lang.reflect.InvocationTargetException;
import org.gusdb.wdk.model.WdkModel;
import org.gusdb.wdk.model.WdkModelBase;
import org.gusdb.wdk.model.WdkModelException;
import org.gusdb.wdk.model.query.Query;
import org.gusdb.wdk.model.user.CountPlugin;
import org.gusdb.wdk.model.user.CountQueryPlugin;
public class CountReference extends WdkModelBase {
private String _pluginClassName;
private CountPlugin _plugin;
private String _queryName;
public CountPlugin getPlugin() {
return _plugin;
}
public void setPlugin(String pluginClassName) {
this._pluginClassName = pluginClassName;
}
public String getQuery() {
return _queryName;
}
public void setQuery(String queryName) {
this._queryName = queryName;
}
@Override
public void resolveReferences(WdkModel wdkModel) throws WdkModelException {
super.resolveReferences(wdkModel);
// cannot use both plugin and query, only one is allowed
if (_pluginClassName != null && _queryName != null)
throw new WdkModelException(
"Cannot use countPlugin and countQuery at the same time. Only one is allowed.");
// if query is specified, will convert it to the default count query plugin
if (_queryName != null) {
Query query = (Query)wdkModel.resolveReference(_queryName);
_plugin = new CountQueryPlugin(query);
} else { // initialize a custom plugin.
try {
Class<? extends CountPlugin> pluginClass = Class.forName(_pluginClassName).asSubclass(CountPlugin.class);
_plugin = pluginClass.getDeclaredConstructor().newInstance();
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
IllegalArgumentException | InvocationTargetException |
NoSuchMethodException | SecurityException ex) {
throw new WdkModelException(ex);
}
}
_plugin.setModel(wdkModel);
}
}
| true |
3897a4b1bb08f63a8d325388f40f0e9a97b5d13a | Java | bquizza5/Sprint-Challenge--RDBMS-and-API-Intros-java-todos | /Project/src/main/java/com/lambdaschool/todo/service/TodoService.java | UTF-8 | 341 | 1.914063 | 2 | [
"MIT"
] | permissive | package com.lambdaschool.todo.service;
import com.lambdaschool.todo.model.Todo;
import java.util.List;
public interface TodoService {
List<Todo> findAll();
Todo findTodoById(long id);
List<Todo> findByUserName (String username);
void delete(long id);
Todo save(Todo todo);
Todo update(Todo todo, long id);
}
| true |
3d71bdb11cfdc38103af7901907fcfcab3d6988d | Java | matteo-manili/servizidog | /src/main/java/com/dogsitter/webapp/controller/DogHostFormController.java | UTF-8 | 4,275 | 2.0625 | 2 | [] | no_license | package com.dogsitter.webapp.controller;
import java.util.Date;
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.dogsitter.Constants;
import com.dogsitter.model.DogHost;
import com.dogsitter.model.User;
import com.dogsitter.service.CreaSitemapManager;
import com.dogsitter.webapp.util.CreaUrlSlugify;
/**
* @author Matteo - matteo.manili@gmail.com
*
*/
@Controller
@RequestMapping("/doghostform*") //la doghostform.jsp
public class DogHostFormController extends BaseFormController {
private CreaSitemapManager creaSitemapManager;
@Autowired
public void setCreaSitemapManager(CreaSitemapManager creaSitemapManager) {
this.creaSitemapManager = creaSitemapManager;
}
public DogHostFormController() {
setCancelView("redirect:/home-utente");
setSuccessView("redirect:/home-utente");
}
@RequestMapping(method = RequestMethod.POST)
public String onSubmit(@ModelAttribute("dogHost") final DogHost dogHostMod, final BindingResult errors, final HttpServletRequest request,
final HttpServletResponse response) {
System.out.println("DogHostFormController POST");
final Locale locale = request.getLocale();
if (validator != null) { // validator is null during testing
validator.validate(dogHostMod, errors);
if (errors.hasErrors() ) { // don't validate when deleting
System.out.println("validazione errata");
return "doghostform";
}
}
try {
User user = getUserManager().getUserByUsername(request.getRemoteUser());
DogHost dogHost = getDogHostManager().getDogHostByUser(user.getId());
//salvo gli oggetti gestiti fuori dal form, con ajax
dogHostMod.setDataInizioDisponib(dogHost.getDataInizioDisponib());
dogHostMod.setDataFineDisponib(dogHost.getDataFineDisponib());
dogHostMod.setTariffa(dogHost.getTariffa());
if (dogHost.getTariffa() == null || dogHost.getTariffa().equals("")){
dogHostMod.setTariffa(Constants.PREZZO_MEDIO_DOGHOST);
}else{
dogHostMod.setTariffa(dogHost.getTariffa());
}
dogHostMod.setMetriQuadrati(dogHost.getMetriQuadrati());
dogHostMod.setTerrazza(dogHost.isTerrazza());
dogHostMod.setGiardino(dogHost.isGiardino());
dogHostMod.setAnimaliPresenti(dogHost.isAnimaliPresenti());
dogHostMod.setUser(user);
dogHostMod.setTitolo(user.getFirstName());
//creo la url profilo in base al titolo
dogHostMod.setUrlProfilo(CreaUrlSlugify.creaUrl("doghost", dogHostMod.getAddress(), dogHostMod.getId()));
dogHostMod.setUltimaModifica(new Date());
getDogHostManager().saveDogHost(dogHostMod);
//creo la Sitemap.xml
//creaSitemapManager.creaSitemapProUrlProfili(getServletContext());
saveMessage(request, getText("user.saved", locale));
return "doghostform";
}catch (final Exception e) {
e.printStackTrace();
saveError(request, getText("errors.save", locale));
return "doghostform";
}
}
@RequestMapping(method = RequestMethod.GET)
protected ModelAndView showForm(final HttpServletRequest request, final HttpServletResponse response) {
System.out.println("DogHostFormController GET");
final Locale locale = request.getLocale();
try{
if(request.getRemoteUser() != null){
User user = getUserManager().getUserByUsername(request.getRemoteUser());
request.setAttribute("dogHost", getDogHostManager().getDogHostByUser(user.getId()));
return new ModelAndView("doghostform");
}else{
return new ModelAndView("redirect:/login");
}
}catch(Exception exc){
exc.printStackTrace();
saveError(request, getText("errors.save", locale));
return new ModelAndView("doghostform");
}
}
}
| true |