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
7446163599cacd6912171d6277d3c5f4037325f0
Java
zhengjiajin/swift
/swift-api/swift-api-protocol/src/main/java/com/swift/api/protocol/core/channel/ChannelManagerFactoryImpl.java
UTF-8
7,830
2.15625
2
[]
no_license
/** * @(#)ChannelManager.java 2020年12月21日 * * Copyright (c) 2015-2015 GuangZhou HHMK Techonlogy Co. Ltd. All rights reserved. */ package com.swift.api.protocol.core.channel; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.springframework.stereotype.Component; import com.swift.api.protocol.auth.ClientInfo; import com.swift.api.protocol.core.ChannelManagerFactory; import com.swift.api.protocol.message.handler.MessageHandlerContext; import com.swift.api.protocol.util.NettyChannel; import com.swift.util.math.RandomUtil; import com.swift.util.type.TypeUtil; /** * 管理已认证的连接及上下文本 * * @author zhengjiajin * @version 1.0 2020年12月21日 */ @Component public class ChannelManagerFactoryImpl implements ChannelManagerFactory { // private static final Logger logger = LoggerFactory.getLogger(ChannelManagerFactoryImpl.class); // 用户同一个客户端类型只能一个连接 userId,ClientInfo,context private Map<Object, Map<ClientInfo, MessageHandlerContext>> userChannels = new ConcurrentHashMap<>(); // 系统同一IP只能一个连接 sysId,Ip,context private Map<String, Map<String, MessageHandlerContext>> sysChannels = new ConcurrentHashMap<>(); private final static Map<Object, Object> LOCK_MAP = new ConcurrentHashMap<>(); // 此处线程不安全但问题不大 private Object getLock(Object obj) { if (!LOCK_MAP.containsKey(obj)) { LOCK_MAP.put(obj, new Object()); } return LOCK_MAP.get(obj); } /** * * @see com.swift.server.netty.core.ChannelManagerFactory#registerChannel(java.lang.String, * com.swift.server.netty.message.handler.MessageHandlerContext) */ @Override public void registerChannel(String sysId, MessageHandlerContext context) { if (sysId == null || context == null) return; String ip = NettyChannel.remoteAddress(context.getChannelHandlerContext().channel()); synchronized (getLock(sysId)) { // 存在旧连接需要把旧连接断连 Map<String, MessageHandlerContext> sysMap = sysChannels.get(sysId); if (sysMap == null) { sysMap = new ConcurrentHashMap<String, MessageHandlerContext>(); sysChannels.put(sysId, sysMap); } MessageHandlerContext contextOld = sysMap.get(ip); if (contextOld != null) { try { contextOld.close(); }catch(Throwable ex) { } } sysMap.put(ip, context); } } /** * @see com.swift.server.netty.core.ChannelManagerFactory#registerChannel(java.lang.Object, * com.swift.server.netty.auth.ClientInfo, com.swift.server.netty.message.handler.MessageHandlerContext) */ @Override public void registerChannel(Object userId, ClientInfo clientInfo, MessageHandlerContext context) { if (userId == null || clientInfo == null || context == null) return; synchronized (getLock(userId)) { Map<ClientInfo, MessageHandlerContext> userMap = userChannels.get(userId); if (userMap == null) { userMap = new ConcurrentHashMap<ClientInfo, MessageHandlerContext>(); userChannels.put(userId, userMap); } MessageHandlerContext contextOld = userMap.get(clientInfo); if (contextOld != null) { try { contextOld.close(); }catch(Throwable ex) { } } userMap.put(clientInfo, context); } } /** * @see com.swift.server.netty.core.ChannelManagerFactory#deregisterChannel(java.lang.String) */ @Override public void deregisterChannel(String sysId, String ip) { if (sysId == null || ip == null) return; synchronized (getLock(sysId)) { Map<String, MessageHandlerContext> sysMap = sysChannels.get(sysId); if (sysMap == null) return; sysMap.remove(ip); if (sysMap.isEmpty()) { sysChannels.remove(sysId); } } } /** * @see com.swift.server.netty.core.ChannelManagerFactory#deregisterChannel(java.lang.Object, * com.swift.server.netty.auth.ClientInfo) */ @Override public void deregisterChannel(Object userId, ClientInfo clientInfo) { if (userId == null || clientInfo == null) return; synchronized (getLock(userId)) { Map<ClientInfo, MessageHandlerContext> maps = userChannels.get(userId); if (maps == null) return; maps.remove(clientInfo); if (maps.isEmpty()) { userChannels.remove(userId); } } } /** * @see com.swift.server.netty.core.ChannelManagerFactory#getChannel(java.lang.String) */ @Override public MessageHandlerContext getChannel(String sysId) { if (TypeUtil.isNull(sysId)) return null; synchronized (getLock(sysId)) { if (!sysChannels.containsKey(sysId)) return null; Set<String> channelsKey = sysChannels.get(sysId).keySet(); if (channelsKey.size() == 0) { sysChannels.remove(sysId); return null; } int ranId = RandomUtil.createCode(0, channelsKey.size() - 1); String ip = (String) channelsKey.toArray()[ranId]; MessageHandlerContext context = sysChannels.get(sysId).get(ip); if (!NettyChannel.isActivity(context)) { sysChannels.get(sysId).remove(ip); if (sysChannels.get(sysId).isEmpty()) { sysChannels.remove(sysId); } return getChannel(sysId); } return context; } } /** * @see com.swift.server.netty.core.ChannelManagerFactory#getChannel(java.lang.Object, * com.swift.server.netty.auth.ClientInfo) */ @Override public MessageHandlerContext getChannel(Object userId, ClientInfo clientInfo) { if (TypeUtil.isNull(userId) || clientInfo == null) return null; synchronized (getLock(userId)) { if (!userChannels.containsKey(userId)) return null; Map<ClientInfo, MessageHandlerContext> map = userChannels.get(userId); if (map.isEmpty()) { userChannels.remove(userId); return null; } MessageHandlerContext channel = map.get(clientInfo); if (!NettyChannel.isActivity(channel)) { map.remove(clientInfo); if (map.isEmpty()) { userChannels.remove(userId); return null; } } return channel; } } /** * @see com.swift.server.netty.core.ChannelManagerFactory#getChannel(java.lang.Object) */ @Override public Collection<MessageHandlerContext> getChannel(Object userId) { if (TypeUtil.isNull(userId)) return null; synchronized (getLock(userId)) { if (!userChannels.containsKey(userId)) return null; Map<ClientInfo, MessageHandlerContext> value = userChannels.get(userId); for (Entry<ClientInfo, MessageHandlerContext> entry : value.entrySet()) { if (!NettyChannel.isActivity(entry.getValue())) { value.remove(entry.getKey()); } } if (value.isEmpty()) { userChannels.remove(userId); return null; } return value.values(); } } }
true
47f1fc00a06618e818bd0fb7a9de632f1da4634a
Java
Heorhius/Library
/src/test/java/by/company/library/domain/mapping/AuthorMapperTest.java
UTF-8
2,888
2.421875
2
[]
no_license
package by.company.library.domain.mapping; import by.company.library.IntegrationTestBase; import by.company.library.domain.dbo.AuthorEntity; import by.company.library.domain.dto.AuthorDto; import org.junit.jupiter.api.Test; import org.modelmapper.ModelMapper; import java.util.Date; import java.util.List; import static org.junit.jupiter.api.Assertions.*; class AuthorMapperTest extends IntegrationTestBase { public static final AuthorMapper mapper = new AuthorMapper(new ModelMapper()); private AuthorDto authorDto; private AuthorEntity authorEntity; @Test void testFromListDbo() { authorEntity = new AuthorEntity(); authorEntity.setId(4); authorEntity.setName("Donalt"); authorEntity.setSurname("Duck"); authorEntity.setPlaceOfBirth("Yorker"); authorEntity.setBirthDate(new Date()); List<AuthorDto> fromList = mapper.fromListDbo(List.of(authorEntity)); authorDto = fromList.get(0); boolean isEqual = (authorDto.getId() == authorEntity.getId() && authorDto.getName().equals(authorEntity.getName()) && authorDto.getSurname().equals(authorEntity.getSurname()) && authorDto.getPlaceOfBirth().equals(authorEntity.getPlaceOfBirth()) && authorDto.getBirthDate().equals(authorEntity.getBirthDate())); assertTrue(isEqual); } @Test void testFromDbo() { authorEntity = new AuthorEntity(); authorEntity.setId(4); authorEntity.setName("Donalt"); authorEntity.setSurname("Duck"); authorEntity.setPlaceOfBirth("Yorker"); authorEntity.setBirthDate(new Date()); authorDto = mapper.fromDbo(authorEntity); boolean isEqual = (authorDto.getId() == authorEntity.getId() && authorDto.getName().equals(authorEntity.getName()) && authorDto.getSurname().equals(authorEntity.getSurname()) && authorDto.getPlaceOfBirth().equals(authorEntity.getPlaceOfBirth()) && authorDto.getBirthDate().equals(authorEntity.getBirthDate())); assertTrue(isEqual); } @Test void testToDbo() { authorDto = new AuthorDto(); authorDto.setId(4); authorDto.setName("Donalt"); authorDto.setSurname("Duck"); authorDto.setPlaceOfBirth("Yorker"); authorDto.setBirthDate(new Date()); authorEntity = mapper.toDbo(authorDto); boolean isEqual = (authorDto.getId() == authorEntity.getId() && authorDto.getName().equals(authorEntity.getName()) && authorDto.getSurname().equals(authorEntity.getSurname()) && authorDto.getPlaceOfBirth().equals(authorEntity.getPlaceOfBirth()) && authorDto.getBirthDate().equals(authorEntity.getBirthDate())); assertTrue(isEqual); } }
true
f766ada2ab85c62800428754a05249a11e033a05
Java
almende/dht
/src/main/java/com/almende/dht/Node.java
UTF-8
1,611
2.84375
3
[ "Apache-2.0" ]
permissive
/* * Copyright: Almende B.V. (2014), Rotterdam, The Netherlands * License: The Apache Software License, Version 2.0 */ package com.almende.dht; import java.io.Serializable; import java.net.URI; /** * The Class Node. */ public class Node implements Serializable, Comparable<Node>{ private static final long serialVersionUID = 941011043741195069L; private Key key; private URI uri; /** * Instantiates a new node. */ public Node() { }; /** * Instantiates a new node. * * @param key * the key * @param uri * the uri */ public Node(final Key key, final URI uri){ this.key=key; this.uri=uri; } /** * Gets the key. * * @return the key */ public Key getKey() { return key; } /** * Sets the key. * * @param key * the new key */ public void setKey(Key key) { this.key = key; } /** * Gets the uri. * * @return the uri */ public URI getUri() { return uri; } /** * Sets the uri. * * @param uri * the new uri */ public void setUri(URI uri) { this.uri = uri; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString(){ return key+":"+uri.toASCIIString(); } @Override public int compareTo(Node o) { return key.compareTo(o.getKey()); } @Override public int hashCode(){ return key.hashCode(); } @Override public boolean equals(Object o){ if (o == null) { return false; } if (!(o instanceof Node)) return false; if (o == this) return true; final Node other = (Node) o; return key.equals(other.getKey()); } }
true
916b41d3232cd4d75425a2690b126ed2a3fc7c4d
Java
s0921122/ARBrowser
/src/org/takanolab/ar/db/StopwordsHelper.java
UTF-8
3,509
2.53125
3
[]
no_license
package org.takanolab.ar.db; import java.util.TreeSet; public class StopwordsHelper { String[] stopwords = null; static TreeSet<String> stopwordsSet = new TreeSet<String>(); // From Lucene public static final String[] ENGLISH_STOP_WORDS = { "a", "an", "and", "are", "as", "at", "be", "but", "by", "for", "if", "in", "into", "is", "it", "no", "not", "of", "on", "or", "such", "that", "the", "their", "then", "there", "these", "they", "this", "to", "was", "will", "with", "why" }; public static final String[] STOP_WORDS = { "00", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "100", "000", "$", "01", "02", "03", "04", "05", "06", "07", "08", "09", "about", "after", "all", "also", "an", "and", "another", "any", "are", "as", "at", "be", "because", "been", "before", "being", "between", "both", "but", "by", "came", "can", "come", "could", "did", "do", "does", "each", "else", "for", "from", "get", "got", "has", "had", "he", "have", "her", "here", "him", "himself", "his", "how","if", "in", "into", "is", "it", "its", "just", "like", "make", "many", "me", "might", "more", "most", "much", "must", "my", "never", "now", "of", "on", "only", "or", "other", "our", "out", "over", "re", "said", "same", "see", "should", "since", "so", "some", "still", "such", "take", "than", "that", "the", "their", "them", "then", "there", "these", "they", "this", "those", "through", "to", "too", "under", "up", "use", "very", "want", "was", "way", "we", "well", "were", "what", "when", "where", "which", "while", "who", "will", "with", "would", "you", "your", "us", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "wikipedia", "search", "scholar", "news", "maps", "oh" //"img", "src", "div", "span", "class", "br", "href", "ismap", "boarder" }; public StopwordsHelper() { for (String term: ENGLISH_STOP_WORDS) { stopwordsSet.add(term); } for (String term: STOP_WORDS) { stopwordsSet.add(term); } } public boolean isStopword(String term) { boolean b = stopwordsSet.contains(term); // For debug // if (b) { // System.out.println(term + " is stopword"); // } else { // System.out.println(term + " is not stopword"); // } return b; } public TreeSet getStopWoredsSet() { return this.stopwordsSet; } public String[] getStopWords() { return this.stopwords; } }
true
750eca1dbad28daa58a9408a208363c035b4d35c
Java
isyzes/brewery
/src/test/java/com/example/demo/mockdata/MapperMockData.java
UTF-8
4,102
2.46875
2
[]
no_license
package com.example.demo.mockdata; import com.example.demo.entity.*; import java.time.LocalDate; import java.util.List; public class MapperMockData { private final static long ID = 3; protected static BeerEntity getBeerEntity() { final BeerEntity beerEntity = new BeerEntity(); beerEntity.setId(ID); beerEntity.setName("Grimbergen"); beerEntity.setColor("bright"); beerEntity.setFortress(12.5); beerEntity.setDateManufacture(LocalDate.of(2020, 12, 12)); beerEntity.setShelfLife(25); beerEntity.setLitersInStock(6225); beerEntity.setRecipe(getRecipeEntity()); beerEntity.setCostPrice(657); beerEntity.setLitersInStock(2551); return beerEntity; } protected static UserEntity getUserEntity() { final UserEntity userEntity = new UserEntity(); userEntity.setId(ID); userEntity.setDateStart(LocalDate.of(2018, 1,15)); userEntity.setDateEnd(LocalDate.of(2019,10,14)); userEntity.setEmail("vasya@email.com"); userEntity.setBirthDate(LocalDate.of(1995, 1, 19)); userEntity.setFio("Пупкин Василий Иванович"); return userEntity; } protected static IngredientEntity getIngredientEntity() { final IngredientEntity ingredientEntity = new IngredientEntity(); ingredientEntity.setId(ID); ingredientEntity.setName("Water"); ingredientEntity.setMilligramsInStock(647851); return ingredientEntity; } protected static List<BeerEntity> getBeerEntityList() { final BeerEntity first = new BeerEntity(); first.setId(1); first.setName("Garage"); first.setColor("bright"); first.setFortress(12.5); first.setDateManufacture(LocalDate.of(2020, 12, 12)); first.setShelfLife(25); first.setCostPrice(574); first.setRecipe(getRecipeEntity()); final BeerEntity second = new BeerEntity(); second.setId(2); second.setName("Miller"); second.setColor("bright"); second.setFortress(12.5); second.setDateManufacture(LocalDate.of(2020, 12, 12)); second.setShelfLife(25); second.setCostPrice(755); second.setRecipe(getRecipeEntity()); final BeerEntity third = new BeerEntity(); third.setId(3); third.setName("Heineken"); third.setColor("dark"); third.setFortress(9.5); third.setDateManufacture(LocalDate.of(2020, 12, 12)); third.setShelfLife(35); third.setCostPrice(5756); third.setRecipe(getRecipeEntity()); return List.of(first, second, third); } protected static List<RecipeItemEntity> getRecipeItemEntityList() { return List.of(getRecipeItemEntity()); } protected static OrderItemEntity getOrderItemEntity() { OrderItemEntity orderItemEntity = new OrderItemEntity(); orderItemEntity.setLiters(6445); orderItemEntity.setBeer(getBeerEntity()); return orderItemEntity; } protected static OrderEntity getOrderEntity() { return getOrderEntity(getOrderItemEntity(), getOrderItemEntity()); } protected static RecipeEntity getRecipeEntity() { RecipeEntity recipeEntity = new RecipeEntity(); recipeEntity.setId(ID); recipeEntity.setItems(List.of(getRecipeItemEntity())); return recipeEntity; } private static RecipeItemEntity getRecipeItemEntity() { final RecipeItemEntity partRecipeEntity = new RecipeItemEntity(); partRecipeEntity.setId(ID); partRecipeEntity.setMilligram(5); partRecipeEntity.setIngredient(getIngredientEntity()); return partRecipeEntity; } private static OrderEntity getOrderEntity(final OrderItemEntity firstSaveItem, final OrderItemEntity secondSaveItem) { final OrderEntity orderEntity = new OrderEntity(); orderEntity.setPrice(26.28); orderEntity.setItems(List.of(firstSaveItem, secondSaveItem)); orderEntity.setConsumer(getUserEntity()); return orderEntity; } }
true
f0ef9d781d3ddd97cf9f1c3db91dc26e281aa29c
Java
paulmai193/team-caring
/src/main/java/com/ttth/teamcaring/web/rest/SocialController.java
UTF-8
2,704
2.078125
2
[]
no_license
/* * */ package com.ttth.teamcaring.web.rest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.social.connect.Connection; import org.springframework.social.connect.web.ProviderSignInUtils; import org.springframework.social.support.URIBuilder; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.view.RedirectView; import com.ttth.teamcaring.config.Constants; import com.ttth.teamcaring.service.SocialService; /** * The Class SocialController. * * @author Dai Mai */ @RestController @RequestMapping("/social") public class SocialController { /** The log. */ private final Logger log = LoggerFactory.getLogger(SocialController.class); /** The social service. */ private final SocialService socialService; /** The provider sign in utils. */ private final ProviderSignInUtils providerSignInUtils; /** * Instantiates a new social controller. * * @param socialService * the social service * @param providerSignInUtils * the provider sign in utils */ public SocialController(SocialService socialService, ProviderSignInUtils providerSignInUtils) { this.socialService = socialService; this.providerSignInUtils = providerSignInUtils; } /** * Sign up. * * @param webRequest * the web request * @param langKey * the lang key * @return the redirect view */ @GetMapping("/signup") public RedirectView signUp(WebRequest webRequest, @CookieValue(name = "NG_TRANSLATE_LANG_KEY", required = false, defaultValue = Constants.DEFAULT_LANGUAGE) String langKey) { try { Connection<?> connection = providerSignInUtils.getConnectionFromSession(webRequest); socialService.createSocialUser(connection, langKey.replace("\"", "")); return new RedirectView( URIBuilder.fromUri("/#/social-register/" + connection.getKey().getProviderId()) .queryParam("success", "true").build().toString(), true); } catch (Exception e) { log.error("Exception creating social user: ", e); return new RedirectView(URIBuilder.fromUri("/#/social-register/no-provider") .queryParam("success", "false").build().toString(), true); } } }
true
7f76899e337c1d0c2aa388eb8f6f481458b91115
Java
tspannhw/pulsar-million-requests
/shine/src/main/java/io/project/app/shine/SwaggerConfig.java
UTF-8
1,170
2.125
2
[]
no_license
package io.project.app.shine; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.info.License; import org.springdoc.core.GroupedOpenApi; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * * @author armdev */ @Configuration class SwaggerConfig { @Bean public GroupedOpenApi publicApi() { return GroupedOpenApi.builder() .group("shine") .pathsToMatch("/api/**") .build(); } @Bean public OpenAPI customOpenAPI(@Value("${springdoc.version}") String appVersion) { return new OpenAPI() .info(new Info().title("Super Hero API") .version(appVersion) .description("This is a sample CRUD application using spring data and cassandra.") .termsOfService("http://swagger.io/terms/") .license(new License().name("Apache 2.0").url("http://springdoc.org"))); } }
true
3894c662983fc235faf67bc0377d27429631f09d
Java
shibani/battleship
/src/test/java/battleship/GameTest.java
UTF-8
4,800
2.90625
3
[]
no_license
package battleship; import org.junit.Test; import static junit.framework.TestCase.assertEquals; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.beans.HasProperty.hasProperty; import static org.junit.Assert.assertThat; public class GameTest { @Test public void getPlayer1() { Game game = new Game(); game.createPlayers(1,1); assertThat(game.player1, instanceOf(Human.class)); } @Test public void getPlayer2() { Game game = new Game(); game.createPlayers(1,1); assertThat(game.player2, instanceOf(Computer.class)); } @Test public void playerTypeCheck1() { Game game = new Game(); game.createPlayers(1,1); assertThat(game.player1, hasProperty("type")); } @Test public void playerTypeCheck2() { Game game = new Game(); game.createPlayers(1,2); assertEquals("Opponent", game.player1.getType()); } @Test public void setCurrentPlayer() { Game game = new Game(); game.createPlayers(1,2); assertEquals("Opponent", game.getCurrentPlayer().getType()); } @Test public void getCurrentPlayer() { Game game = new Game(); game.createPlayers(1,2); game.setCurrentPlayer(); assertEquals("User", game.getCurrentPlayer().getType()); } @Test public void moveReturnsAHit1() { Game game = new Game(); game.createPlayers(1,1); game.setCurrentPlayer(); String result = game.makeMove(45); assertEquals("X", game.getCurrentPlayer().getBoard().getPositions().get(45)); } @Test public void moveReturnsAHit2() { Game game = new Game(); game.createPlayers(1,1); game.setCurrentPlayer(); String result = game.makeMove(35); assertEquals("hit", result); } @Test public void moveReturnsAMiss1() { Game game = new Game(); game.createPlayers(1,1); game.setCurrentPlayer(); String result = game.makeMove(24); assertEquals("n", game.getCurrentPlayer().getBoard().getPositions().get(24)); } @Test public void moveReturnsAMiss2() { Game game = new Game(); game.createPlayers(1,1); game.setCurrentPlayer(); String result = game.makeMove(24); assertEquals("miss", result); } @Test public void shipIsHit() { Game game = new Game(); game.createPlayers(1,1); game.setCurrentPlayer(); game.getCurrentPlayer().getBoard().getPositions().set(1, "X"); game.getCurrentPlayer().getBoard().getPositions().set(2, "X"); assertEquals("hit", game.shipIsHit(85)); } @Test public void shipIsSunk() { Game game = new Game(); game.createPlayers(1,1); game.setCurrentPlayer(); game.getCurrentPlayer().getBoard().getPositions().set(83, "X"); game.getCurrentPlayer().getBoard().getPositions().set(84, "X"); assertEquals("sunk", game.shipIsHit(85)); } @Test public void noShipsHit() { Game game = new Game(); game.createPlayers(1,1); game.setCurrentPlayer(); game.getCurrentPlayer().getBoard().getPositions().set(1, "X"); game.getCurrentPlayer().getBoard().getPositions().set(2, "X"); assertEquals("miss", game.shipIsHit(23)); } @Test public void isWon() { Game game = new Game(); game.createPlayers(1,1); game.setCurrentPlayer(); game.getCurrentPlayer().getBoard().getPositions().set(1, "X"); game.getCurrentPlayer().getBoard().getPositions().set(17, "X"); game.getCurrentPlayer().getBoard().getPositions().set(18, "X"); game.getCurrentPlayer().getBoard().getPositions().set(19, "X"); game.getCurrentPlayer().getBoard().getPositions().set(83, "X"); game.getCurrentPlayer().getBoard().getPositions().set(84, "X"); game.getCurrentPlayer().getBoard().getPositions().set(85, "X"); game.getCurrentPlayer().getBoard().getPositions().set(35, "X"); game.getCurrentPlayer().getBoard().getPositions().set(45, "X"); game.getCurrentPlayer().getBoard().getPositions().set(55, "X"); game.getCurrentPlayer().getBoard().getPositions().set(65, "X"); game.getCurrentPlayer().getBoard().getPositions().set(38, "X"); game.getCurrentPlayer().getBoard().getPositions().set(48, "X"); game.getCurrentPlayer().getBoard().getPositions().set(58, "X"); game.getCurrentPlayer().getBoard().getPositions().set(68, "X"); game.getCurrentPlayer().getBoard().getPositions().set(78, "X"); game.shipIsHit(2); assertEquals(true, game.isWon()); } }
true
fbcd003a4721c61d98be2cfe6ba3b0bff98738bd
Java
isaiahscheel/GoMoKu
/GoMoKu Client/src/MainWindow/MasterController.java
UTF-8
3,248
2.828125
3
[ "MIT" ]
permissive
package MainWindow; import static MainWindow.Constants.serverIp; /** * A controller to control all the controllers for Gomoku game play */ public class MasterController { public Constants constants = new Constants(); public User user = new User(); public GameModel gm; public LobbyWindowController lwc; public String opponent; public Client client = new Client(serverIp, 4444, this); // the clients connecting information public GameBoard gb; /** * Method to open the lobby window of Gomoku */ public void openLobby() { lwc = new LobbyWindowController(client, this); lwc.lw.setTitle(lwc.user.userName); } /** * Method to open the register window of Gomoku */ void openRegister() { RegisterWindowController rwc = new RegisterWindowController(client); // passed in client for read/write to a file of users } /** * Method to open the register window if the user has types in to the login * user name of Gomoku */ void openRegister(String userName) { RegisterWindowController rwc = new RegisterWindowController(userName, client); } /** * Method to open the main window of Gomoku */ void openMainWindow() { MainWindowController mwc = new MainWindowController(client, this); } /** * Opens the game board with you and the inviters name */ void openGameBoard(String accepter, String ip, int port, PlayerController thisP) { this.opponent = accepter; HostServer server = new HostServer(port); GameClient gc = new GameClient(ip, port, server); GameBoardController gbc = new GameBoardController(gc, this, server); gbc.pc = thisP; this.gm = gbc.gm; gm.addPlayer(thisP); gbc.gb.frame.setTitle("You vs " + accepter); gbc.disableAll(); gc.listen(); } /** * If an invite is send then you make the server */ void openBoard(int port, String opponent, PlayerController thisP) { this.opponent = opponent; HostServer server = new HostServer(port); GameBoardController gbc = new GameBoardController(server, this); gbc.pc = thisP; this.gm = gbc.gm; gm.addPlayer(thisP); gbc.gb.frame.setTitle("You vs " + opponent); gbc.enableAll(); server.listen(); } /** * Method used to put the player back into the lobby. If gameWin == 1, then the * winner tells the server who won and who lost. Else, the player just goes back * into the lobby. */ void returnLobby(int gameWin) { lwc.lw.OnlinelistModel.clear(); lwc.lw.inviteList.clear(); if (gameWin == 1) { lwc.send("Return " + "\n" + user.userName + "\n" + gameWin + "\n" + opponent); } else { lwc.send("Back " + user.userName); } lwc.lw.setVisible(true); } /** * A method to try and only make the client if needed. Always for offline gameplay. */ void connect() { client = new Client(serverIp, 4444, this); // the clients connecting information } /** * Method to start an AI game. The String it takes determines the difficulty. * Follow the format of string in the mainwindow dropDown String. */ void AIGame(String AItype) { GameBoardController gbc = new GameBoardController(this, AItype); gbc.gb.turnLabel.setText("Your turn"); } }
true
d51828037f125eaaf0fc2e5d81aadf10da351077
Java
mortalDu/IpcServer
/MsgCommunicate/src/main/java/com/mududu/communicate/ipc/exception/TooLargeException.java
UTF-8
215
1.859375
2
[]
no_license
package com.mududu.communicate.ipc.exception; /** * Created by tiger on 2016/12/12. */ public class TooLargeException extends RuntimeException { public TooLargeException(String s){ super(s); } }
true
76211a22ee469c49af9f8348b18b74b9b9ba5d90
Java
isLiuHao/QASystem
/MedicalKG/src/main/java/com/lh/service/imp/CureNodeServiceImpl.java
UTF-8
672
2.1875
2
[]
no_license
package com.lh.service.imp; import com.lh.entity.medical.node.CureNode; import com.lh.entity.medical.node.SymptomNode; import com.lh.repository.medical.node.CureNodeRepository; import com.lh.repository.medical.node.SymptomNodeRepository; import com.lh.service.CureNodeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CureNodeServiceImpl implements CureNodeService { @Autowired private CureNodeRepository cureNodeR; //通过名字查找SymptomNode @Override public CureNode findCureNodeByName(String name) { return cureNodeR.findByName(name); } }
true
56e01b6f327661f18657a0169f4510fddd1ba30d
Java
John256145/date-program
/src/date/MyDateLoop.java
UTF-8
266
2.625
3
[]
no_license
package date; public class MyDateLoop { public static void main(String[] args) { // TODO Auto-generated method stub MyDate d1 = new MyDate(2011, 12, 28); for (int i = 0; i < 66; i++) { System.out.println(d1.nextDay()); } } }
true
3cc6c4ed75e7be6cb1b041491d14827fec856088
Java
dharmtomar/demotest
/demotest/src/test/java/smoke_TestPages/Sales_Test.java
UTF-8
280
1.867188
2
[]
no_license
package smoke_TestPages; import java.io.IOException; import org.testng.annotations.Test; import smoke_ObjectPages.Sales; public class Sales_Test extends BaseClass{ Sales sl; @Test public void salestest() throws IOException{ sl=new Sales(odriver); sl.clicksales(); } }
true
3284b43367a899257df27fc293496e8689e9592b
Java
sritala/ot-harjoitustyo
/Viiniarkisto/src/main/java/wine/dao/FileWineDao.java
UTF-8
3,440
3.3125
3
[]
no_license
package wine.dao; import wine.domain.Wine; import java.io.File; import java.io.FileWriter; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * WineDao's class, which handles creating and saving of the wines */ public class FileWineDao implements WineDao { public List<Wine> wines; private String file; public FileWineDao(String file) throws Exception { this.wines = new ArrayList<>(); this.file = file; try { Scanner reader = new Scanner(new File(file)); while (reader.hasNextLine()) { String[] parts = reader.nextLine().split(";"); int id = Integer.parseInt(parts[0]); int year = Integer.parseInt(parts[1]); String country = parts[2]; String name = parts[3]; String adder = parts[4]; String grape = parts[5]; String food = parts[6]; Wine wine = new Wine(year, country, name, adder, grape, food); wine.setId(generateId()); this.wines.add(wine); } } catch (Exception e) { FileWriter writer = new FileWriter(new File(file)); writer.close(); } } private int generateId() { return this.wines.size() + 1; } /** * creates a wine to the list * * @param wine new created wine * @return returns wine for the further handling * @throws java.lang.Exception */ @Override public Wine create(Wine wine) throws Exception { wine.setId(generateId()); this.wines.add(wine); save(); return wine; } /** * saves wine for the file * */ private void save() throws Exception { try (FileWriter writer = new FileWriter(new File(file))) { for (Wine wine : this.wines) { writer.write(wine.getId() + ";" + wine.getYear() + ";" + wine.getCountry() + ";" + wine.getName() + ";" + wine.getAdder() + ";" + wine.getGrape() + ";" + wine.getFood() + "\n"); } } } /** * fetches existing wines * */ @Override public List<Wine> getAll() { return this.wines; } /** * deletes wine from file * * @param name wine to be deleted */ @Override public void delete(String name) throws Exception { for (int i = 0; i < this.wines.size(); i++) { Wine wine = this.wines.get(i); if (wine.getName().equalsIgnoreCase(name)) { this.wines.remove(i); } save(); } } /** * Updates wine and saves the result to file * * @param id id of the wine * @param year new year of the wine * @param country new country of the wine * @param name new name of the wine * @param grape new grape of the wine * @param food new food of the wine */ @Override public void updateWine(int id, int year, String country, String name, String grape, String food) throws Exception { Wine wine = this.wines.get(id); wine.setYear(year); wine.setCountry(country); wine.setName(name); wine.setGrape(grape); wine.setFood(food); this.wines.set(id, wine); save(); } }
true
7aee42d14b5e9fa09c225df801fd9c5607ec651e
Java
iantal/AndroidPermissions
/apks/test_apks/insecurebank/source/com/google/android/gms/games/internal/game/Acls.java
UTF-8
639
1.617188
2
[ "Apache-2.0" ]
permissive
package com.google.android.gms.games.internal.game; import com.google.android.gms.common.api.Releasable; import com.google.android.gms.common.api.Result; public abstract interface Acls { public static abstract interface LoadAclResult extends Releasable, Result {} public static abstract interface LoadFAclResult extends Releasable, Result {} public static abstract interface OnGameplayAclLoadedCallback {} public static abstract interface OnGameplayAclUpdatedCallback {} public static abstract interface OnNotifyAclLoadedCallback {} public static abstract interface OnNotifyAclUpdatedCallback {} }
true
679f80835b8269b04880d5e653bbc40eb9672e6b
Java
liurenzhong000/mtc2-parent
/biz/facade-user/src/main/java/io/mtc/facade/user/entity/dividend/DividendData.java
UTF-8
1,757
2.59375
3
[]
no_license
package io.mtc.facade.user.entity.dividend; import com.google.common.collect.Lists; import lombok.Getter; import lombok.Setter; import java.math.BigDecimal; import java.util.List; import java.util.stream.Collectors; /** * @Auther: hyp * @Date: 2019/3/12 09:18 * @Description: 分红用户统计 */ @Setter @Getter public class DividendData { /**第几级*/ private Integer level; /**快照持有平均量(用于计算分红)*/ private BigDecimal balance; /**当前级别用户的平均持有量(用于记录)*/ private BigDecimal levelBalance; /**当前级别的下级所获得的收益*/ private BigDecimal price; /**用户id*/ private Long userId; public DividendData(Integer level, BigDecimal balance, BigDecimal levelBalance, BigDecimal price, Long userId){ this.level = level; this.balance = balance; this.levelBalance = levelBalance; this.price = price; this.userId = userId; } public static List<DividendData> listByLevel(List<DividendData> list, Integer level){ if (list == null || list.size() <= 0) { return Lists.newArrayList(); } return list.stream().filter(item -> item.getLevel() == level).collect(Collectors.toList()); } public static String joinUserIdsFromList(List<DividendData> list){ return list.stream().map(item -> item.getUserId().toString()).reduce("", (a,b) -> { if (a.equals("")){ return "" + b; } return a +"," +b; }); } public static BigDecimal countPriceFromList(List<DividendData> list){ return list.stream().map(item -> item.getPrice()).reduce(BigDecimal.ZERO, BigDecimal::add); } }
true
0daf68d4d7df2299934ea6e6195ff1062b98da4b
Java
yukiao/movie-app-v2
/app/src/main/java/com/yukiao/movie_app/TrendingFragment.java
UTF-8
3,047
2.15625
2
[]
no_license
package com.yukiao.movie_app; import android.content.Intent; import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.yukiao.movie_app.adapters.AiringTodayAdapter; import com.yukiao.movie_app.adapters.OnItemClick; import com.yukiao.movie_app.models.AiringToday; import com.yukiao.movie_app.models.AiringTodayResponse; import com.yukiao.movie_app.network.Const; import com.yukiao.movie_app.network.TVShowApiClient; import com.yukiao.movie_app.network.TVShowApiInterface; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class TrendingFragment extends Fragment implements OnItemClick { private RecyclerView recyclerView; private AiringTodayAdapter adapter; private List<AiringToday> airingTodays; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_trending, container, false); recyclerView = view.findViewById(R.id.rv_tv_show); recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2)); loadData(); return view; } private void loadData() { TVShowApiInterface tvShowApiInterface = TVShowApiClient.getRetrofit() .create(TVShowApiInterface.class); Call<AiringTodayResponse> airingTodayResponseCall = tvShowApiInterface.getAiringTodays(Const.API_KEY); airingTodayResponseCall.enqueue(new Callback<AiringTodayResponse>() { @Override public void onResponse(Call<AiringTodayResponse> call, Response<AiringTodayResponse> response) { if(response.isSuccessful() && response.body() != null){ airingTodays = response.body().getAiringTodays(); adapter = new AiringTodayAdapter(airingTodays, TrendingFragment.this); recyclerView.setAdapter(adapter); }else{ Toast.makeText(getActivity(), "Failed", Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<AiringTodayResponse> call, Throwable t) { Log.d("TVShowFragment", "onFailure: " + t.getLocalizedMessage()); Toast.makeText(getActivity(), "Failed " + t.getLocalizedMessage(), Toast.LENGTH_LONG).show(); } }); } @Override public void onClick(int pos) { Intent detailActivity = new Intent(getActivity(), DetailActivity.class); detailActivity.putExtra("ID", airingTodays.get(pos).getId()); detailActivity.putExtra("TYPE", "TV Show"); startActivity(detailActivity); } }
true
7635f1b3f27f32287c307a77c530cf33908ddc22
Java
kamieniarzk/image-processor
/app/src/main/java/com/imageprocessor/util/VideoAdapter.java
UTF-8
1,980
2.34375
2
[]
no_license
package com.imageprocessor.util; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.imageprocessor.R; import com.imageprocessor.VideoActivity; import com.imageprocessor.model.Video; import java.util.ArrayList; public class VideoAdapter extends RecyclerView.Adapter<VideoAdapter.VideoViewHolder> { ArrayList<Video> videosList; Context context; public VideoAdapter(Context context, ArrayList<Video> videosList){ this.context = context; this.videosList = videosList; } @NonNull @Override public VideoViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.gallery_row, parent, false); return new VideoViewHolder(itemView); } @Override public void onBindViewHolder(@NonNull VideoViewHolder holder, int position) { final Video item = videosList.get(position); try { Glide.with(context).load(item.getData()).into(holder.imgViewThumbnail); } catch (Exception e) { } holder.itemView.setOnClickListener(view -> { Intent intent = new Intent(view.getContext(), VideoActivity.class); intent.putExtra("videoUri", item.getData()); view.getContext().startActivity(intent); }); } @Override public int getItemCount() { return videosList.size(); } static class VideoViewHolder extends RecyclerView.ViewHolder { ImageView imgViewThumbnail; public VideoViewHolder(@NonNull View itemView) { super(itemView); imgViewThumbnail = itemView.findViewById(R.id.thumbnailImageView); } } }
true
ede58d3452f0ddbd96b588d121ae28023e87c065
Java
YYB-Puls/ybblog
/JavaStudy/src/Day09/IterateChars.java
UTF-8
743
4.09375
4
[]
no_license
package Day09; public class IterateChars { public static void main(String[] args) { //需要统计的字符串 String str = "adcsfsesrdfcafgsdfsafse"; //需要统计的字符 char target = 's'; //得到字符串的长度 int len = str.length(); //用来保存结果的int变量 int count = 0; //遍历字符串中的每一个字符 for (int i = 0; i < len; i++){ //得到字符串中的第i个字符 char ch = str.charAt(i); //如果这个字符是需要统计的则加1 if (ch == target){ count++; } } System.out.println("包含s的字符有"+count+"个"); } }
true
c457513dc7e025986b1eae7f4d78a9aed058885d
Java
zscgrhg/moonshine
/services/jta/src/main/java/org/atteo/moonshine/jta/JtaConnectionFactoryWrapper.java
UTF-8
1,490
2.0625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2011 Atteo. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.atteo.moonshine.jta; import javax.annotation.Nullable; import javax.jms.ConnectionFactory; import javax.jms.XAConnectionFactory; /** * Wraps {@link XAConnectionFactory} into {@link ConnectionFactory} adding transaction support. */ public interface JtaConnectionFactoryWrapper { /** * Wrap given {@link XAConnectionFactory} into {@link ConnectionFactory} adding transaction support. * @param name unique name for the returned {@link ConnectionFactory} * @param xaFactory {@link ConnectionFactory} to wrap * @param poolOptions options for the connection pool * @return wrapped {@link ConnectionFactory} */ ConnectionFactory wrap(String name, XAConnectionFactory xaFactory, @Nullable PoolOptions poolOptions); /** * Close previously wrapped connection factory. * @param connectionFactory connection factory to close */ void close(ConnectionFactory connectionFactory); }
true
2de4e1907b7d398aaa3147ebc699b436ecec3cfc
Java
MiguelKuckoski/curso_java_8
/src/udemy/java8/unidade2/lambdas/Validador.java
UTF-8
126
2
2
[]
no_license
package udemy.java8.unidade2.lambdas; @FunctionalInterface public interface Validador<T> { boolean validada(T t); }
true
ad8b2792c7c61d3f5bbc8dc8deb1c1971245c339
Java
DigitalHouseBrasil/MobileAndroid-0219MOACN01O
/Android/AndroidRoomDatabaseApp/app/src/main/java/br/com/digitalhouse/roomdatabaseapp/interfaces/RecyclerViewOnItemClickListener.java
UTF-8
208
1.921875
2
[]
no_license
package br.com.digitalhouse.roomdatabaseapp.interfaces; import br.com.digitalhouse.roomdatabaseapp.model.Contato; public interface RecyclerViewOnItemClickListener { void onItemClick(Contato contato); }
true
0eb9c20250635f476740a8f4e5cb65bb6ce099d4
Java
bestDvlpr/logistics-new
/src/main/java/uz/hasan/service/dto/AddressDTO.java
UTF-8
4,066
2.3125
2
[]
no_license
package uz.hasan.service.dto; import javax.validation.constraints.*; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import java.util.Objects; /** * A DTO for the Address entity. */ public class AddressDTO implements Serializable { private Long id; @NotNull private String streetAddress; private String latitude; private String longitude; private Long countryId; private String countryName; private Long regionId; private String regionName; private Long cityId; private String cityName; private Long districtId; private String districtName; private Long clientId; private String clientFirstName; private Long companyId; private String companyName; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getStreetAddress() { return streetAddress; } public void setStreetAddress(String streetAddress) { this.streetAddress = streetAddress; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public Long getCountryId() { return countryId; } public void setCountryId(Long locationId) { this.countryId = locationId; } public String getCountryName() { return countryName; } public void setCountryName(String locationName) { this.countryName = locationName; } public Long getRegionId() { return regionId; } public void setRegionId(Long locationId) { this.regionId = locationId; } public String getRegionName() { return regionName; } public void setRegionName(String locationName) { this.regionName = locationName; } public Long getCityId() { return cityId; } public void setCityId(Long locationId) { this.cityId = locationId; } public String getCityName() { return cityName; } public void setCityName(String locationName) { this.cityName = locationName; } public Long getDistrictId() { return districtId; } public void setDistrictId(Long locationId) { this.districtId = locationId; } public String getDistrictName() { return districtName; } public void setDistrictName(String locationName) { this.districtName = locationName; } public Long getClientId() { return clientId; } public void setClientId(Long clientId) { this.clientId = clientId; } public String getClientFirstName() { return clientFirstName; } public void setClientFirstName(String clientFirstName) { this.clientFirstName = clientFirstName; } public Long getCompanyId() { return companyId; } public void setCompanyId(Long companyId) { this.companyId = companyId; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AddressDTO addressDTO = (AddressDTO) o; if ( ! Objects.equals(id, addressDTO.id)) { return false; } return true; } @Override public int hashCode() { return Objects.hashCode(id); } @Override public String toString() { return "AddressDTO{" + "id=" + id + ", streetAddress='" + streetAddress + "'" + ", latitude='" + latitude + "'" + ", longitude='" + longitude + "'" + '}'; } }
true
afb5e69bd46a0e4230814419589bac02a1952c5a
Java
patou/Common-GWT
/src/main/java/com/sfeir/common/gwt/theme/twitter/Form.java
UTF-8
1,571
1.539063
2
[]
no_license
package com.sfeir.common.gwt.theme.twitter; import com.google.gwt.resources.client.CssResource; public interface Form extends CssResource, Style { // // @ClassName("input-medium") // String inputMedium(); // // @ClassName("input-append") // String inputAppend(); // // String span12(); // // String span11(); // // String span10(); // // @ClassName("form-horizontal") // String formHorizontal(); // // @ClassName("form-search") // String formSearch(); // // @ClassName("input-small") // String inputSmall(); // // String span8(); // // String controls(); // // @ClassName("input-mini") // String inputMini(); // // String span9(); // // String span6(); // // String span7(); // // String span4(); // // @ClassName("input-prepend") // String inputPrepend(); // // String span5(); // // String span2(); // // String span3(); // // @ClassName("help-block") // String helpBlock(); // // String span1(); // // @ClassName("form-inline") // String formInline(); // // String error(); // // @ClassName("help-inline") // String helpInline(); // // @ClassName("input-large") // String inputLarge(); // // @ClassName("form-actions") // String formActions(); // // @ClassName("uneditable-input") // String uneditableInput(); // // @ClassName("input-xxlarge") // String inputXxlarge(); // // @ClassName("search-query") // String searchQuery(); // // @ClassName("add-on") // String addOn(); // // String active(); // // @ClassName("input-xlarge") // String inputXlarge(); // // String success(); // // @ClassName("control-group") // String controlGroup(); // // String warning(); }
true
306b2d3523e7316b2888a0349e75c27faf03cf80
Java
frantisekrusek/schwimmbad
/model/schwimmbad/Schwimmbad.java
UTF-8
13,236
2.53125
3
[]
no_license
package model.schwimmbad; import model.pumpe.Pumpe; import model.schwimmer.Schwimmer; import model.useController.UseController; import viewing.Rahmen_4_nachzahlen; import java.text.DecimalFormat; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.stream.Collectors; public class Schwimmbad { //Warum statische Eigenschaften? - Es gibt nur eine Instanz. private static int gesamtBesucherCounter; private static int anwesendeBesucherCounter; private ArrayList<Schwimmer> anwesendeBesucherArrayList = new ArrayList<>(); private ArrayList<Schwimmer> gesamtBesucherArrayList = new ArrayList<>(); private Pumpe pumpe = new Pumpe(); private UseController useControllerS; private Sprachmodul sprachmodulS; //Automat gibt Chip-armbänder gegen Bezahlung aus. //Unterschiedliche Farbe der Bänder nach Tarifgruppe (zb grün für Schüler, blau für Senioren, rot für Vollpreis) //Superklasse Schwimmer, Subklassen Tarifgruppen. //Preisstaffelung nach Schwimmdauer. private BargeldAnnahmeAutomat bargeldAnnahmeAutomat= new BargeldAnnahmeAutomat(); private String infoIDfertigerSchwimmer = ""; private DecimalFormat decimalFormat = new DecimalFormat("###0.##"); private ArrayList<Duration> vollzahlerBesuche = new ArrayList<>(); private ArrayList<Duration> seniorenBesuche = new ArrayList<>(); private ArrayList<Duration> schuelerBesuche = new ArrayList<>(); private boolean feueralarm; //ctr public Schwimmbad (UseController useController){ this.useControllerS = useController; sprachmodulS = new Sprachmodul(Sprachmodul.Sprache.DEU, this); } //end ctr //bei Eintritt eines Besuchers werden Zaehler angepasst. public void eintreten(Schwimmer s){ this.gesamtBesucherArrayList.add(s); this.anwesendeBesucherArrayList.add(s); BargeldAnnahmeAutomat.setEinnahmenCounter(getBargeldAnnahmeAutomat().getEinnahmenCounter() + s.getPreis()); ++this.gesamtBesucherCounter; ++this.anwesendeBesucherCounter; s.setInstantEintreten(Instant.now()); System.out.println("LOG: Geplante Besuchsdauer maximal " + s.getBesuchsDauer() + " Stunden"); }//end eintreten public void verlassenSchw_2(int pId){ Schwimmer fertigerSchwimmer = null; //Validierung - Anwesende im Bad? if (anwesendeBesucherCounter >0) { for (Schwimmer sc: anwesendeBesucherArrayList) { if (sc.getArmbandID() == pId) { fertigerSchwimmer = sc; } } //Validierung - wurde ein Schwimmer übergeben? if (fertigerSchwimmer !=null) { fertigerSchwimmer.setInstantVerlassen(Instant.now()); fertigerSchwimmer.setDuration(Duration.between(fertigerSchwimmer.getInstantEintreten(), fertigerSchwimmer.getInstantVerlassen())); fertigerSchwimmer.speichereDuration(); System.out.println("LOG Schwimmbad: Dauer Aufenthalt in Sekunden : " + fertigerSchwimmer.getDuration().toSeconds()); //Kurzzeit-Karten werden auf Zeitüberschreitung geprüft, gegebenenfalls zur Nachzahlung beim Ausgangs-Automaten aufgefordert bevor Austrittsschranke freigegeben wird. //Einnahmencounter und Eintrittspreis des betreffenden Schwimmers werden für statistische Verarbeitung entsprechend erhöht (siehe Rahmen_4_nachzahlen) if (fertigerSchwimmer.isKurzzeit() && fertigerSchwimmer.getDuration().toSeconds() > 3 && !feueralarm){ useControllerS.setNachZahlBedingung(true); new Rahmen_4_nachzahlen(useControllerS, fertigerSchwimmer); }else { System.out.println("LOG: Tschuess, ID " + fertigerSchwimmer.getArmbandID()); infoIDfertigerSchwimmer = "<html><body>" + getSprachmodulS().getSchwBadAbschiedSFV() + fertigerSchwimmer.getArmbandID() + "!<br/>" + fertigerSchwimmer.gebeAusDuration() + "</html></body>"; anwesendeBesucherArrayList.remove(fertigerSchwimmer); --this.anwesendeBesucherCounter; } }else{ infoIDfertigerSchwimmer = sprachmodulS.getLabel5ChipleseFehlerSFV(); } }else{ infoIDfertigerSchwimmer = sprachmodulS.getLabel5BadLeerSFV(); } }//end verlassen public void aufzahlenSchwimmbad(){ --Schwimmbad.anwesendeBesucherCounter; } //Ausgabe durchschnittliche Besuchsdauer (nach Tarifgruppe) public String schnittDauerAusgebenVollzahler(){ Duration sum = Duration.ZERO; for(Duration d: vollzahlerBesuche){ sum = sum.plus(d); System.out.println("LOG:" + sum.toSeconds()); } System.out.println("LOG: Elemente in VollzahlerBesucheArrList: " + vollzahlerBesuche.size()); System.out.println("LOG: Summe aller Besuche in Sekunden: " + sum.toSeconds()); //Gefahr Division durch 0 //daher Exception Handling durch try-catch zur Vermeidung von Laufzeitfehlern. Duration average = Duration.ZERO; try { average = sum.dividedBy(vollzahlerBesuche.size()); }catch (Exception e){ System.out.println("LOG: " + e); } long h = average.toHours(); long m = average.toMinutesPart(); long s = average.toSecondsPart(); String averageFormatiert = String.format("%02d:%02d:%02d",h,m,s); System.out.println("LOG: Schnitt aller Besuche in Sekunden: " + average.toSeconds()); return averageFormatiert; } public String schnittDauerAusgebenSenioren(){ Duration sum = Duration.ZERO; for(Duration d: seniorenBesuche){ sum = sum.plus(d); System.out.println("LOG:" + sum.toSeconds()); } System.out.println("LOG: Elemente in SeniorenBesucherArrList: " + seniorenBesuche.size()); System.out.println("LOG: Summe aller Besuche in Sekunden: " + sum.toSeconds()); Duration average = Duration.ZERO; //Gefahr Division durch 0 try { average = sum.dividedBy(seniorenBesuche.size()); }catch (Exception e){ System.out.println("LOG: " + e); } long h = average.toHours(); long m = average.toMinutesPart(); long s = average.toSecondsPart(); String averageFormatiert = String.format("%02d:%02d:%02d",h,m,s); System.out.println("LOG: Schnitt aller Besuche in Sekunden: " + average.toSeconds()); return averageFormatiert; } public String schnittDauerAusgebenSchueler(){ Duration sum = Duration.ZERO; for(Duration d: schuelerBesuche){ sum = sum.plus(d); System.out.println("LOG:" + sum.toSeconds()); } System.out.println("LOG: Elemente in SchuelerBesucherArrList: " + schuelerBesuche.size()); System.out.println("LOG: Summe aller Besuche in Sekunden: " + sum.toSeconds()); Duration average = Duration.ZERO; //Gefahr Division durch 0 try { average = sum.dividedBy(schuelerBesuche.size()); }catch (Exception e){ System.out.println("LOG: " + e); } long h = average.toHours(); long m = average.toMinutesPart(); long s = average.toSecondsPart(); String averageFormatiert = String.format("%02d:%02d:%02d",h,m,s); System.out.println("LOG: Schnitt aller Besuche in Sekunden: " + average.toSeconds()); return averageFormatiert; } public double rechneProzent(double pGesamt, double pAnteil){ return (pAnteil*100)/pGesamt; } public String errechneAnteileAnEinnahmenVollzahler(){ long anzahlVollzahler = gesamtBesucherArrayList.stream().filter(schwimmer -> schwimmer.getTarifGruppe().equals("Vollzahler")).count(); double preiseVollzahler = 0; //Stream mit 2 Intermediates //Anwendung der Functional Interfaces Predicate und Function preiseVollzahler = gesamtBesucherArrayList.stream() //filter() verlangt Subklasse von FI Predicate, Methode test(), Syntax lambda expression - aus allen Besuchern werden Vollzahler herausgefiltert. .filter(schwimmer -> schwimmer.getTarifGruppe().equals("Vollzahler")) //map() verlangt FI Function, dessen Methode apply() ruft //Schwimmer.getPreis() auf, Syntax method reference //Beträge Eintritt werden ermittelt .map(Schwimmer::getPreis) //Eintritte (Typ double) werden summiert und zurückgegeben. //Quellenangabe Summierung Double-Werte in terminal operation: https://www.baeldung.com/java-stream-sum .collect(Collectors.summingDouble(Double::doubleValue)); double anteilEinnahmenVollzahler = rechneProzent(BargeldAnnahmeAutomat.getEinnahmenCounter(), preiseVollzahler); return sprachmodulS.getSchwibaEinnahmenVonSFV() + anzahlVollzahler + sprachmodulS.getSchwibaVollzahlernSFV() + "€" + preiseVollzahler + " - " + decimalFormat.format(anteilEinnahmenVollzahler) + sprachmodulS.getSchwibaProzentSFV(); } public String errechneAnteileAnEinnahmenSenioren() { long anzahlSenioren = gesamtBesucherArrayList.stream().filter(schwimmer -> schwimmer.getTarifGruppe().equals("Senior")).count(); double preiseSenioren = 0; //Stream mit 2 Intermediates //Anwendung der Functional Interfaces Predicate und Function preiseSenioren = gesamtBesucherArrayList.stream().filter(schwimmer -> schwimmer.getTarifGruppe().equals("Senior")).map(schwimmer -> schwimmer.getPreis()).collect(Collectors.summingDouble(Double::doubleValue)); double anteilEinnahmenSenioren = rechneProzent(BargeldAnnahmeAutomat.getEinnahmenCounter(), preiseSenioren); return sprachmodulS.getSchwibaEinnahmenVonSFV() + anzahlSenioren + sprachmodulS.getSchwibaSeniorenSFV() + "€" + preiseSenioren + " - " + decimalFormat.format(anteilEinnahmenSenioren) + sprachmodulS.getSchwibaProzentSFV(); } public String errechneAnteileAnEinnahmenSchueler(){ long anzahlSchueler = gesamtBesucherArrayList.stream().filter(schwimmer -> schwimmer.getTarifGruppe().equals("Schueler")).count(); double preiseSchueler; preiseSchueler = gesamtBesucherArrayList.stream().filter(schwimmer -> schwimmer.getTarifGruppe().equals("Schueler")).map(schwimmer -> schwimmer.getPreis()).collect(Collectors.summingDouble(Double::doubleValue)); double anteilEinnahmenSchueler = rechneProzent(BargeldAnnahmeAutomat.getEinnahmenCounter(), preiseSchueler); return sprachmodulS.getSchwibaEinnahmenVonSFV() + anzahlSchueler + sprachmodulS.getSchwibaSchuelernSFV() + "€" + preiseSchueler + " - " + decimalFormat.format(anteilEinnahmenSchueler) + sprachmodulS.getSchwibaProzentSFV(); } // Methoden leiten Nachrichten weiter (zB aus UseController an Pumpe.) public void vermittleSetBetrieb(boolean b){ pumpe.setBetrieb(b); } public boolean vermittleIsBetrieb(){ return pumpe.isBetrieb(); } public void vermittleSetPassendeUmlaufGeschwindigkeit(){ Pumpe.setPassendeUmlaufGeschwindigkeit(); } public int rufePumpeUG(){ return Pumpe.getUmlaufGeschwindigkeit(); } public void vermittleSetUmlaufGeschwindigkeit(int i){ Pumpe.setUmlaufGeschwindigkeit(i); } //Getter und Setter public void setFeueralarm(boolean feueralarm) { this.feueralarm = feueralarm; } public ArrayList<Schwimmer> getAnwesendeBesucherArrayList() { return anwesendeBesucherArrayList; } public String getInfoID() { return infoIDfertigerSchwimmer; } public BargeldAnnahmeAutomat getBargeldAnnahmeAutomat() { return bargeldAnnahmeAutomat; } public static int getAnwesendeBesucherCounter() { return anwesendeBesucherCounter; } public int getGesamtBesucherCounter() { return gesamtBesucherCounter; } public ArrayList<Duration> getSchuelerBesuche() { return schuelerBesuche; } public ArrayList<Duration> getVollzahlerBesuche() { return vollzahlerBesuche; } public ArrayList<Duration> getSeniorenBesuche() { return seniorenBesuche; } public Sprachmodul getSprachmodulS() { return sprachmodulS; } public void setSprachmodulS(Sprachmodul sprachmodulS) { this.sprachmodulS = sprachmodulS; } public UseController getUseControllerS() { return useControllerS; } }//end class
true
d6e5bf99d470b569fa4b871f8f7173321175b31b
Java
CLTracker/CLT-mobileapp
/app/src/main/java/com/clt/conventionlogistictracker/NewsViewAdapter.java
UTF-8
3,077
2.34375
2
[]
no_license
package com.clt.conventionlogistictracker; import android.content.Context; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; import java.util.ArrayList; /** * Created by dongw on 5/2/17. */ public class NewsViewAdapter extends RecyclerView.Adapter<NewsViewAdapter.NewsViewHolder> { public class NewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private CardView card; private TextView title; private TextView announcement; private TextView author; public ImageView imageView; public NewsViewHolder(View itemView) { super(itemView); itemView.setOnClickListener(this); title = (TextView) itemView.findViewById(R.id.firstLine); announcement = (TextView) itemView.findViewById(R.id.secondLine); author = (TextView) itemView.findViewById(R.id.thirdLine); imageView = (ImageView) itemView.findViewById(R.id.company_logo); } @Override public void onClick(View v) { Log.d("RecyclerView onClick", "Element " + getAdapterPosition() + " clicked."); if (mOnEntryClickListener != null) { mOnEntryClickListener.onEntryClick(v, getLayoutPosition()); } } } private Context mContext; private ArrayList<News> mNews; public NewsViewAdapter(Context context, ArrayList<News> arrayNews) { mContext = context; mNews = arrayNews; } @Override public int getItemCount() { return mNews.size(); } @Override public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item_layout, parent, false); return new NewsViewHolder(view); } @Override public void onBindViewHolder(NewsViewHolder holder, int position) { News news = mNews.get(position); Picasso.with(mContext) .load(news.getLogoUrl()) .into(holder.imageView); holder.title.setText(news.getTitle()); holder.announcement.setText(news.getText()); holder.author.setText(news.getAuthor()); } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); } private com.clt.conventionlogistictracker.RecyclerViewAdapter.OnEntryClickListener mOnEntryClickListener; public interface OnEntryClickListener { void onEntryClick(View view, int position); } public void setOnEntryClickListener(com.clt.conventionlogistictracker.RecyclerViewAdapter.OnEntryClickListener onEntryClickListener) { mOnEntryClickListener = onEntryClickListener; } }
true
c60bc8863b1143cf258628fc4b1c8f4786c0cf70
Java
BBK-PiJ-2016-67/exercises
/d9/3/Employee.java
UTF-8
153
2.71875
3
[]
no_license
public class Employee implements LinkedElement { public Employee next; public String name; public Employee(String name) { this.name = name; } }
true
d3bbf3a18b6d83b52d633d3a00593708d91df9e5
Java
jacrylodai/CriminalIntentRev
/src/com/bignerdranch/android/crimeintentrev/utils/PictureUtils.java
GB18030
2,188
2.609375
3
[ "Apache-2.0" ]
permissive
package com.bignerdranch.android.crimeintentrev.utils; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.view.Display; import android.widget.ImageView; public class PictureUtils { private static final String TAG = "PictureUtils"; /** * ͼƬѹصBitmapDrawableͼƬߴĻߴжԱȣѹ * @param activity * @param filePath * @return */ public static BitmapDrawable getScaledDrawable(Activity activity,String filePath){ Display display = activity.getWindowManager().getDefaultDisplay(); float desWidth = display.getWidth(); float desHeight = display.getHeight(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(filePath, options); float srcWidth = options.outWidth; float srcHeight = options.outHeight; int inSampleSize = 1; if( (srcWidth > desWidth) || (srcHeight > desHeight) ){ int widthSampleSize = Math.round(srcWidth/desWidth); LogUtil.d(TAG, "srcWidth:"+srcWidth+"--desWidth:"+desWidth +"--widthSampleSize:"+widthSampleSize); int heightSampleSize = Math.round(srcHeight/desHeight); LogUtil.d(TAG, "srcHeight:"+srcHeight+"--desHeight:"+desHeight +"--heightSampleSize:"+heightSampleSize); if(widthSampleSize > heightSampleSize){ inSampleSize = widthSampleSize; }else{ inSampleSize = heightSampleSize; } } options = new BitmapFactory.Options(); options.inSampleSize = inSampleSize; Bitmap bitmap = BitmapFactory.decodeFile(filePath, options); return new BitmapDrawable(activity.getResources(), bitmap); } /** * ͷimageViewеͼƬռõڴռ * @param imageView */ public static void cleanImageView(ImageView imageView){ Drawable drawable = imageView.getDrawable(); if(drawable instanceof BitmapDrawable){ BitmapDrawable bitmapDrawable = (BitmapDrawable)drawable; bitmapDrawable.getBitmap().recycle(); imageView.setImageDrawable(null); } } }
true
f0a542e224358fb9a0aeec9e123e13a3a5dd18f9
Java
hcpx/program
/kanleme_v2/src/com/scchuangtou/model/PromoCodeInfo.java
UTF-8
220
1.546875
2
[]
no_license
package com.scchuangtou.model; public class PromoCodeInfo { public String promo_code; public int type; public float money; public long start_time; public long end_time; public String user_id; public long time; }
true
058dcd79e6b797deabc1548831c21e02d8681a13
Java
AlenCaoning/springboot2.x-rabbitmq
/producer/src/main/java/com/alen/tasks/TaskSchedulerConfig.java
UTF-8
892
2.296875
2
[]
no_license
/** * @author: Alen Cao * @description: * @time: 2019/7/2 15:03 */ package com.alen.tasks; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.SchedulingConfigurer; import org.springframework.scheduling.config.ScheduledTaskRegistrar; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @Configuration @EnableScheduling public class TaskSchedulerConfig implements SchedulingConfigurer { @Override public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) { scheduledTaskRegistrar.setScheduler(taskScheduler()); } @Bean(destroyMethod = "shutdown") public Executor taskScheduler() { return Executors.newScheduledThreadPool(100); } }
true
e114ce107a81427b6073a180afe79653d8aeb301
Java
hanoseok/Caches
/src/main/java/com/hanoseok/cache/redis/service/RedisClusterCacheService.java
UTF-8
1,159
2.453125
2
[]
no_license
package com.hanoseok.cache.redis.service; import org.springframework.beans.factory.InitializingBean; import redis.clients.jedis.*; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Created by hanoseok on 2014. 4. 4.. */ public class RedisClusterCacheService<T> implements RedisCacheService <T>, InitializingBean { private JedisCluster jedis; @Override public T get(String key) { try{ return (T)jedis.get(key); }catch(Exception e){ return null; } } @Override public void set(String key, T t) { try{ jedis.set(key, (String) t); }catch(Exception e){ } } @Override public void del(String key) { jedis.del(key); } @Override public void afterPropertiesSet() throws Exception { Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>(); jedisClusterNodes.add(new HostAndPort("192.168.239.133", 6379)); jedisClusterNodes.add(new HostAndPort("192.168.239.134", 6379)); jedisClusterNodes.add(new HostAndPort("192.168.239.135", 6379)); jedisClusterNodes.add(new HostAndPort("192.168.239.136", 6379)); jedis = new JedisCluster(jedisClusterNodes); } }
true
44ce6f3c4f7dd01b2124e96378a780ce2e73c4e6
Java
Trunker/Formal-WordAid
/app/src/main/java/dev/goodjob/wordmemorizationaid/NewsListEditActivity.java
UTF-8
8,046
2.03125
2
[]
no_license
package dev.goodjob.wordmemorizationaid; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.SearchView; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class NewsListEditActivity extends AppCompatActivity { private static final String TAG = "NewsListEditActivity"; public static String clickItemUrl; ListView lvNews; // for listing all news items ArrayList<String> alNews; // get data from news items database ArrayAdapter adapter; // an adapter used to put data from arraylist into listView DatabaseHelperActivity db1 = new DatabaseHelperActivity(this); // a newsitem instance @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_news_list_edit); alNews = new ArrayList<String>(); lvNews = findViewById(R.id.lvnewsListEditAdd); viewData(); FloatingActionButton btnNewsListItemsAdd= findViewById(R.id.btnNewsListItemsAdd); btnNewsListItemsAdd.setOnClickListener(new View.OnClickListener() { //add listener for "add" button @Override public void onClick(View v) { Intent intent = new Intent(NewsListEditActivity.this, addNewsItems.class); startActivity(intent); } }); lvNews.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { getUrl(lvNews.getItemAtPosition(position).toString()); Intent intent = new Intent(NewsListEditActivity.this, NewsListItemsWebView.class); startActivity(intent); } }); lvNews.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) { getUrl(lvNews.getItemAtPosition(position).toString()); final String selectedItem = parent.getItemAtPosition(position).toString(); final AlertDialog.Builder builder = new AlertDialog.Builder(NewsListEditActivity.this); builder.setMessage("Do you want to remove " + selectedItem + "?"); builder.setCancelable(false); builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { adapter.remove(selectedItem); db1.deleteEntry(clickItemUrl); Log.d(TAG, "onItemLongClick: "+ "entry"+ clickItemUrl +"has been deleted from"+db1.DB_TABLE); adapter.notifyDataSetChanged(); Toast.makeText( getApplicationContext(), selectedItem + " has been removed.", Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // Create and show the dialog builder.show(); // Signal OK to avoid further processing of the long click return true; } }); //for adding words // lvNews.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { // @Override // public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { // getUrl(lvNews.getItemAtPosition(position).toString()); // DatabaseNewsActivity.DB_TABLE = "\""+NewsListEditActivity.clickItemUrl + "\""; // Intent intent = new Intent(NewsListEditActivity.this, wordListActivity.class); // startActivity(intent); // Log.d(TAG, "onItemLongClick: URl is"+ clickItemUrl); // return false; // } // }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_search, menu); MenuItem item = menu.findItem(R.id.menuSearch); SearchView searchView = (SearchView)item.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { if(!newText.equals("")) { if (adapter != null) { adapter.getFilter().filter(newText); } else { AlertDialog.Builder builder = new AlertDialog.Builder(NewsListEditActivity.this); builder.setMessage("There is no item"); builder.setCancelable(false); builder.setNegativeButton("I see", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); } } return false; } }); return super.onCreateOptionsMenu(menu); } @Override protected void onRestart() { super.onRestart(); alNews.clear(); viewData(); Toast.makeText(this,"Come on", Toast.LENGTH_SHORT).show(); } public void viewData(){ Cursor cursor = db1.viewData(); if(cursor.getCount()==0){ Toast.makeText(this, "There is no data", Toast.LENGTH_SHORT).show(); }else{ while (cursor.moveToNext()){ alNews.add(cursor.getString(1).replaceAll("\"", "").replaceAll("##", "")); } adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, alNews); lvNews.setAdapter(adapter); } cursor.close(); } public void getUrl(String itemTitle){ Cursor cursor = db1.viewData(); if(cursor.getCount()==0){ Toast.makeText(this, "There is no data", Toast.LENGTH_SHORT).show(); }while (cursor.moveToNext()){ String cursorString = cursor.getString(1).replaceAll("\"",""); Log.d(TAG, "cursorString is "+cursorString); Log.d(TAG, "itemTitle is "+itemTitle); if(itemTitle.equalsIgnoreCase(cursorString)){ clickItemUrl = cursor.getString(3).replaceAll("\"",""); Log.d(TAG, "equal is true"); Log.d(TAG, "getUrl: "+clickItemUrl); } } cursor.close(); } }
true
bb3e08340819fc87e521e23b84060a6b7b78ad73
Java
Shaw007/BrowseProducts
/app/src/main/java/com/srmstudios/browseproducts/ui/sign_in/SignInModel.java
UTF-8
2,053
2.421875
2
[]
no_license
package com.srmstudios.browseproducts.ui.sign_in; import com.srmstudios.browseproducts.data.room.AppDatabase; import com.srmstudios.browseproducts.data.room.model.User; import com.srmstudios.browseproducts.util.interfaces.IDatabaseOps; import io.reactivex.Observable; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Function; import io.reactivex.schedulers.Schedulers; public class SignInModel implements SignInMVP.Model { private AppDatabase appDatabase; public SignInModel(AppDatabase appDatabase) { this.appDatabase = appDatabase; } @Override public void getUser(String email, IDatabaseOps iDatabaseOps) { Observable.just(appDatabase) .map(new Function<AppDatabase, User>() { @Override public User apply(AppDatabase appDatabase) throws Exception { return appDatabase.getUserDao().getUser(email); } }) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<User>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(User user) { iDatabaseOps.onSuccess(user); } @Override public void onError(Throwable e) { e.printStackTrace(); if(e instanceof NullPointerException){ iDatabaseOps.onError("User not found", e); }else { iDatabaseOps.onError("Something went wrong", e); } } @Override public void onComplete() { } }); } }
true
9d84b69b562d27d04bf61e9fad9703d1499aca75
Java
liuguojin2017/ShiroLearn
/ssm-shiro-web/src/main/java/com/fengwenyi/ssmshiroweb/realm/CustomRealm.java
UTF-8
2,932
2.25
2
[]
no_license
package com.fengwenyi.ssmshiroweb.realm; import com.fengwenyi.ssmshiroweb.dao.UserDao; import com.fengwenyi.ssmshiroweb.vo.User; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.util.ByteSource; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.Resource; import java.util.*; /** * @author Wenyi Feng * @since 2018-10-15 */ public class CustomRealm extends AuthorizingRealm { @Resource private UserDao userDao; // 授权 protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { String username = (String) principals.getPrimaryPrincipal(); // 获取角色 Set<String> roles = getRolesByUsername(username); Set<String> permissions = getPermissionsByUsername(username); SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); authorizationInfo.setRoles(roles); authorizationInfo.setStringPermissions(permissions); return authorizationInfo; } private Set<String> getPermissionsByUsername(String username) { Set<String> permissionMap = new HashSet<String>(); // permissionMap.add("user:select"); // permissionMap.add("user:add"); // permissionMap.add("user:update"); permissionMap.add("user:delete"); return permissionMap; } private Set<String> getRolesByUsername(String username) { List<String> list = userDao.findRolesByUsername(username); Set<String> roleMap = new HashSet<String>(list); return roleMap; } // 认证 protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { // 从主体传过来的认证信息中,获取用户名 String username = (String) token.getPrincipal(); // 通过用户名到数据库中获取凭证 String password = getPasswordByUsername(username); // System.out.println(password); if (password == null) return null; SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, getName()); // 使用admin对密码进行加密 authenticationInfo.setCredentialsSalt(ByteSource.Util.bytes("admin")); return authenticationInfo; } private String getPasswordByUsername(String username) { User user = userDao.findUserByUserName(username); if (user != null) return user.getPassword(); return null; } }
true
98f3f73e911e240884d780bc193b8bf245d4ed32
Java
jayeshagwan1/iBeacon
/app/src/main/java/com/infocepts/retreat2017/retreat2017/Employee.java
UTF-8
765
2.25
2
[]
no_license
package com.infocepts.retreat2017.retreat2017; import java.util.Date; /** * Created by jjagwan on 31-01-2017. */ public class Employee { public String getEmployeeId() { return employeeId; } public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } private String employeeName; private String employeeId; public Date getDatetimestamp() { return datetimestamp; } public void setDatetimestamp(Date datetimestamp) { this.datetimestamp = datetimestamp; } private Date datetimestamp; }
true
547eb0f76e4d8380f71d76068fde9f2cb810b7d1
Java
EnnBi/Powerradar
/powerradar/src/main/java/com/stie/powerradar/dao/MeasurementDao.java
UTF-8
1,172
2.0625
2
[]
no_license
package com.stie.powerradar.dao; import java.time.LocalDateTime; import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import com.stie.powerradar.customdao.MeasurementCustomDao; import com.stie.powerradar.domains.Measurement; import com.stie.powerradar.projections.MeasurementDTO; public interface MeasurementDao extends CrudRepository<Measurement, Long>,MeasurementCustomDao { @Query("Select ROUND(SUM(m.power),0) from Measurement m where m.measurement_time = :time and m.site.id = :site") Long findPowerConsumption(@Param("time") LocalDateTime time,@Param("site") long site); @Query("Select new com.stie.powerradar.projections.MeasurementDTO(ROUND(SUM(m.power),0),m.device.deviceCategory) from Measurement m where m.measurement_time = :time and m.site.id = :site GROUP BY m.device.deviceCategory") List<MeasurementDTO> findPowerConsumptionGroupByDeviceCategory(@Param("time") LocalDateTime time,@Param("site") long site); @Query("Select Max(m.measurement_time) from Measurement m") LocalDateTime findMaxTime(); }
true
03c4344d76216b5b7830012f6103e97240e97ce5
Java
smkim816/booksearch
/src/main/java/com/web/repository/KeywordRepository.java
UTF-8
705
2.140625
2
[]
no_license
package com.web.repository; import com.web.domain.Keyword; import com.web.domain.Rank; import com.web.domain.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; @Repository public interface KeywordRepository extends JpaRepository<Keyword, Long> { Page<Keyword> findByUser(Pageable pageable, User user); @Query(value = "select new com.web.domain.Rank(t.text, count(t) as cnt) from Keyword t group by t.text order by count(t) desc") Page<Rank> findTop10(Pageable pageable); }
true
f0a27815723934d6c9909412f0fbd208aece56af
Java
ithinksky/java-patterns
/src/test/java/com/ithinksky/patterns/a03structural/t06composite/TreeNodeTest.java
UTF-8
451
2.6875
3
[ "MIT" ]
permissive
package com.ithinksky.patterns.a03structural.t06composite; import com.google.gson.Gson; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; /** * @author tengpeng.gao */ @Slf4j class TreeNodeTest { @Test void add() { TreeNode nodeA = new TreeNode("A"); TreeNode nodeB = new TreeNode("B"); nodeA.add(nodeB); Gson gson = new Gson(); log.info(" === {}", gson.toJson(nodeA)); } }
true
1f236113b81a5ffe27b43cf60a1f3e56a7e64e5a
Java
alexTrifonov/atrifonov
/carstore_spring/src/main/java/ru/job4j/carstorespring/crudRepositories/DriveRepository.java
UTF-8
399
2.171875
2
[ "Apache-2.0" ]
permissive
package ru.job4j.carstorespring.crudRepositories; import org.springframework.data.repository.CrudRepository; import ru.job4j.carstorespring.models.Drive; import java.util.List; /** * Repository for Drive. * @author atrifonov. * @version 1. * @since 02.04.2018. */ public interface DriveRepository extends CrudRepository<Drive, Integer> { List<Drive> findByDriveType(String driveType); }
true
02150d7b61b15e69752746c34ac64942b9b32393
Java
picalag/PicalagPserver
/src/java/recommender/VenueRecommender.java
UTF-8
3,429
2.328125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package recommender; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.NamingException; import org.apache.mahout.cf.taste.common.TasteException; import representations.User; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; import org.apache.mahout.cf.taste.impl.model.jdbc.MySQLBooleanPrefJDBCDataModel; import org.apache.mahout.cf.taste.impl.model.jdbc.MySQLJDBCDataModel; import org.apache.mahout.cf.taste.impl.recommender.GenericItemBasedRecommender; import org.apache.mahout.cf.taste.impl.similarity.LogLikelihoodSimilarity; import org.apache.mahout.cf.taste.impl.similarity.TanimotoCoefficientSimilarity; import org.apache.mahout.cf.taste.model.DataModel; import org.apache.mahout.cf.taste.recommender.ItemBasedRecommender; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.apache.mahout.cf.taste.similarity.ItemSimilarity; import representations.recommendation.RecommendedVenue; /** * * @author seb */ public class VenueRecommender { private VenueRecommender() { } /** * Recommends venues to user u based on it's favorite venues (collaborative filtering) * Uses an Item-Based CF system as the number of venues is not expected to vary a lot * @param u user who needs recommendations * @param nb_recs maximum number of recommendations * @return an ArrayList of recommended venues (that encapsulates the venue recommended and explanations) */ public static ArrayList<RecommendedVenue> recommendVenues(User u, int nb_recs) { ArrayList<RecommendedVenue> recommendedVenues = new ArrayList<RecommendedVenue>(); try { DataModel model; Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("jdbc/picalag_pserver"); model = new MySQLBooleanPrefJDBCDataModel(ds, "users_favorite_venues", "user_id", "venue_id", ""); /*Specifies the Similarity algorithm*/ ItemSimilarity itemSimilarity = new LogLikelihoodSimilarity(model); //ItemSimilarity itemSimilarity = new TanimotoCoefficientSimilarity(model); /*Initalizing the recommender */ ItemBasedRecommender recommender = new GenericItemBasedRecommender(model, itemSimilarity); //calling the recommend method to generate recommendations List<RecommendedItem> recommendations = recommender.recommend((Integer) u.getId(), nb_recs); for (RecommendedItem r : recommendations) { RecommendedVenue rv = new RecommendedVenue((int) r.getItemID()); List<RecommendedItem> because = recommender.recommendedBecause((Integer) u.getId(), r.getItemID(), 3); for(RecommendedItem b : because) { rv.recommendedBecause.add((int) b.getItemID()); } recommendedVenues.add(rv); } } catch (TasteException ex) { Logger.getLogger(VenueRecommender.class.getName()).log(Level.SEVERE, null, ex); } catch (NamingException ex) { Logger.getLogger(VenueRecommender.class.getName()).log(Level.SEVERE, null, ex); } return recommendedVenues; } }
true
b252a888f08aea02d5583b9b8c15a7081b23cace
Java
Katr1nD/recruitment-platform
/src/main/java/com/exadel/recruitmentPlatform/dto/UserDto.java
UTF-8
800
1.992188
2
[]
no_license
package com.exadel.recruitmentPlatform.dto; import com.exadel.recruitmentPlatform.entity.UserRole; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.validation.constraints.Email; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class UserDto extends BaseDto { @NotBlank @Size(min = 1, max = 50) private String firstName; @NotBlank @Size(min = 1, max = 50) private String lastName; @Email @Size(min = 5, max = 50) private String email; private UserRole role; private String skype; private String photo; private String phone; private String otherInformation; }
true
d8ef1de4f4a6d0c77a463871ef5dcc88d68ec09a
Java
496268931/manyEclipse
/sptaskmanager/sptaskmanager-dao/src/main/java/com/bxt/sptask/dao/TaskAgentDao.java
UTF-8
259
1.742188
2
[]
no_license
package com.bxt.sptask.dao; import java.util.HashMap; import java.util.List; import com.bxt.sptask.taskhandle.vo.TaskVo; public interface TaskAgentDao { List<TaskVo> getAgentTask(HashMap<String,String> hmobj); Integer upateTaskStatus(String taskid); }
true
1ddde41f6bcbea7f6299a755624c0a8c05cb1bc8
Java
iptomar/PSI-Grupo-B-2019-2020
/Selenium_Tests/test/AaUnsuccess/Uns_LoginRegister.java
UTF-8
890
2
2
[]
no_license
package AaUnsuccess; /* * 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. */ import Testes.Login.Capabilities.Capabilities; import org.junit.Test; import org.openqa.selenium.WebDriver; import Admin.*; /** * * @author Luís Badalo */ public class Uns_LoginRegister { WebDriver driver; public Uns_LoginRegister() { this.driver = new Capabilities().getDriver(); } // TODO add test methods here. // The methods must be annotated with annotation @Test. For example: // @Test public void FailedLoginRegister() { new LoginUnsuccesfull(driver).loginUnsucessfully(); new LoginSuccess(driver).loginSucessfully(); new RegisterUnsuccessfull(driver).registerUnsuccessfully(); driver.quit(); } }
true
db1a2878c7b2cc496d7e5df03dc72b557a531725
Java
RinatB2017/Android_github
/android-jmdns/LocalCommunication/src/main/java/me/alwx/localcommunication/SampleApplication.java
UTF-8
606
2.25
2
[]
no_license
package me.alwx.localcommunication; import android.app.Application; import me.alwx.localcommunication.connection.ConnectionWrapper; /** * @author alwx * @version 1.0 */ public class SampleApplication extends Application { private ConnectionWrapper mConnectionWrapper; @Override public void onCreate() { super.onCreate(); } public void createConnectionWrapper(ConnectionWrapper.OnCreatedListener listener) { mConnectionWrapper = new ConnectionWrapper(getApplicationContext(), listener); } public ConnectionWrapper getConnectionWrapper() { return mConnectionWrapper; } }
true
3966ec26738cedada7ec50e2e9fefa114a8dc033
Java
kumarabhishek0809/microservices
/spring-reactive/src/main/java/com/simple/config/ItemDataInitializer.java
UTF-8
1,469
2.625
3
[]
no_license
package com.simple.config; import com.simple.document.Item; import com.simple.repository.ItemReactiveRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import reactor.core.publisher.Flux; import java.util.Arrays; import java.util.List; @Component public class ItemDataInitializer implements CommandLineRunner { @Autowired private ItemReactiveRepository itemReactiveRepository; @Override public void run(String... args) throws Exception { initialDataSetUp(); } private void initialDataSetUp() { itemReactiveRepository.deleteAll() .thenMany(Flux.fromIterable(data())) .flatMap(itemReactiveRepository::save) .thenMany(itemReactiveRepository.findAll()) .subscribe( item -> System.out.println("Item Inserted from Command Line"+item)); } private List<Item> data() { return Arrays.asList( Item.builder().description("Samsung TV").price(400.00).build(), Item.builder().description("LG TV").price(420.00).build(), Item.builder().description("Apple Watch").price(299.99).build(), Item.builder().description("Beats Head Phone").price(410.00).build(), Item.builder().id("ABC").description("Bose Head Phone").price(410.00).build() ); } }
true
af59850aff8d2e74003b67e84fbeb018d0833d5c
Java
XeonLyfe/Backdoored-1.7-Deobf-Source-Leak
/com/google/api/client/json/webtoken/JsonWebToken.java
UTF-8
808
2.421875
2
[ "MIT" ]
permissive
package com.google.api.client.json.webtoken; import com.google.api.client.util.Objects; import com.google.api.client.util.Preconditions; public class JsonWebToken { private final JsonWebToken$Header header; private final JsonWebToken$Payload payload; public JsonWebToken(JsonWebToken$Header header, JsonWebToken$Payload payload) { this.header = (JsonWebToken$Header)Preconditions.checkNotNull(header); this.payload = (JsonWebToken$Payload)Preconditions.checkNotNull(payload); } public String toString() { return Objects.toStringHelper(this).add("header", this.header).add("payload", this.payload).toString(); } public JsonWebToken$Header getHeader() { return this.header; } public JsonWebToken$Payload getPayload() { return this.payload; } }
true
48b4786b601be1ae34df72a80a03a27a4a12c57d
Java
newrelic/cloudformation-partner-integration
/NrqlAlertCondition/src/main/java/com/newrelic/alerts/nrqlalert/UpdateHandler.java
UTF-8
4,562
2.03125
2
[ "Apache-2.0" ]
permissive
package com.newrelic.alerts.nrqlalert; import com.newrelic.alerts.nrqlalert.model.NewRelicNrqlCondition; import java.io.IOException; import java.util.ArrayList; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.http.impl.client.HttpClients; import org.json.JSONArray; import org.json.JSONObject; import software.amazon.cloudformation.proxy.AmazonWebServicesClientProxy; import software.amazon.cloudformation.proxy.Logger; import software.amazon.cloudformation.proxy.OperationStatus; import software.amazon.cloudformation.proxy.ProgressEvent; import software.amazon.cloudformation.proxy.ResourceHandlerRequest; public class UpdateHandler extends BaseHandler<CallbackContext> { private AlertApiClient alertApiClient; public UpdateHandler() { this.alertApiClient = new AlertApiClient(AlertApiClient.URL_PREFIX, HttpClients.createDefault()); } // this will allow us to mock the client and not make real actual calls when testing public UpdateHandler(AlertApiClient alertApiClient) { this.alertApiClient = alertApiClient; } @Override public ProgressEvent<ResourceModel, CallbackContext> handleRequest( final AmazonWebServicesClientProxy proxy, final ResourceHandlerRequest<ResourceModel> request, final CallbackContext callbackContext, final Logger logger) { final ResourceModel model = request.getDesiredResourceState(); final String apiKey = model.getApiKey(); final int conditionId = model.getNrqlCondition().getId(); OperationStatus status = OperationStatus.SUCCESS; NrqlCondition modelNrqlCondition = model.getNrqlCondition(); // convert to our New Relic-specific class NewRelicNrqlCondition newRelicNrqlCondition = new NewRelicNrqlCondition(modelNrqlCondition); try { logger.log( String.format( "Attempting to update alert condition for condition ID: %d", conditionId)); JSONObject nrqlConditionJson = alertApiClient.update(newRelicNrqlCondition, apiKey, conditionId); NrqlCondition nrqlCondition = model.getNrqlCondition(); nrqlCondition.setEnabled(nrqlConditionJson.getBoolean("enabled")); nrqlCondition.setExpectedGroups(nrqlConditionJson.getInt("expected_groups")); nrqlCondition.setIgnoreOverlap(nrqlConditionJson.getBoolean("ignore_overlap")); nrqlCondition.setName(nrqlConditionJson.getString("name")); nrqlCondition.setRunbookUrl(nrqlConditionJson.getString("runbook_url")); nrqlCondition.setType(nrqlConditionJson.getString("type")); nrqlCondition.setValueFunction(nrqlConditionJson.getString("value_function")); nrqlCondition.setViolationTimeLimitSeconds( nrqlConditionJson.getInt("violation_time_limit_seconds")); // update query info Nrql nrql = new Nrql(); JSONObject nrqlJson = nrqlConditionJson.getJSONObject("nrql"); nrql.setQuery(nrqlJson.getString("query")); nrql.setSinceValue(nrqlJson.getInt("since_value")); nrqlCondition.setNrql(nrql); // update all terms ArrayList<Term> terms = new ArrayList<>(); JSONArray termsJson = nrqlConditionJson.getJSONArray("terms"); termsJson.forEach( termObj -> { JSONObject termJson = (JSONObject) termObj; Term term = new Term(); term.setDuration(termJson.getInt("duration")); term.setOperator(termJson.getString("operator")); term.setPriority(termJson.getString("priority")); term.setThreshold((double) termJson.getFloat("threshold")); term.setTimeFunction(termJson.getString("time_function")); terms.add(term); }); nrqlCondition.setTerms(terms); logger.log(String.format("Updated alert condition with ID: %d", conditionId)); } catch (IOException | AlertApiException e) { status = OperationStatus.FAILED; logger.log(ExceptionUtils.getStackTrace(e)); } return ProgressEvent.<ResourceModel, CallbackContext>builder() .resourceModel(model) .status(status) .build(); } }
true
f99695c054c5fd2c87d73907bb7a2ba6b51d4603
Java
WoogLim/SpringProject_PMS
/bpms/src/main/java/kr/or/ddit/projects/issue/service/AdminIssueService.java
UTF-8
2,652
2.171875
2
[]
no_license
package kr.or.ddit.projects.issue.service; import java.util.List; import kr.or.ddit.projects.issue.vo.IssueVO; import kr.or.ddit.projects.member.vo.MemberVO; import kr.or.ddit.vo.PagingVO; /** * @author 신광진 * @since 2021. 2. 9. * @version 1.0 * @see javax.servlet.http.HttpServlet * * <pre> * [[개정이력(Modification Information)]] * 수정일 수정자 수정내용 * ----------- -------- ---------------------- * 2021. 2. 9. 신광진 최초작성 * Copyright (c) 2021 by DDIT All right reserved * </pre> */ public interface AdminIssueService { /** * pagingVO의 검색조건과 일치하는 모든 이슈 조회 * * @param pagingVO * @return * * <pre> * 검색결과가 있는경우: List&lt;IssueVO&gt; * 검색결과가 없는경우: null * </pre> */ public List<IssueVO> retrieveIssueList(PagingVO<IssueVO> pagingVO); /** * pagingVO의 검색조건과 일치하는 이슈 수 조회 * * @param pagingVO * @return * * <pre> * 검색결과가 있는경우: return&gt;0 * 검색결과가 없는경우: 0 * </pre> */ public int retrieveIssueCount(PagingVO<IssueVO> pagingVO); /** * 파라미터로 받은 memberVO의 memId와 일치하는 회원이 발행한 ISSUE를 최근날짜순서로 최대 5건 조회 * * @param memberVO * @return * * <pre> * 검색결과가 있는경우: List&lt;IssueVOgt; * 검색결과가 없는경우: null * </pre> */ public List<IssueVO> retrieveIssueListByMember(MemberVO memberVO); /** * 파라미터로 받은 pagingVO의 searchVO조건에 맞는 이슈 담당자를 모두 조회 담당자 별 구분을 위해 사용 * * @param pagingVO * @return * * <pre> * 검색결과가 있는경우: List&lt;IssueVOgt; * 검색결과가 없는경우: null * </pre> */ public List<IssueVO> retrieveIssueDirectorList(PagingVO<IssueVO> pagingVO); /** * 파라미터로 받은 pagingVO의 searchDetail조건에 맞는 이슈 발행인을 모두 조회 발행인 별 구분을 위해 사용 * * @param pagingVO * @return * * <pre> * 검색결과가 있는경우: List&lt;IssueVOgt; * 검색결과가 없는경우: null * </pre> */ public List<IssueVO> retrieveBoardWriterList(PagingVO<IssueVO> pagingVO); /** * 등록된 모든 이슈의 상태별 개수를 조회 * @return * <pre> * 검색결과가 있는경우: List&lt;IssueVO&gt; * 검색결과가 없는경우: null * </pre> */ public List<IssueVO> retrieveIssueByState(); }
true
5460609d36fa5316c82c9e21eef7b26aa307d9af
Java
tatianakobayashi/bookshelfManagementApp
/trabalhoControleLivros/app/src/main/java/atividade/mobile/tatiana/trabalhocontrolelivros/activities/alteration/RemoveSeriesRelationshipActivity.java
UTF-8
2,836
2.09375
2
[]
no_license
package atividade.mobile.tatiana.trabalhocontrolelivros.activities.alteration; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import java.util.List; import atividade.mobile.tatiana.trabalhocontrolelivros.Database.DatabaseHelper; import atividade.mobile.tatiana.trabalhocontrolelivros.Database.DatabaseSeries; import atividade.mobile.tatiana.trabalhocontrolelivros.Database.DatabaseSeriesRelations; import atividade.mobile.tatiana.trabalhocontrolelivros.Models.Book; import atividade.mobile.tatiana.trabalhocontrolelivros.R; import atividade.mobile.tatiana.trabalhocontrolelivros.Models.Series; import atividade.mobile.tatiana.trabalhocontrolelivros.Models.User; public class RemoveSeriesRelationshipActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { private User user; private Book book; private Series serie; private DatabaseSeries helper; private boolean changed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_remove_series_relationship); Bundle bundle = getIntent().getExtras(); user = (User) bundle.getSerializable("logged_user"); book = (Book) bundle.getSerializable("Book"); if(user == null || book == null){ finish(); } Spinner spinner = findViewById(R.id.spnRemoveSeriesRelationship); Button button = findViewById(R.id.btnRemoveSeriesRelationship); helper = new DatabaseSeries(this); List<Series> series = helper.getAllSeriesByBook(book); ArrayAdapter<Series> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, series); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(this); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (changed) { DatabaseSeriesRelations relations = new DatabaseSeriesRelations(RemoveSeriesRelationshipActivity.this); relations.deleteSeriesRelationship(serie, book); } finish(); } }); } public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { serie = (Series) parent.getItemAtPosition(pos); changed = true; } public void onNothingSelected(AdapterView<?> parent) { // Another interface callback changed = false; } }
true
8fb48d192074285fa44613bb78b8e886119fece7
Java
baskFuming/Business_Android
/app/src/main/java/com/zwonline/top28/bean/BannerBean.java
UTF-8
1,018
2.171875
2
[]
no_license
package com.zwonline.top28.bean; import java.util.List; /** * @author YSG * @desc * @date ${Date} */ public class BannerBean { /** * status : 1 * msg : * data : [{"type":"project","target":"33","img_src":"https://toutiao.28.com/data/upload/personal_avatars//171127/5a1b79b2d63ec.png_thumb.png"},{"type":"project","target":"59","img_src":"https://toutiao.28.com/data/upload/personal_avatars//171127/5a1bb881a885d.png_thumb.png"},{"type":"article","target":"71","img_src":"https://toutiao.28.com/data/upload/article_img/1711/08/5a02cb3751b76.jpg"}] * dialog : */ public int status; public String msg; public String dialog; public List<DataBean> data; public static class DataBean { /** * type : project * target : 33 * img_src : https://toutiao.28.com/data/upload/personal_avatars//171127/5a1b79b2d63ec.png_thumb.png */ public String type; public String target; public String img_src; } }
true
c419abea4a5f990c4a0131853d16e7d5127d3e7a
Java
plutztom/LogisticsApplication
/src/LogisticsManager/Orders/OrderLoader.java
UTF-8
4,399
2.640625
3
[]
no_license
package LogisticsManager.Orders; import java.io.File; import java.io.IOException; import java.util.HashMap; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import LogisticsManager.Facilities.FacilityManager; import LogisticsManager.Facilities.ItemNotFoundException; import LogisticsManager.Inventory.Items; import LogisticsManager.Inventory.ItemsManager; public class OrderLoader { private OrderManager omanager; private ItemsManager imanager; private FacilityManager fmanager; OrderLoader(FacilityManager fmanager,OrderManager omanager,ItemsManager imanager){ this.omanager = omanager; this.imanager = imanager; this.fmanager = fmanager; Load(); } public void Load(){ try { String fileName = "order.xml"; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); File xml = new File(fileName); if (!xml.exists()) { System.err.println("**** XML File '" + fileName + "' cannot be found"); System.exit(-1); } Document doc = db.parse(xml); doc.getDocumentElement().normalize(); HashMap<Items, Integer> order = new HashMap<>(); NodeList items = doc.getDocumentElement().getChildNodes(); for (int i = 0; i < items.getLength(); i++) { order = new HashMap<>(); if (items.item(i).getNodeType() == Node.TEXT_NODE) { continue; } String entryName = items.item(i).getNodeName(); if (!entryName.equals("orders")) { System.err.println("Unexpected node found: " + entryName); return; } // Get a node attribute NamedNodeMap aMap = items.item(i).getAttributes(); // Get a named nodes Element elem = (Element) items.item(i); String OrderId = elem.getElementsByTagName("id").item(0).getTextContent(); int OrderTime = Integer.parseInt(elem.getElementsByTagName("time").item(0).getTextContent()); String OrderDestination = elem.getElementsByTagName("destination").item(0).getTextContent(); // Get all nodes named "Book" - there can be 0 or more NodeList ItemsOrdered = elem.getElementsByTagName("items"); for (int j = 0; j < ItemsOrdered.getLength(); j++) { if (ItemsOrdered.item(j).getNodeType() == Node.TEXT_NODE) { continue; } entryName = ItemsOrdered.item(j).getNodeName(); if (!entryName.equals("items")) { System.err.println("Unexpected node found: " + entryName); return; } // Get some named nodes elem = (Element) ItemsOrdered.item(j); String ItemId = elem.getElementsByTagName("id").item(0).getTextContent(); int quantity = Integer.parseInt(elem.getElementsByTagName("quantity").item(0).getTextContent()); Items item = imanager.get(ItemId); // Create a string summary of the book order.put(item,quantity); } // Here I would create a Store object using the data I just loaded from the XML Order OrderPlaced = new Order(fmanager,OrderId,OrderTime,OrderDestination,order); omanager.addItem(OrderPlaced); } } catch (ParserConfigurationException | SAXException | IOException | DOMException | ItemNotFoundException e) { e.printStackTrace(); } } }
true
8094f3a48e6741a56649bd9748f98fbbceb612d0
Java
spyrotrot/java-exercise
/src/test/java/com/mypackage/ShiftMultiplyEncryptionTest.java
UTF-8
1,003
2.109375
2
[]
no_license
package com.mypackage; import org.junit.Test; import com.google.inject.Guice; import com.google.inject.Injector; public class ShiftMultiplyEncryptionTest extends ShiftEncryptionTest { @Test public void shouldShiftMultiplyEncrypt() throws InvalidEncryptionKeyException { Injector injector = Guice.createInjector(new AlgorithmModule( new ShiftMultiplyEncryption().toString())); EncryptionAlgorithm<KeyMaker> algorithm = injector .getInstance(EncryptionAlgorithm.class); shouldShiftEncrypt(algorithm); } @Test(expected = InvalidEncryptionKeyException.class) public void shouldThrowException() throws InvalidEncryptionKeyException { Injector injector = Guice.createInjector(new AlgorithmModule( new ShiftMultiplyEncryption().toString())); EncryptionAlgorithm<KeyMaker> algorithm = injector .getInstance(EncryptionAlgorithm.class); exceptionTest(algorithm); } }
true
1b65987d1ddc4c5ec8daf2c3bf7ecfcf5e18ea37
Java
liumeiGithub5/lock-rent-v0.02
/src/main/java/com/yifushidai/utils/GlobalExceptionHandler.java
UTF-8
2,486
2.25
2
[]
no_license
package com.yifushidai.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.dao.DuplicateKeyException; import org.springframework.validation.BindException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import javax.validation.ConstraintViolationException; /** * Created by liumei on 2017/11/29 14:32. * desc:全局异常 封装 */ @ControllerAdvice() @ConfigurationProperties public class GlobalExceptionHandler { protected Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class); public GlobalExceptionHandler() { log.info("GlobalExceptionHandler构建"); } @ExceptionHandler(RRException.class)//自定义异常 @ResponseBody public R RRExceptionHandler(RRException ex) { R r = R.error(ex.getCode(),ex.getMsg()); return r; } @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseBody public R missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException e) { R r = R.error(ErrorCodeConstant.ARGUMENT_VANISH,"缺少参数 "+e.getMessage()); return r; } @ExceptionHandler(MethodArgumentTypeMismatchException.class) @ResponseBody public R methodArgumentTypeMismatchExceptionExceptionHandler(MethodArgumentTypeMismatchException e) { R r = R.error(ErrorCodeConstant.ARGUMENT_TYPE_MISMATCH,"参数类型不正确"); return r; } @ExceptionHandler({BindException.class,ConstraintViolationException.class}) @ResponseBody public R ViolationException(Exception e) { R r = R.error(ErrorCodeConstant.ARGUMENT_VIOLATION,"参数校验异常"); return r; } @ExceptionHandler(DuplicateKeyException.class) @ResponseBody public R DuplicateKeyExceptionHandler( DuplicateKeyException e) { R r = R.error(ErrorCodeConstant.DUPLICATE,"数据已存在"); return r; } @ExceptionHandler(Exception.class)//处理其他异常 @ResponseBody public R exceptionHandler(Exception e) { R r = R.error(); return r; } }
true
e756245138eb2a6d0edd7c9d780de80926884fad
Java
bellmit/crmtest
/src/java/com/trilogy/app/crm/provision/gateway/ServiceProvisionGatewayClient.java
UTF-8
2,050
1.8125
2
[]
no_license
/* * This code is a protected work and subject to domestic and international * copyright law(s). A complete listing of authors of this work is readily * available. Additionally, source code is, by its very nature, confidential * information and inextricably contains trade secrets and other information * proprietary, valuable and sensitive to Redknee. No unauthorized use, * disclosure, manipulation or otherwise is permitted, and may only be used * in accordance with the terms of the license agreement entered into with * Redknee Inc. and/or its subsidiaries. * * Copyright (c) Redknee Inc. (Migreated for testing purposes) and its subsidiaries. All Rights Reserved. */ package com.trilogy.app.crm.provision.gateway; import java.util.Collection; import java.util.Map; import java.util.Set; import com.trilogy.app.crm.bean.Subscriber; import com.trilogy.framework.xhome.context.Context; /** * * * @author victor.stratan@redknee.com * @since 8.5 */ public interface ServiceProvisionGatewayClient { /** * Provision services on Service Provision Gateway. This will add and/or remove services. */ void provision(Context ctx, Set<Long> removeList, Set<Long> addList, Map<Integer, String> values, Subscriber sub) throws ServiceProvisionGatewayException; /** * Update services on Service Provision Gateway. This will NOT add or remove services. * A service may be removed and added as the only possible update call flow. * @param values TODO */ void update(Context ctx, Set<Long> currentList, Map<Integer, String> keyValues, Map<Integer, String> values, Subscriber sub) throws ServiceProvisionGatewayException; /** * Execute special command on Service Provision Gateway related to a service. * @param values TODO */ void execute(Context ctx, int command, long serviceID, Map<Integer, String> values, Subscriber sub) throws ServiceProvisionGatewayException; }
true
e63f11d00636e39b9c8288375ed7091eab820be9
Java
yaofei123/rxo-dsf
/hystrix-dashboard-server/src/main/java/com/refactoring/rxo/hystrix/HystrixDashboardServerApplication.java
UTF-8
665
1.648438
2
[]
no_license
/* * Copyright (C) 2017 北京好药师大药房连锁有限公司(www.ehaoyao.com) , All Rights Reserved. */ package com.refactoring.rxo.hystrix; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard; /** * @Description API熔断看板 * @Author * @Date 2017-12-23 11:03 * @Modified by: **/ @EnableHystrixDashboard @SpringBootApplication public class HystrixDashboardServerApplication { public static void main(String[] args) { SpringApplication.run(HystrixDashboardServerApplication.class, args); } }
true
730ba8d7dd6fb3821dbf103b46e7e3af79cc603f
Java
DanYuDev/UIBestPractice
/app/src/main/java/com/example/coderlt/uibestpractice/activity/PersonalBillActivity.java
UTF-8
4,609
2.234375
2
[]
no_license
package com.example.coderlt.uibestpractice.activity; import android.content.Intent; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bigkoo.pickerview.builder.TimePickerBuilder; import com.bigkoo.pickerview.listener.OnTimeSelectListener; import com.bigkoo.pickerview.view.TimePickerView; import com.example.coderlt.uibestpractice.R; import com.example.coderlt.uibestpractice.fragments.BillDetailFragment; import com.example.coderlt.uibestpractice.utils.Utils; import java.text.SimpleDateFormat; import java.util.Date; public class PersonalBillActivity extends AppCompatActivity implements View.OnClickListener{ private static final String TAG = "PersonalBillActivity"; private FloatingActionButton writeFab; private TextView titleText; private ImageView monthIv; private TabLayout billTab; private Fragment billDetailFragment; private FragmentManager fm; private FragmentTransaction fmt; private TimePickerView pvTime; private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_personal_bill); initViews(); } @Override public void onClick(View v){ switch (v.getId()){ case R.id.write_bill_fab: startActivity(new Intent(this,EditBillActivity.class)); break; case R.id.month_select_iv: Utils.showToast("Select Month."); // TODO 回头自己写一个日期选择动画,从底部弹出 window 那种,比较优雅 pvTime.show(); break; case R.id.month_tv: Utils.showToast("Select Month."); // TODO 回头自己写一个日期选择动画,从底部弹出 window 那种,比较优雅 pvTime.show(); break; default: break; } } private void initViews(){ // find view writeFab = findViewById(R.id.write_bill_fab); titleText = findViewById(R.id.title_tv); billTab = findViewById(R.id.personal_bill_tab); monthIv = findViewById(R.id.month_select_iv); // init fragments fm = getSupportFragmentManager(); // add listener monthIv.setOnClickListener(this); writeFab.setOnClickListener(this); billTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { switch (tab.getPosition()){ case 0: billDetailFragment = new BillDetailFragment(); fmt = fm.beginTransaction(); fmt.replace(R.id.fragment_content,billDetailFragment) .commit(); break; default: Utils.showToast("攻城狮正在努力 Coding..."); //时间选择器 break; } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); // init data titleText.setText("记账本"); billTab.addTab(billTab.newTab().setText("明细")); billTab.addTab(billTab.newTab().setText("类别报表")); billTab.addTab(billTab.newTab().setText("账户")); pvTime = new TimePickerBuilder(PersonalBillActivity.this, new OnTimeSelectListener() { @Override public void onTimeSelect(Date date, View v) { Utils.showToast("Date picked: "+date); String dateStr = sdf.format(date); Log.d(TAG,"The select date is :"+dateStr); ((BillDetailFragment)billDetailFragment).refreshData(dateStr.substring(0,7)); } }).isDialog(true) .build(); } }
true
9f5aeed1f26cffa14fca12e08b8684d39db8343b
Java
unica-open/siacbilapp
/src/main/java/it/csi/siac/siacbasegengsaapp/frontend/ui/model/registrazionemovfin/ConsultaRegistrazioneMovFinAccertamentoBaseModel.java
UTF-8
3,995
1.742188
2
[]
no_license
/* *SPDX-FileCopyrightText: Copyright 2020 | CSI Piemonte *SPDX-License-Identifier: EUPL-1.2 */ package it.csi.siac.siacbasegengsaapp.frontend.ui.model.registrazionemovfin; import java.util.EnumSet; import it.csi.siac.siacbasegengsaapp.frontend.ui.util.wrapper.registrazionemovfin.ElementoModificaMovimentoGestioneEntrataRegistrazioneMovFin; import it.csi.siac.siacbasegengsaapp.frontend.ui.util.wrapper.registrazionemovfin.ElementoSubAccertamentoRegistrazioneMovFin; import it.csi.siac.siacbasegengsaapp.frontend.ui.util.wrapper.registrazionemovfin.consultazione.ConsultaRegistrazioneMovFinAccertamentoHelper; import it.csi.siac.siacbilapp.frontend.ui.util.format.FormatUtils; import it.csi.siac.siacbilser.model.ImportiCapitoloEnum; import it.csi.siac.siacfinser.frontend.webservice.msg.DatiOpzionaliCapitoli; import it.csi.siac.siacfinser.frontend.webservice.msg.DatiOpzionaliElencoSubTuttiConSoloGliIds; import it.csi.siac.siacfinser.frontend.webservice.msg.RicercaAccertamentoPerChiaveOttimizzato; import it.csi.siac.siacfinser.model.Accertamento; import it.csi.siac.siacfinser.model.SubAccertamento; import it.csi.siac.siacfinser.model.movgest.ModificaMovimentoGestioneEntrata; import it.csi.siac.siacfinser.model.ric.RicercaAccertamentoK; /** * Classe base di model per la consultazione dell'accertamento. * * @author Marchino Alessandro * @version 1.0.0 - 07/10/2015 * */ public abstract class ConsultaRegistrazioneMovFinAccertamentoBaseModel extends ConsultaRegistrazioneMovFinMovimentoGestioneBaseModel<Accertamento, SubAccertamento, ElementoSubAccertamentoRegistrazioneMovFin, ModificaMovimentoGestioneEntrata, ElementoModificaMovimentoGestioneEntrataRegistrazioneMovFin, ConsultaRegistrazioneMovFinAccertamentoHelper>{ /** Per la serializzazione */ private static final long serialVersionUID = -8660196779235411777L; @Override public String getConsultazioneSubpath() { return "Accertamento"; } /** * Crea una request per il servizio di {@link RicercaAccertamentoPerChiaveOttimizzato}. * * @return la request creata */ public RicercaAccertamentoPerChiaveOttimizzato creaRequestRicercaAccertamentoPerChiaveOttimizzato() { RicercaAccertamentoPerChiaveOttimizzato request = creaPaginazioneRequest(RicercaAccertamentoPerChiaveOttimizzato.class); request.setEnte(getEnte()); request.setpRicercaAccertamentoK(creaPRicercaAccertamentoK()); request.setCaricaSub(true); request.setSubPaginati(true); DatiOpzionaliElencoSubTuttiConSoloGliIds datiOpzionaliElencoSubTuttiConSoloGliIds = new DatiOpzionaliElencoSubTuttiConSoloGliIds(); datiOpzionaliElencoSubTuttiConSoloGliIds.setEscludiAnnullati(true); request.setDatiOpzionaliElencoSubTuttiConSoloGliIds(datiOpzionaliElencoSubTuttiConSoloGliIds); DatiOpzionaliCapitoli datiOpzionaliCapitoli = new DatiOpzionaliCapitoli(); //Non richiedo NESSUN importo derivato del capitolo datiOpzionaliCapitoli.setImportiDerivatiRichiesti(EnumSet.noneOf(ImportiCapitoloEnum.class)); request.setDatiOpzionaliCapitoli(datiOpzionaliCapitoli); return request; } /** * Crea un'utilit&agrave; per la ricerca impegno. * * @return l'utility creata */ private RicercaAccertamentoK creaPRicercaAccertamentoK() { RicercaAccertamentoK utility = new RicercaAccertamentoK(); utility.setAnnoEsercizio(getAnnoEsercizioInt()); utility.setAnnoAccertamento(getAnno()); utility.setNumeroAccertamento(getNumero()); return utility; } @Override protected String ottieniDenominazioneMovimentoGestione() { return "Accertamento"; } @Override public String getStato() { if(consultazioneHelper.getMovimentoGestione() == null) { return ""; } return new StringBuilder() .append("Stato: ") .append(consultazioneHelper.getMovimentoGestione().getDescrizioneStatoOperativoMovimentoGestioneEntrata()) .append(" dal ") .append(FormatUtils.formatDate(consultazioneHelper.getMovimentoGestione().getDataStatoOperativoMovimentoGestioneEntrata())) .toString(); } }
true
f28ac3005318eb248d25e15e577800443f88551d
Java
shanghaif/jwr
/jwr/src/com/wr4/domain/EnExchangeCertInfo.java
UTF-8
7,816
1.632813
2
[]
no_license
package com.wr4.domain; import java.io.Serializable; public class EnExchangeCertInfo implements Serializable{ /** * */ private static final long serialVersionUID = 1L; //en_apply表中字段 private String license ; private String tax ; private String createdate ; private String cdate ; private String remarks ; private String orgid1 ; private String advice ; private String pid ; private String del ; private String enname ; private String safe ; private String renew ; private String zpreport ; private String province ; private String cid ; private String legalp ; private String grade ; private String email ; private String bustype ; private String resp ; private String respdate_review; private String type2 ; private String contact ; private String advice_review ; private String address ; private String mobile ; private String qual ; private String adminmot ; private String resp_review ; private String tel ; private String respdate ; private String orgid ; private String userid ; private String applytype ; private int id ; private String zpscore ; private String adminmotname; private String type2name; //cert表中字段 private String certnumber ; private String fzdate ; private String certtype ; private String certstatus ; private String reason ; private String stopdate ; private String changeresault;//CHANGERESAULT 换证申请是否成功 private String changereason;//CHANGEREASON 换证申请审批意见 private String changedate;//换证申请处理时间 private String city;//所在市 public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getChangeresault() { return changeresault; } public void setChangeresault(String changeresault) { this.changeresault = changeresault; } public String getChangereason() { return changereason; } public void setChangereason(String changereason) { this.changereason = changereason; } public String getChangedate() { return changedate; } public void setChangedate(String changedate) { this.changedate = changedate; } public static long getSerialversionuid() { return serialVersionUID; } public String getAdminmotname() { return adminmotname; } public void setAdminmotname(String adminmotname) { this.adminmotname = adminmotname; } public String getType2name() { return type2name; } public void setType2name(String type2name) { this.type2name = type2name; } public String getLicense() { return license; } public void setLicense(String license) { this.license = license; } public String getTax() { return tax; } public void setTax(String tax) { this.tax = tax; } public String getCreatedate() { return createdate; } public void setCreatedate(String createdate) { this.createdate = createdate; } public String getCdate() { return cdate; } public void setCdate(String cdate) { this.cdate = cdate; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } public String getOrgid1() { return orgid1; } public void setOrgid1(String orgid1) { this.orgid1 = orgid1; } public String getAdvice() { return advice; } public void setAdvice(String advice) { this.advice = advice; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getDel() { return del; } public void setDel(String del) { this.del = del; } public String getEnname() { return enname; } public void setEnname(String enname) { this.enname = enname; } public String getSafe() { return safe; } public void setSafe(String safe) { this.safe = safe; } public String getRenew() { return renew; } public void setRenew(String renew) { this.renew = renew; } public String getZpreport() { return zpreport; } public void setZpreport(String zpreport) { this.zpreport = zpreport; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getLegalp() { return legalp; } public void setLegalp(String legalp) { this.legalp = legalp; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBustype() { return bustype; } public void setBustype(String bustype) { this.bustype = bustype; } public String getResp() { return resp; } public void setResp(String resp) { this.resp = resp; } public String getRespdate_review() { return respdate_review; } public void setRespdate_review(String respdate_review) { this.respdate_review = respdate_review; } public String getType2() { return type2; } public void setType2(String type2) { this.type2 = type2; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public String getAdvice_review() { return advice_review; } public void setAdvice_review(String advice_review) { this.advice_review = advice_review; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getQual() { return qual; } public void setQual(String qual) { this.qual = qual; } public String getAdminmot() { return adminmot; } public void setAdminmot(String adminmot) { this.adminmot = adminmot; } public String getResp_review() { return resp_review; } public void setResp_review(String resp_review) { this.resp_review = resp_review; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getRespdate() { return respdate; } public void setRespdate(String respdate) { this.respdate = respdate; } public String getOrgid() { return orgid; } public void setOrgid(String orgid) { this.orgid = orgid; } public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getApplytype() { return applytype; } public void setApplytype(String applytype) { this.applytype = applytype; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getZpscore() { return zpscore; } public void setZpscore(String zpscore) { this.zpscore = zpscore; } public String getCertnumber() { return certnumber; } public void setCertnumber(String certnumber) { this.certnumber = certnumber; } public String getFzdate() { return fzdate; } public void setFzdate(String fzdate) { this.fzdate = fzdate; } public String getCerttype() { return certtype; } public void setCerttype(String certtype) { this.certtype = certtype; } public String getCertstatus() { return certstatus; } public void setCertstatus(String certstatus) { this.certstatus = certstatus; } public String getReason() { return reason; } public void setReason(String reason) { this.reason = reason; } public String getStopdate() { return stopdate; } public void setStopdate(String stopdate) { this.stopdate = stopdate; } }
true
00d2368764b5ad9d1dfe29075d1ff9408ad55bcf
Java
gubartz/pdm2018
/Licao06-Dagger/E06.01-Solucao-Introducao/app/src/main/java/br/edu/ifsp/hto/viewmodel/repositories/ListaEsperaRepository.java
UTF-8
1,894
2.359375
2
[]
no_license
package br.edu.ifsp.hto.viewmodel.repositories; import android.arch.lifecycle.LiveData; import java.util.List; import javax.inject.Inject; import br.edu.ifsp.hto.viewmodel.database.ListaEsperaDAO; import br.edu.ifsp.hto.viewmodel.entities.ListaEspera; import br.edu.ifsp.hto.viewmodel.utilities.AppExecutors; public class ListaEsperaRepository { //TODO(20) Trocar o atributo de classe de AppDatabase para um ListaEsperaDAO // private AppDatabase mDb; ListaEsperaDAO mListaEsperaDAO; //TODO(21) Trocar o construtor para receber um ListaEsperaDAO //TODO(22) Utilizar a annotation Inject no construtor @Inject public ListaEsperaRepository(ListaEsperaDAO listaEsperaDAO) { //TODO(23) Atribuir o parâmetro do construtor para o atributo de classe mListaEsperaDAO = listaEsperaDAO; } //TODO(24) Trocar todos os métodos para usar o atributo de classe ListaEsperaDAO public LiveData<List<ListaEspera>> getAllListaEspera(){ return mListaEsperaDAO.loadAllListaEspera(); } public void addListaEspera(final ListaEspera listaEspera){ AppExecutors.getInstance().diskIO().execute(new Runnable() { @Override public void run() { mListaEsperaDAO.insertListaEspera(listaEspera); } }); } public void removeListaEspera(final ListaEspera listaEspera){ AppExecutors.getInstance().diskIO().execute(new Runnable() { @Override public void run() { mListaEsperaDAO.deleteListaEspera(listaEspera); } }); } public void updateListaEspera(final ListaEspera listaEspera){ AppExecutors.getInstance().diskIO().execute(new Runnable() { @Override public void run() { mListaEsperaDAO.updateListaEspera(listaEspera); } }); } }
true
57b92ef3a9d2366005954a0f474fde0ec1eaa383
Java
aws404/Image2Map
/src/main/java/space/essem/image2map/Image2Map.java
UTF-8
8,563
1.859375
2
[ "MIT" ]
permissive
package space.essem.image2map; import com.mojang.brigadier.Command; import com.mojang.brigadier.LiteralMessage; import com.mojang.brigadier.arguments.IntegerArgumentType; import com.mojang.brigadier.arguments.StringArgumentType; import com.mojang.brigadier.builder.ArgumentBuilder; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import com.mojang.brigadier.suggestion.SuggestionProvider; import me.shedaniel.autoconfig.AutoConfig; import me.shedaniel.autoconfig.serializer.GsonConfigSerializer; import net.fabricmc.api.ModInitializer; import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback; import net.minecraft.command.CommandSource; import net.minecraft.command.suggestion.SuggestionProviders; import net.minecraft.entity.ItemEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.FilledMapItem; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NbtCompound; import net.minecraft.nbt.NbtInt; import net.minecraft.nbt.NbtList; import net.minecraft.nbt.NbtString; import net.minecraft.server.command.CommandManager; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.LiteralText; import net.minecraft.text.Style; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import net.minecraft.util.Identifier; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import space.essem.image2map.config.Image2MapConfig; import space.essem.image2map.renderer.MapRenderer; import java.awt.image.BufferedImage; import java.util.Arrays; import java.util.function.UnaryOperator; public class Image2Map implements ModInitializer { public static final Logger LOGGER = LogManager.getLogger(); public static Image2MapConfig CONFIG = AutoConfig.register(Image2MapConfig.class, GsonConfigSerializer::new) .getConfig(); @Override public void onInitialize() { LOGGER.info("Loading Image2Map..."); CommandRegistrationCallback.EVENT.register((dispatcher, _dedicated) -> { dispatcher.register( CommandManager.literal("mapcreate").requires(source -> source.hasPermissionLevel(CONFIG.minPermLevel)) .then(CommandManager.argument("path", StringArgumentType.greedyString()) .executes(ctx -> createMaps(MapGenerationContext.getBasicInfo(ctx, true))))); dispatcher.register( CommandManager.literal("dithermap").requires(source -> source.hasPermissionLevel(CONFIG.minPermLevel)) .then(ditherAndPath(ctx -> createMaps(MapGenerationContext.getBasicInfo(ctx))))); dispatcher.register(CommandManager.literal("multimap") .requires(source -> source.hasPermissionLevel(CONFIG.minPermLevel)) .then(CommandManager.argument("width", IntegerArgumentType.integer(1, 25)).then(CommandManager .argument("height", IntegerArgumentType.integer(1, 25)) .then(CommandManager.argument("scale", StringArgumentType.word()).suggests(ScaleMode.getSuggestor()) .then(ditherAndPath(ctx -> createMaps( MapGenerationContext.getBasicInfo(ctx).getSize(ctx).getScaleMethod(ctx).makePoster(true)))))))); }); } private static final UnaryOperator<Style> LORE_STYLE = s -> s.withColor(Formatting.GOLD).withItalic(false); private NbtList getLore(int width, int height) { NbtList posterLore = new NbtList(); posterLore.add(NbtString.of(Text.Serializer .toJson(new LiteralText(String.format("Use me on an item frame grid at least %d by %d big", width, height)) .styled(LORE_STYLE)))); posterLore .add(NbtString.of(Text.Serializer.toJson(new LiteralText("and I'll make a big image!").styled(LORE_STYLE)))); return posterLore; } protected static ArgumentBuilder<ServerCommandSource, ?> ditherAndPath(Command<ServerCommandSource> command) { return CommandManager.argument("dither", StringArgumentType.word()).suggests(DitherMode.getSuggestor()) .then(CommandManager.argument("path", StringArgumentType.greedyString()).executes(command)); } private int createMaps(MapGenerationContext context) throws CommandSyntaxException { try { ServerCommandSource source = context.getSource(); source.sendFeedback(new LiteralText("Generating image map..."), false); BufferedImage sourceImg = ImageUtils.getImage(context.getPath(), source); if (sourceImg == null) return 0; ServerPlayerEntity player = source.getPlayer(); new Thread(() -> { BufferedImage img = ImageUtils.scaleImage(context.getScaleMode(), context.getCountX(), context.getCountY(), sourceImg); final int SECTION_SIZE = 128; NbtList maps = new NbtList(); for (int y = 0; y < context.getCountY(); y++) { NbtList mapsY = new NbtList(); for (int x = 0; x < context.getCountX(); x++) { BufferedImage subImage = img.getSubimage(x * SECTION_SIZE, y * SECTION_SIZE, SECTION_SIZE, SECTION_SIZE); ItemStack stack = createMap(source, context.getDither(), subImage); if (context.shouldMakePoster() && (context.getCountX() > 1 || context.getCountY() > 1)) { mapsY.add(NbtInt.of(FilledMapItem.getMapId(stack))); } else { givePlayerMap(player, stack); } } maps.add(mapsY); } if (context.shouldMakePoster() && (context.getCountX() > 1 || context.getCountY() > 1)) { BufferedImage posterImg = ImageUtils.scaleImage(ScaleMode.FIT, 1, 1, img); ItemStack stack = createMap(source, context.getDither(), posterImg); stack.putSubTag("i2mStoredMaps", maps); NbtCompound stackDisplay = stack.getOrCreateSubTag("display"); String path = context.getPath(); String fileName = ImageUtils.getImageName(path); if (fileName == null) fileName = path.length() < 15 ? path : "image"; stackDisplay.put("Name", NbtString.of(String.format("{\"text\":\"Poster for '%s'\",\"italic\":false}", fileName))); stackDisplay.put("Lore", getLore(context.getCountX(), context.getCountY())); givePlayerMap(player, stack); } source.sendFeedback(new LiteralText("Done!"), false); }).start(); source.sendFeedback(new LiteralText("Map Creation Queued!"), false); } catch (Exception e) { e.printStackTrace(); throw e; } return 1; } private ItemStack createMap(ServerCommandSource source, DitherMode mode, BufferedImage image) { return MapRenderer.render(image, mode, source.getWorld(), source.getPosition().x, source.getPosition().z); } private void givePlayerMap(PlayerEntity player, ItemStack stack) { if (!player.getInventory().insertStack(stack)) { ItemEntity itemEntity = new ItemEntity(player.world, player.getPos().x, player.getPos().y, player.getPos().z, stack); player.world.spawnEntity(itemEntity); } } public enum DitherMode { NONE, FLOYD; private static final SuggestionProvider<ServerCommandSource> SUGGEST_PROVIDER = SuggestionProviders.register(new Identifier("dither_mode"), (commandContext, suggestionsBuilder) -> CommandSource.suggestMatching(Arrays.stream(values()).map(ditherMode -> ditherMode.name().toLowerCase()), suggestionsBuilder)); // The default from string method doesn't quite fit my needs public static DitherMode fromString(String string) throws CommandSyntaxException { if (string.equalsIgnoreCase("NONE")) return DitherMode.NONE; else if (string.equalsIgnoreCase("DITHER") || string.equalsIgnoreCase("FLOYD")) return DitherMode.FLOYD; throw new CommandSyntaxException( new SimpleCommandExceptionType(new LiteralMessage("Invalid Dither mode '" + string + "'")), new LiteralMessage("Invalid Dither mode '" + string + "'")); } public static SuggestionProvider<ServerCommandSource> getSuggestor() { return SUGGEST_PROVIDER; } } public enum ScaleMode { FIT, FILL, STRETCH; private static final SuggestionProvider<ServerCommandSource> SUGGEST_PROVIDER = SuggestionProviders.register(new Identifier("scale_mode"), (commandContext, suggestionsBuilder) -> CommandSource.suggestMatching(Arrays.stream(values()).map(scaleMode -> scaleMode.name().toLowerCase()), suggestionsBuilder)); public static ScaleMode fromString(String sMode) { return switch (sMode.toUpperCase()) { case "FIT" -> FIT; case "FILL" -> FILL; case "STRETCH" -> STRETCH; default -> throw new IllegalArgumentException("input string must be a valid enum value!"); }; } public static SuggestionProvider<ServerCommandSource> getSuggestor() { return SUGGEST_PROVIDER; } } }
true
cccafa833b3aa6fc0c590f4bbb7383e1854e8dd9
Java
xgimenezs/M3Oct2
/src/main/java/com/xgim/demo4/TwitterConfig.java
UTF-8
894
2.125
2
[]
no_license
package com.xgim.demo4; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.social.twitter.api.impl.TwitterTemplate; @Configuration @PropertySource("classpath:twitter.properties") public class TwitterConfig { @Value("${api.key}") private String apiKey; @Value("${api.key.secret}") private String apiKeySecret; @Value("${access.token}") private String accessToken; @Value("${access.token.secret}") private String accessTokenSecret; @Bean public TwitterTemplate getTwitterTemplate() { TwitterTemplate twitterTemplate = new TwitterTemplate(apiKey, apiKeySecret, accessToken, accessTokenSecret); return twitterTemplate; } }
true
f1c99f5ebedef933a2141c71134119e9ca5a5a2f
Java
FirstLetterZ/compression
/compress/src/main/java/com/zpf/compress/AndroidCompressUtil.java
UTF-8
8,228
2.234375
2
[]
no_license
package com.zpf.compress; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.os.Build; import java.io.BufferedInputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; class AndroidCompressUtil { //用于兼容Android Q,以及仅能通过uri读取文件流的情况 public static int compress(InputStream sourceStream, String targetFilePath, int outWidth, int outHeight, int quality) { return compress(null, sourceStream, targetFilePath, outWidth, outHeight, quality); } public static int compress(String sourceFilePath, String targetFilePath, int outWidth, int outHeight, int quality) { return compress(sourceFilePath, null, targetFilePath, outWidth, outHeight, quality); } private static int compress(String sourceFilePath, InputStream sourceStream, String targetFilePath, int outWidth, int outHeight, int quality) { if (sourceFilePath != null) { try { sourceStream = new FileInputStream(sourceFilePath); } catch (FileNotFoundException e) { e.printStackTrace(); } } if (sourceStream == null || targetFilePath == null || quality < 0 || quality > 100) { safeClose(sourceStream); return CompressErrorCode.ERROR_CHECK_OPTION; } try { if (!(sourceStream instanceof BufferedInputStream)) { sourceStream = new BufferedInputStream(sourceStream); } sourceStream.mark(sourceStream.available()); } catch (Exception e) { return CompressErrorCode.ERROR_CHECK_OPTION; } BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; options.inSampleSize = 1; try { BitmapFactory.decodeStream(sourceStream, null, options); } catch (Exception e) { safeClose(sourceStream); return CompressErrorCode.ERROR_READ_FILE; } options.inJustDecodeBounds = false; int originalWidth = options.outWidth; int originalHeight = options.outHeight; if (outHeight <= 0) { outHeight = originalHeight; } if (outWidth <= 0) { outWidth = originalWidth; } if (outWidth <= 0 || outHeight <= 0) { safeClose(sourceStream); return CompressErrorCode.ERROR_CHECK_OPTION; } options.inSampleSize = computeSize(outWidth, outHeight); Bitmap sourceBitmap = null; try { sourceStream.reset(); sourceBitmap = BitmapFactory.decodeStream(sourceStream, null, options); } catch (Exception e) { // } if (sourceBitmap == null) { safeClose(sourceStream); return CompressErrorCode.ERROR_READ_FILE; } int picDegree = 0; if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { picDegree = readPictureDegree(sourceStream); } else if (sourceFilePath != null) { picDegree = readPictureDegree(sourceFilePath); } if (picDegree != 0) { sourceBitmap = rotatingImage(sourceBitmap, picDegree); } File targetFile = new File(targetFilePath); File targetParent = targetFile.getParentFile(); if (targetParent != null && !targetParent.exists()) { targetParent.mkdirs(); } Bitmap.CompressFormat format = null; if (options.outMimeType != null) { if (options.outMimeType.endsWith("png")) { format = Bitmap.CompressFormat.PNG; } else if (options.outMimeType.endsWith("webp")) { format = Bitmap.CompressFormat.WEBP; } else if (options.outMimeType.endsWith("jpg") || options.outMimeType.endsWith("jpeg")) { format = Bitmap.CompressFormat.JPEG; } } if (format == null && sourceFilePath != null) { try { sourceStream.reset(); int typeCode = FileTypeUtil.readFileType(sourceStream); if (FileType.PNG == typeCode) { format = Bitmap.CompressFormat.PNG; } else if (FileType.WEBP == typeCode) { format = Bitmap.CompressFormat.WEBP; } else { format = Bitmap.CompressFormat.JPEG; } } catch (IOException ignore) { // } } if (format == null) { format = Bitmap.CompressFormat.JPEG; } if (format != Bitmap.CompressFormat.PNG) { options.inPreferredConfig = Bitmap.Config.RGB_565; } try (FileOutputStream fos = new FileOutputStream(targetFilePath)) { sourceBitmap.compress(format, quality, fos); fos.flush(); } catch (IOException e) { e.printStackTrace(); return CompressErrorCode.ERROR_WHITE_FILE; } finally { safeClose(sourceStream); sourceBitmap.recycle(); } return CompressErrorCode.SUCCESS_ANDROID; } private static int readPictureDegree(InputStream inputStream) { int degree = 0; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { try { ExifInterface exifInterface = new ExifInterface(inputStream); degree = getDegree(exifInterface); } catch (Exception e) { e.printStackTrace(); } } return degree; } private static int readPictureDegree(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); degree = getDegree(exifInterface); } catch (Exception e) { e.printStackTrace(); } return degree; } private static int getDegree(ExifInterface exifInterface) { int degree = 0; int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } return degree; } private static void safeClose(Closeable closeable) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { // } } } //使用了开源库luban的算法 private static int computeSize(int width, int height) { width = width % 2 == 1 ? width + 1 : width; height = height % 2 == 1 ? height + 1 : height; int longSide = Math.max(width, height); int shortSide = Math.min(width, height); float scale = ((float) shortSide / longSide); if (scale <= 1 && scale > 0.5625) { if (longSide < 1664) { return 1; } else if (longSide < 4990) { return 2; } else if (longSide > 4990 && longSide < 10240) { return 4; } else { return longSide / 1280; } } else if (scale <= 0.5625 && scale > 0.5) { return longSide / 1280 == 0 ? 1 : longSide / 1280; } else { return (int) Math.ceil(longSide / (1280.0 / scale)); } } private static Bitmap rotatingImage(Bitmap bitmap, int angle) { Matrix matrix = new Matrix(); matrix.postRotate(angle); return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } }
true
a9b44476becbf45409bc56888139a980294a8344
Java
zhoutiancheng77/dzfui
/zxkj-modules/zxkj-app/src/main/java/com/dzf/zxkj/app/model/sys/AppMemberVO.java
UTF-8
1,000
1.726563
2
[]
no_license
package com.dzf.zxkj.app.model.sys; import java.io.Serializable; /** * 接手人信息 * @author zy * */ public class AppMemberVO implements Serializable{ private static final long serialVersionUID = 4077018980376224832L; private String id; private String username; private String avatar; private String pk_corp;//所属公司主键 private String corpname;//所属公司名称 public String getPk_corp() { return pk_corp; } public void setPk_corp(String pk_corp) { this.pk_corp = pk_corp; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getCorpname() { return corpname; } public void setCorpname(String corpname) { this.corpname = corpname; } }
true
28d1e1dbd4f5083794c0819c0b814d145ef6fd56
Java
takhir-nafikov/AndroidArchitecture
/AAC/src/main/java/com/example/aac/database/TaskDatabase.java
UTF-8
705
2.234375
2
[]
no_license
package com.example.aac.database; import android.arch.persistence.room.Database; import android.arch.persistence.room.Room; import android.arch.persistence.room.RoomDatabase; import android.content.Context; @Database(entities = TaskModel.class, version = 1) public abstract class TaskDatabase extends RoomDatabase { private static TaskDatabase INSTANCE; public static TaskDatabase getDatabase(Context context){ if(INSTANCE == null){ INSTANCE = Room.databaseBuilder(context.getApplicationContext(), TaskDatabase.class, "task_db") .build(); } return INSTANCE; } public abstract TaskModelDao taskModelDao(); }
true
6f282286e31335c9885ac0b6e1bb7438456203d8
Java
lqleon1214/IPC-example
/app/src/main/java/com/example/qing/myapplication/data/KeyValContract.java
UTF-8
1,942
2.171875
2
[]
no_license
package com.example.qing.myapplication.data; import android.content.ContentResolver; import android.net.Uri; import android.provider.BaseColumns; /** * Created by qing on 16/8/29. */ public final class KeyValContract { private KeyValContract(){} public static final int VERSION = 1; public static final String AUTHORITY = "com.enterpriseandroid.database.keyval"; private static final Uri URI_BASE = new Uri.Builder().scheme(ContentResolver.SCHEME_CONTENT).authority(AUTHORITY).build(); public static final String TABLE_VALS = "vals"; public static final Uri URI_VALS = URI_BASE.buildUpon().appendPath(TABLE_VALS).build(); public static final String TYPE_VALS = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.com.enterpriseandroid.database.val"; public static final String TYPE_VAL = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.com.enterpriseandroid.database.val"; public static final String TABLE_KEYVAL = "keyval"; public static final Uri URI_KEYVAL = URI_BASE.buildUpon().appendPath(TABLE_KEYVAL).build(); public static final String TYPE_KEYVALS = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.com.enterpriseandroid.database.keyval"; public static final String TYPE_KEYVAL = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.com.enterpriseandroid.database.keyval"; public static final class Columns { private Columns(){} // columns in both tables public static final String ID = BaseColumns._ID; public static final String VAL = "val"; public static final String EXTRA = "extra"; // columns only in the keyval table public static final String KEY = "key"; } public static final class Permission { private Permission() {} public static final String READ = "com.enterpriseandroid.database.keyval.READ"; public static final String WRITE = "com.enterpriseandroid.database.keyval.WRITE"; } }
true
6267c47fa0a3f23fb343e19f2818c9693075be39
Java
hyogij/Algorithm
/practice/Sol63.maximalRectangle/src/Solution.java
UTF-8
2,307
3.453125
3
[]
no_license
import java.util.Arrays; import java.util.Stack; /* ========================================================== Author : Hyogi Jung(hyogij@gmail.com) Date : 2016.03.22 Problem : https://leetcode.com/problems/maximal-rectangle/ ========================================================== */ public class Solution { /* * Given a 2D binary matrix filled with 0's and 1's, find the largest * rectangle containing all ones and return its area. */ public static void main(String[] args) { char[][] matrix1 = {{'0', '1', '0', '0', '0'}, {'0', '1', '0', '1', '0'}, {'1', '1', '1', '1', '0'}, {'1', '1', '1', '1', '0'}, {'0', '1', '1', '0', '1'}}; System.out.println("largestRectangleArea " + maximalRectangle(matrix1)); char[][] matrix2 = {{'0', '0', '0', '0', '0'}, {'0', '0', '0', '0', '0'}, {'0', '0', '1', '1', '0'}, {'0', '0', '1', '1', '0'}, {'0', '0', '1', '1', '0'}}; System.out.println("largestRectangleArea " + maximalRectangle(matrix2)); } public static int maximalRectangle(char[][] matrix) { int max = 0; if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return max; int[] area = new int[matrix[0].length]; for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[row].length; col++) { if (row == 0) { if (matrix[row][col] == '0') area[col] = 0; else area[col] = 1; } else { if (matrix[row][col] == '0') area[col] = 0; else area[col]++; } } max = Math.max(max, largestRectangleArea(area)); } return max; } public static int largestRectangleArea(int[] heights) { int max = 0, area = 0, top = 0, height = 0; if (heights == null || heights.length == 0) return max; Stack<Integer> stack = new Stack<Integer>(); for (int i = 0; i <= heights.length;) { if (i == heights.length) height = 0; else height = heights[i]; if (stack.isEmpty() == true || heights[stack.peek()] <= height) { stack.push(i++); continue; } while (stack.isEmpty() != true && heights[stack.peek()] > height) { top = stack.pop(); // Calculate area if (stack.isEmpty()) { area = heights[top] * i; } else { area = heights[top] * (i - stack.peek() - 1); } max = Math.max(area, max); } } return max; } }
true
590da1c7e81bba7e3fe2cd41380b77b0d62169e9
Java
Jhan/PROY108072012
/src/main/java/com/eomasoft/sermeden/domain/Person.java
UTF-8
856
2.421875
2
[]
no_license
package com.eomasoft.sermeden.domain; import java.io.Serializable; @SuppressWarnings("serial") public class Person implements Serializable { private Long id; private String dni; private String name; private String lastname; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getDni() { return dni; } public void setDni(String dni) { this.dni = dni; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } @Override public String toString() { return "Person [id=" + id + ", dni=" + dni + ", name=" + name + ", lastname=" + lastname + "]"; } }
true
392444627325e1bbfa6e9d1b451ebe724c5dce28
Java
binlei/mobile
/mobile/.svn/pristine/1b/1bcdfa2f512f722d7f769bc79d665b26dbd3d9f7.svn-base
UTF-8
2,262
2.3125
2
[]
no_license
/** * Copyright©2014 www.jshuabo.com. all rights reserved. * * @Title: MobileDataProcessQuartz.java * @Prject: mobile * @Package: com.jshuabo.mobile.server.quartz.mobile * @author: lianghe.yuan * @date: Apr 29, 2014 2:23:41 PM * @version: * @Description: */ package com.jshuabo.mobile.server.quartz.mobile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import com.jshuabo.mobile.server.service.mobile.IMobileDataProcessService; /** * @ClassName: MobileDataProcessQuartz * @Description: * @author: lianghe.yuan * @date: Apr 29, 2014 2:23:41 PM */ public class MobileDataProcessQuartz { Logger logger = LoggerFactory.getLogger(MobileDataProcessQuartz.class); @Autowired private IMobileDataProcessService mobileDataProcessService; /** * @Title: process * @Description: 整理接口数据 * @return: void */ public void process() { try { mobileDataProcessService.process(); } catch (Exception ex) { logger.error("process mobile data error: {}", ex.getLocalizedMessage()); } } /** * @Title: processAppUsage * @Description: 统计app使用 * @return: void */ public void processAppUsage() { try { mobileDataProcessService.processAppUsage(); } catch (Exception ex) { logger.error("process mobile appusage error: {}", ex.getLocalizedMessage()); } } /** * @Title: processDeleteOldRecord * @Description: 删除原表数据 * @return: void */ public void processDeleteOldRecord() { try { mobileDataProcessService.processDeleteOldRecord(); } catch (Exception ex) { logger.error("process mobile appusage error: {}", ex.getLocalizedMessage()); } } /** * @Title: updateChannel * @Description: 更新渠道(extendPro4、extendPro5) * @return: void */ public void updateChannel() { try { mobileDataProcessService.updateChannel(); } catch (Exception e) { logger.error("process update channel error: {}", e.getLocalizedMessage()); } } }
true
76101edcdd54816eee580309c114dfb07969e562
Java
Saikrish572835/saikrish
/AdminLoginController.java
UTF-8
4,855
2.15625
2
[]
no_license
package com.cts.lch.controller; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; 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.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; import com.cts.lch.form.ChangePasswordForm; import com.cts.lch.form.LoginForm; import com.cts.lch.marketplace.model.Admin; import com.cts.lch.marketplace.service.AdminService; @Controller @SessionAttributes("admin") public class AdminLoginController { private static final Logger LOGGER = Logger.getLogger(AdminLoginController.class); private AdminService adminService; @Autowired(required=true) @Qualifier(value="adminService") public void setAdminService(AdminService adminService) { this.adminService = adminService; } @RequestMapping(value = "/ShowLogin", method = RequestMethod.GET) public String showLogin() { LOGGER.info("Start"); return "ShowLogin"; } @RequestMapping(value = "/ShowChangePassword", method = RequestMethod.GET) public String showChangePassword() { LOGGER.info("Start"); return "ShowChangePassword"; } @RequestMapping(value = "/AdminLogin", method=RequestMethod.POST) public ModelAndView login(@ModelAttribute LoginForm loginForm) { LOGGER.info("Start"); ModelAndView model = new ModelAndView(); int associateId = loginForm.getAssociateId(); LOGGER.debug(associateId); Admin admin = adminService.authenticate(associateId, loginForm.getPassword()); if (admin != null) { model.addObject("admin", admin); if (admin.getAdTempPwdExpires() != null) { LOGGER.debug("Change default password."); model.setViewName("ShowChangePassword"); model.addObject("associateId", associateId); } else { model.setViewName(resolveView(admin.getAdRole())); } LOGGER.debug("Login successful."); } else { model.addObject("errorMessage", "Invalid Associate ID or Password"); model.setViewName("ShowLogin"); LOGGER.debug("Login failed."); } //model.setViewName("ShowLogin"); LOGGER.info("End"); return model; } @RequestMapping(value = "/ChangePassword", method=RequestMethod.POST) public ModelAndView changePassword(@ModelAttribute ChangePasswordForm changePasswordForm) { LOGGER.info("Start"); ModelAndView model = new ModelAndView(); int associateId = changePasswordForm.getAssociateId(); if (!changePasswordForm.getNewPassword().equals(changePasswordForm.getConfirmPassword())) { model.addObject("errorMessage", "New Password and Confirm Password does not match"); model.addObject("associateId", associateId); model.setViewName("ShowChangePassword"); return model; } LOGGER.debug("associateId: " + associateId); Admin admin = adminService.authenticate(associateId, changePasswordForm.getCurrentPassword()); if (admin == null) { model.addObject("errorMessage", "Invalid Associate Id or Password."); model.addObject("associateId", associateId); model.setViewName("ShowChangePassword"); return model; } admin.setAdPassword(changePasswordForm.getNewPassword()); admin.setAdTempPwdExpires(null); adminService.updateAdmin(admin); model.addObject("message", "Password changed successfully. Please login with new password."); model.setViewName("ShowLogin"); LOGGER.info("End"); return model; } private String resolveView(String role) { LOGGER.info("Start"); LOGGER.debug("Role: " + role); String view = null; switch (role) { case "AD": view = "AppAdminHome"; break; case "PL": view = "BuAdminHome"; break; case "SOL": view = "SolutionTeamHome"; break; case "GWFM": view = "GWFMHome"; break; case "VMO": view = "VmoUserHome"; break; } LOGGER.debug("View: " + view); return view; } }
true
8f8655cda7eca137938e4dda56d5c7ebcd3a8446
Java
iig-uni-freiburg/SWAT20
/src/de/uni/freiburg/iig/telematik/swat/workbench/SwatTreeView.java
UTF-8
14,825
1.773438
2
[ "BSD-3-Clause" ]
permissive
package de.uni.freiburg.iig.telematik.swat.workbench; import de.uni.freiburg.iig.telematik.swat.workbench.components.SwatComponentType; import de.uni.freiburg.iig.telematik.swat.workbench.components.SwatComponents; import java.awt.Color; import java.awt.Component; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; import javax.swing.BorderFactory; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import de.invation.code.toval.graphic.dialog.ExceptionDialog; import de.invation.code.toval.misc.wd.ComponentListener; import de.invation.code.toval.misc.wd.ProjectComponentException; import de.uni.freiburg.iig.telematik.sepia.graphic.AbstractGraphicalPN; import de.uni.freiburg.iig.telematik.sewol.log.LogView; import de.uni.freiburg.iig.telematik.sewol.log.filter.AbstractLogFilter; import de.uni.freiburg.iig.telematik.swat.analysis.Analysis; import de.uni.freiburg.iig.telematik.swat.logs.LogModel; import de.uni.freiburg.iig.telematik.swat.workbench.dialog.SwatTreePopupMenu; import de.uni.freiburg.iig.telematik.swat.workbench.dialog.SwatTreePopupMenuFilter; import de.uni.freiburg.iig.telematik.swat.workbench.dialog.SwatTreePopupMenuLog; import de.uni.freiburg.iig.telematik.swat.workbench.dialog.SwatTreePopupMenuView; import de.uni.freiburg.iig.telematik.swat.workbench.listener.SwatStateListener; import de.uni.freiburg.iig.telematik.swat.workbench.listener.SwatTreeViewListener; import de.uni.freiburg.iig.telematik.wolfgang.editor.component.ViewComponent; import java.util.Collections; import java.util.Iterator; import java.util.List; import javax.swing.SwingUtilities; import javax.swing.tree.TreePath; public class SwatTreeView extends JTree implements SwatStateListener, ComponentListener { private static final String PN_HEADING = "Petri nets"; private static final String LOGS_HEADING = "Process Logs"; private static final String CONTEXTS_HEADING = "Execution Contexts"; private static final String ACMODELS_HEADING = "Access Control Models"; private static final Color DEFAULT_BG_COLOR = UIManager.getColor("Panel.background"); private final DefaultTreeModel defaultTreeModel; private final Set<SwatTreeViewListener> listeners = new HashSet<>(); private static SwatTreeView instance = null; private final DefaultMutableTreeNode rootNode; private DefaultMutableTreeNode petriNetNode = null; private DefaultMutableTreeNode logsNode = null; private DefaultMutableTreeNode acModelsNode = null; private DefaultMutableTreeNode contextsNode = null; private SwatTreeView() throws Exception { rootNode = new DefaultMutableTreeNode("Working Directory"); defaultTreeModel = new DefaultTreeModel(rootNode); this.setBackground(DEFAULT_BG_COLOR); this.setModel(defaultTreeModel); this.setShowsRootHandles(true); this.setEditable(false); setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); buildTree(); setToggleClickCount(0);//prevent collapse on double click // this.setSelectionInterval(0,0); addMouseListener(new TreeViewMouseAdapter()); SwatComponents.getInstance().addComponentListener(this); SwatComponents.getInstance().getContainerAristaflowLogs().addComponentListener(this); SwatComponents.getInstance().getContainerMXMLLogs().addComponentListener(this); SwatComponents.getInstance().getContainerXESLogs().addComponentListener(this); SwatComponents.getInstance().getContainerPetriNets().addComponentListener(this); SwatComponents.getInstance().getContainerLogViews().addComponentListener(this); } public static SwatTreeView getInstance() throws Exception { if (instance == null) { instance = new SwatTreeView(); } return instance; } public void removeAndUpdateSwatComponents() throws ProjectComponentException { rootNode.removeAllChildren(); buildTree(); defaultTreeModel.reload(); expandAll(); repaint(); } @SuppressWarnings("rawtypes") private void buildTree() throws ProjectComponentException { rootNode.removeAllChildren(); // Petri Nets if (SwatComponents.getInstance().containsPetriNets()) { petriNetNode = new DefaultMutableTreeNode(PN_HEADING); rootNode.add(petriNetNode); for (AbstractGraphicalPN petriNet : SwatComponents.getInstance().getContainerPetriNets().getComponentsSorted()) { SwatTreeNode node = new SwatTreeNode(petriNet, SwatComponentType.PETRI_NET); for (Analysis analysis : SwatComponents.getInstance().getContainerPetriNets().getContainerAnalysis(node.getDisplayName()).getComponents()) { node.add(new SwatTreeNode(analysis, SwatComponentType.PETRI_NET_ANALYSIS)); } petriNetNode.add(node); } } // Logs if (SwatComponents.getInstance().containsLogs()) { logsNode = new DefaultMutableTreeNode(LOGS_HEADING); rootNode.add(logsNode); // Logs List<LogModel> logFiles = SwatComponents.getInstance().getLogs(); Collections.sort(logFiles); for (LogModel logModel : logFiles) { SwatComponentType logType = null; switch (logModel.getType()) { case Aristaflow: logType = SwatComponentType.ARISTAFLOW_LOG; break; case MXML: logType = SwatComponentType.MXML_LOG; break; case XES: logType = SwatComponentType.XES_LOG; break; } final DefaultMutableTreeNode logNode = new SwatTreeNode(logModel, logType); for (LogView view : logModel.getLogViews()) { SwatTreeNode viewNode = new SwatTreeNode(view, SwatComponentType.LOG_VIEW); // list filters Iterator<AbstractLogFilter> filterIterator = view.getFilters().iterator(); while (filterIterator.hasNext()) { AbstractLogFilter filter = filterIterator.next(); viewNode.add(new SwatTreeFilterNode(filter, viewNode)); } logNode.add(viewNode); } logsNode.add(logNode); } } if (SwatComponents.getInstance().containsProcessContexts()) { contextsNode = new DefaultMutableTreeNode(CONTEXTS_HEADING); rootNode.add(contextsNode); } if (SwatComponents.getInstance().containsACModels()) { acModelsNode = new DefaultMutableTreeNode(ACMODELS_HEADING); rootNode.add(acModelsNode); } expandAll(); validate(); repaint(); } public void expandAll() { try { for (int i = 0; i < getRowCount(); i++) { expandRow(i); } } catch (Exception e) { } } @Override public void operatingModeChanged() { } public void addTreeViewListener(SwatTreeViewListener listener) { listeners.add(listener); } private void notifyComponentSelected(SwatTreeNode node) { for (SwatTreeViewListener listener : listeners) { listener.componentSelected(node); } } private void notifyComponentActivated(SwatTreeNode node) { for (SwatTreeViewListener listener : listeners) { listener.componentActivated(node); } } @SuppressWarnings("unchecked") public SwatTreeNode getComponent(ViewComponent component) { Enumeration<SwatTreeNode> children = rootNode.children(); while (children.hasMoreElements()) { SwatTreeNode node = children.nextElement(); if (node.getUserObject().equals(component)) { return node; } } return null; } private class TreeViewMouseAdapter extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { if (!(e.getSource() instanceof SwatTreeView)) { return; } if (getSelectionPath() == null) { return; } Object selectedNode = getSelectionPath().getLastPathComponent(); if (selectedNode == null) { return; } if (!((selectedNode instanceof SwatTreeNode) || (selectedNode instanceof SwatTreeFilterNode))) { return; } SwatTreeNode swatNode = (SwatTreeNode) selectedNode; if (e.getClickCount() == 1) { if (e.isPopupTrigger()) { // Right click on tree node showPopup(e); } else { // Left click on tree node notifyComponentSelected(swatNode); } } else if (e.getClickCount() == 2 && e.getButton() == 1 && !e.isPopupTrigger() && !(swatNode instanceof SwatTreeFilterNode)) { // Double click on tree node notifyComponentActivated(swatNode); } } @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { showPopup(e); } } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { showPopup(e); } } private void showPopup(MouseEvent e) { int selRow = getRowForLocation(e.getX(), e.getY()); TreePath selPath = getPathForLocation(e.getX(), e.getY()); setSelectionPath(selPath); if (selRow > -1) { setSelectionRow(selRow); } if (getSelectionPath() == null) { return; } Object selectedNode = getSelectionPath().getLastPathComponent(); if (selectedNode instanceof SwatTreeFilterNode) { SwatTreeFilterNode treeNode = (SwatTreeFilterNode) selectedNode; SwatTreePopupMenuFilter menu = new SwatTreePopupMenuFilter(treeNode); menu.show((Component) e.getSource(), e.getX(), e.getY()); } else if (selectedNode instanceof SwatTreeNode) { SwatTreeNode swatNode = (SwatTreeNode) selectedNode; SwatTreePopupMenu menu; if (swatNode.getObjectType() == SwatComponentType.ARISTAFLOW_LOG || swatNode.getObjectType() == SwatComponentType.MXML_LOG || swatNode.getObjectType() == SwatComponentType.XES_LOG) { menu = new SwatTreePopupMenuLog(swatNode); } else if (swatNode.getObjectType() == SwatComponentType.LOG_VIEW) { menu = new SwatTreePopupMenuView(swatNode); } else { menu = new SwatTreePopupMenu(swatNode); } menu.show((Component) e.getSource(), e.getX(), e.getY()); } } } @Override public void componentsChanged() { try { buildTree(); defaultTreeModel.reload(); expandAll(); repaint(); } catch (Exception e) { ExceptionDialog.showException(SwingUtilities.getWindowAncestor(SwatTreeView.this), "Tree View Exception", new Exception("Exception while building tree"), true, true); } } @Override public void componentAdded(Object component) throws ProjectComponentException { buildTree(); } @Override public void componentRemoved(Object component) throws ProjectComponentException { buildTree(); } @Override public void componentRenamed(Object component, String oldName, String newName) throws ProjectComponentException { buildTree(); } }
true
07e7dc3b24e9b88dc61fb7579acc04d3903c61a5
Java
aysegulbulur/courier_company
/com.project.courierCompany/com.project.courierCompany/com.project.courierCompany/src/main/java/com/courierCompany/com/project/courierCompany/MessageController.java
UTF-8
1,168
2.5625
3
[]
no_license
package com.courierCompany.com.project.courierCompany; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; /** * Date : 2021-05-04 * * @author AysegulBulur * @version 1.0 */ @Controller public class MessageController { /* * Data is received with @Controller. * @GetMapping is used to map HTTP GET requests. ---> welcome page * The welcome method provides the communication of data between the web page and the backend. * @return welcome presents the data (model) in the view welcome.jsp. * Logger is used for logging. Outputs are given according to the logs created. * */ Logger logger = LoggerFactory.getLogger(MessageController.class); /** * @param model : Uses the model class * @return Return the Operations.jsp page */ @GetMapping("/Operations") // .../Operations When a request is sent to the url, the welcome function will run. public String welcome(Model model){ model.addAttribute("message", "Welcome"); return "Operations"; //Returns Operations view } }
true
ee55fdeafc6eddc4bce8524016135a1cb4f7e77c
Java
pinottisamuel/controle-jdbc
/src/br/com/jdbc/entities/Produto.java
UTF-8
919
2.6875
3
[]
no_license
package br.com.jdbc.entities; import java.math.BigDecimal; import java.util.Calendar; public class Produto { private Integer id; private String nome; private BigDecimal valor; private Calendar dataCadastro; private String observacao; public Produto(String nome, BigDecimal valor, String observacao) { super(); this.nome = nome; this.valor = valor; this.observacao = observacao; } public Integer getId() { return id; } public String getObservacao() { return observacao; } public String getNome() { return nome; } public BigDecimal getValor() { return valor; } public Calendar getDataCadastro() { return dataCadastro; } @Override public String toString() { return String.format("[produto: %d %s]", id, nome); } public void setId(Integer id) { this.id = id; } public void setDataCadastro(Calendar dtCadastro) { this.dataCadastro = dtCadastro; } }
true
56d7a0b99582ae2f1a97bb52fb2d9a2e019813ad
Java
STAMP-project/dspot-experiments
/benchmark/training/org/hibernate/test/annotations/uniqueconstraint/UniqueConstraintBatchingTest.java
UTF-8
2,610
1.945313
2
[]
no_license
/** * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.test.annotations.uniqueconstraint; import javax.persistence.PersistenceException; import org.hibernate.dialect.H2Dialect; import org.hibernate.engine.jdbc.spi.SqlExceptionHelper; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.jpa.test.BaseEntityManagerFunctionalTestCase; import org.hibernate.testing.RequiresDialect; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.logger.LoggerInspectionRule; import org.hibernate.testing.logger.Triggerable; import org.hibernate.testing.transaction.TransactionUtil; import org.jboss.logging.Logger; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; /** * * * @author Vlad Mihalcea */ @TestForIssue(jiraKey = "HHH-12688") @RequiresDialect(H2Dialect.class) public class UniqueConstraintBatchingTest extends BaseEntityManagerFunctionalTestCase { @Rule public LoggerInspectionRule logInspection = new LoggerInspectionRule(Logger.getMessageLogger(CoreMessageLogger.class, SqlExceptionHelper.class.getName())); private Triggerable triggerable; @Test public void testBatching() throws Exception { Room livingRoom = new Room(); TransactionUtil.doInJPA(this::entityManagerFactory, ( entityManager) -> { livingRoom.setId(1L); livingRoom.setName("livingRoom"); entityManager.persist(livingRoom); }); TransactionUtil.doInJPA(this::entityManagerFactory, ( entityManager) -> { House house = new House(); house.setId(1L); house.setCost(100); house.setHeight(1000L); house.setRoom(livingRoom); entityManager.persist(house); }); try { TransactionUtil.doInJPA(this::entityManagerFactory, ( entityManager) -> { House house2 = new House(); house2.setId(2L); house2.setCost(100); house2.setHeight(1001L); house2.setRoom(livingRoom); entityManager.persist(house2); }); Assert.fail("Should throw exception"); } catch (PersistenceException e) { Assert.assertEquals(1, triggerable.triggerMessages().size()); Assert.assertTrue(triggerable.triggerMessage().startsWith("Unique index or primary key violation")); } } }
true
4931aa49bff5435c9a0665e3c0e20ae4ef965fbd
Java
Tmin10/bin2img
/src/Bin2img.java
UTF-8
5,767
2.546875
3
[]
no_license
import javax.imageio.ImageIO; import com.objectplanet.image.PngEncoder; import java.awt.*; import java.awt.image.BufferedImage; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Bin2img { private byte[] file; private String filename; private String outFilename = null; private boolean color = true; private boolean background = false; private boolean circle = false; private boolean lowColors = false; private int width = 300; public Bin2img (String filename) { this.filename = filename; Path path = Paths.get(filename); try { file = Files.readAllBytes(path); } catch (IOException e) { e.printStackTrace(); } } public void toPNG () { int cHeight, cWidth; if (this.circle) { cHeight = (int) Math.sqrt(getPixelsCount())+2; cWidth = (int) Math.sqrt(getPixelsCount())+2; } else { //TODO round up cHeight = (int) this.getPixelsCount()/this.width; if (this.getPixelsCount()%500 > 0) { cHeight++; } cWidth = this.width; } BufferedImage bi = new BufferedImage(cWidth, cHeight, BufferedImage.TYPE_INT_RGB); if (this.background) { Graphics2D ig2 = bi.createGraphics(); ig2.setBackground(Color.white); ig2.clearRect(0, 0, cWidth, cHeight); } if (this.circle) { //TODO round up int x = Math.round(cHeight/2); int y = x; int direction = 1; //1-right 2-down 3-left 4-up int incriment = 1; int go = 0; //steps counter for (int i = 0; i < getPixelsCount(); i++) { if ((i+1)%(getPixelsCount()/10) == 0) { System.out.print("\r"+(((i+1)*10/(getPixelsCount()/10)))+"%"); } bi.setRGB(x, y, getColorByNumber(i)); switch (direction) { case 1: x ++; if (++go >= incriment) { direction = 2; go = 0; } break; case 2: y ++; if (++go >= incriment) { direction = 3; go = 0; incriment++; } break; case 3: x--; if (++go >= incriment) { direction = 4; go = 0; } break; case 4: y--; if (++go >= incriment) { direction = 1; go = 0; incriment++; } break; } } } else { for (int i = 0; i < getPixelsCount(); i++) { if ((i+1)%(getPixelsCount()/10) == 0) { System.out.print("\r"+(((i+1)*10/(getPixelsCount()/10)))+"%"); } bi.setRGB(i%cWidth, i/cWidth, getColorByNumber(i)); } } String filename = this.filename+".png"; if (this.outFilename != null) { filename = this.outFilename; } File output_file = new File(filename); try { System.out.println(); System.out.println("Image saving..."); //ImageIO.write(bi, "PNG", output_file); BufferedOutputStream imageOutputStream = new BufferedOutputStream(new FileOutputStream(output_file)); new PngEncoder().encode(bi, imageOutputStream); imageOutputStream.close(); System.out.println("Saved to "+filename); } catch (IOException e) { e.printStackTrace(); } } private int getPixelsCount () { if (this.color) { return this.file.length; } else { return this.file.length * 8; } } private int getColorByNumber (int number) { if (this.color) { if (this.lowColors) { int b = this.file[number]; b += 127; //TODO unsign convert if (b < 64) { return Color.red.getRGB(); } else if (b < 128) { return Color.blue.getRGB(); } else if (b < 192) { return Color.green.getRGB(); } else { return Color.yellow.getRGB(); } } else { return getColor4Byte(this.file[number]); } } else { int b = this.file[number/8]; int offset = 7-number%8; if (((b>>offset)&1) == 1) { return Color.black.getRGB(); } else { return Color.white.getRGB(); } } } private int getColor4Byte (byte b) { int red = (b>>5)&7; int green = (b>>2)&7; int blue = b&3; return (255<<24)|(red<<21)|(green<<13)|(blue<<6); } public void setColor(boolean color) { this.color = color; } public void setBackground(boolean background) { this.background = background; } public void setCircle(boolean circle) { this.circle = circle; } public void setWidth(int width) { this.width = width; } public void setOutFilename(String outFilename) { this.outFilename = outFilename; } public void setLowColors(boolean lowColors) { this.lowColors = lowColors; } }
true
217418703ddf4782f3b884312b51e47adceab6a3
Java
KocheEvo/lolesports
/src/main/java/com/kingjakeu/lolesports/api/rune/domain/Rune.java
UTF-8
925
2.28125
2
[]
no_license
package com.kingjakeu.lolesports.api.rune.domain; import lombok.*; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.time.LocalDateTime; @Entity @Getter @AllArgsConstructor @Builder @NoArgsConstructor(access = AccessLevel.PROTECTED) @Table(name = "RUNE") public class Rune { @Id @Column(name = "ID", length = 5) private String id; @Column(name = "RUNE_NAME", length = 50) private String name; @CreationTimestamp @Column(name = "CREATE_DTM", nullable = false, updatable = false, columnDefinition = "timestamp") private LocalDateTime createDateTime; @UpdateTimestamp @Column(name = "UPDATE_DTM", nullable = false, columnDefinition = "timestamp") private LocalDateTime updateDateTime; }
true
f6083f042bd0c791210dd4c605e25aa2671c96a4
Java
Azure/azure-sdk-for-java
/sdk/relay/azure-resourcemanager-relay/src/main/java/com/azure/resourcemanager/relay/fluent/models/HybridConnectionInner.java
UTF-8
4,399
1.976563
2
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "CC0-1.0", "BSD-3-Clause", "UPL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.relay.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.management.ProxyResource; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.OffsetDateTime; /** Description of hybrid connection resource. */ @Fluent public final class HybridConnectionInner extends ProxyResource { /* * Properties of the HybridConnection. */ @JsonProperty(value = "properties") private HybridConnectionProperties innerProperties; /** * Get the innerProperties property: Properties of the HybridConnection. * * @return the innerProperties value. */ private HybridConnectionProperties innerProperties() { return this.innerProperties; } /** * Get the createdAt property: The time the hybrid connection was created. * * @return the createdAt value. */ public OffsetDateTime createdAt() { return this.innerProperties() == null ? null : this.innerProperties().createdAt(); } /** * Get the updatedAt property: The time the namespace was updated. * * @return the updatedAt value. */ public OffsetDateTime updatedAt() { return this.innerProperties() == null ? null : this.innerProperties().updatedAt(); } /** * Get the listenerCount property: The number of listeners for this hybrid connection. Note that min : 1 and max:25 * are supported. * * @return the listenerCount value. */ public Integer listenerCount() { return this.innerProperties() == null ? null : this.innerProperties().listenerCount(); } /** * Get the requiresClientAuthorization property: Returns true if client authorization is needed for this hybrid * connection; otherwise, false. * * @return the requiresClientAuthorization value. */ public Boolean requiresClientAuthorization() { return this.innerProperties() == null ? null : this.innerProperties().requiresClientAuthorization(); } /** * Set the requiresClientAuthorization property: Returns true if client authorization is needed for this hybrid * connection; otherwise, false. * * @param requiresClientAuthorization the requiresClientAuthorization value to set. * @return the HybridConnectionInner object itself. */ public HybridConnectionInner withRequiresClientAuthorization(Boolean requiresClientAuthorization) { if (this.innerProperties() == null) { this.innerProperties = new HybridConnectionProperties(); } this.innerProperties().withRequiresClientAuthorization(requiresClientAuthorization); return this; } /** * Get the userMetadata property: The usermetadata is a placeholder to store user-defined string data for the hybrid * connection endpoint. For example, it can be used to store descriptive data, such as a list of teams and their * contact information. Also, user-defined configuration settings can be stored. * * @return the userMetadata value. */ public String userMetadata() { return this.innerProperties() == null ? null : this.innerProperties().userMetadata(); } /** * Set the userMetadata property: The usermetadata is a placeholder to store user-defined string data for the hybrid * connection endpoint. For example, it can be used to store descriptive data, such as a list of teams and their * contact information. Also, user-defined configuration settings can be stored. * * @param userMetadata the userMetadata value to set. * @return the HybridConnectionInner object itself. */ public HybridConnectionInner withUserMetadata(String userMetadata) { if (this.innerProperties() == null) { this.innerProperties = new HybridConnectionProperties(); } this.innerProperties().withUserMetadata(userMetadata); return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (innerProperties() != null) { innerProperties().validate(); } } }
true
8fdaf65b34bf99457eb39cd7cbe357c2027bf830
Java
umutisik/flow-on-pages
/src/org/monome/pages/pages/gui/MIDITriggersGUI.java
UTF-8
10,602
2.3125
2
[]
no_license
package org.monome.pages.pages.gui; import javax.swing.ButtonGroup; import javax.swing.JPanel; import javax.swing.JLabel; import java.awt.Rectangle; import javax.swing.JComboBox; import org.monome.pages.pages.MIDITriggersPage; import javax.swing.JRadioButton; import javax.swing.JCheckBox; import java.io.Serializable; import javax.swing.JTextField; public class MIDITriggersGUI extends JPanel implements Serializable { static final long serialVersionUID = 42L; MIDITriggersPage page; private JLabel pageLabel = null; private JComboBox rowColCB = null; private JLabel rowColLBL = null; private String[] colChoices = {"Col 1", "Col 2", "Col 3", "Col 4", "Col 5", "Col 6", "Col 7", "Col 8", "Col 9", "Col 10", "Col 11", "Col 12", "Col 13", "Col 14", "Col 15", "Col 16"}; private String[] rowChoices = {"Row 1", "Row 2", "Row 3", "Row 4", "Row 5", "Row 6", "Row 7", "Row 8", "Row 9", "Row 10", "Row 11", "Row 12", "Row 13", "Row 14", "Row 15", "Row 16"}; public JRadioButton rowRB = null; private JLabel rowLBL = null; public JRadioButton colRB = null; private JLabel colLBL = null; public JCheckBox onAndOffCB = null; private JLabel onAndOffLBL = null; private JComboBox modeCB = null; private JLabel modeLBL = null; private boolean ignoreModeCB = false; public JCheckBox ccCB = null; private JLabel ccLbl = null; private JTextField velocityTF = null; private JLabel velocityLBL = null; /** * This is the default constructor */ public MIDITriggersGUI(MIDITriggersPage page) { super(); this.page = page; initialize(); } /** * This method initializes this * * @return void */ private void initialize() { velocityLBL = new JLabel(); velocityLBL.setBounds(new Rectangle(95, 185, 96, 21)); velocityLBL.setText("Velocity"); ccLbl = new JLabel(); ccLbl.setBounds(new Rectangle(60, 160, 131, 21)); ccLbl.setText("MIDI CC Mode"); modeLBL = new JLabel(); modeLBL.setBounds(new Rectangle(10, 105, 33, 26)); modeLBL.setText("Mode"); pageLabel = new JLabel(); pageLabel.setBounds(new Rectangle(5, 5, 186, 21)); this.setSize(213, 222); this.setLayout(null); this.add(pageLabel, null); setName("MIDI Triggers Page"); this.add(getRowColCB(), null); this.add(getRowColLBL(), null); this.add(getRowRB(), null); this.add(getRowLBL(), null); this.add(getColRB(), null); this.add(getColLBL(), null); this.add(getOnAndOffCB(), null); this.add(getOnAndOffLBL(), null); this.add(getModeCB(), null); this.add(modeLBL, null); this.add(getCcCB(), null); this.add(ccLbl, null); this.add(getVelocityTF(), null); this.add(velocityLBL, null); ButtonGroup colRowBG = new ButtonGroup(); colRowBG.add(getRowRB()); colRowBG.add(getColRB()); rowRB.doClick(); } public void setName(String name) { pageLabel.setText((page.getIndex() + 1) + ": " + name); } private void colMode() { rowColCB.removeAllItems(); for (int i = 0; i < colChoices.length; i++) { rowColCB.addItem(colChoices[i]); } rowColLBL.setText("Col"); page.redrawDevice(); } private void rowMode() { rowColCB.removeAllItems(); for (int i = 0; i < rowChoices.length; i++) { rowColCB.addItem(rowChoices[i]); } rowColLBL.setText("Row"); page.redrawDevice(); } /** * This method initializes rowColCB * * @return javax.swing.JComboBox */ private JComboBox getRowColCB() { if (rowColCB == null) { rowColCB = new JComboBox(); rowColCB.setBounds(new Rectangle(45, 30, 96, 21)); rowColCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { String label = (String) rowColCB.getSelectedItem(); if (label == null) { return; } String[] pieces; if (rowRB.isSelected()) { pieces = label.split("Row "); } else { pieces = label.split("Col "); } int index = Integer.parseInt(pieces[1]) - 1; onAndOffCB.setSelected(page.onAndOff[index]); ccCB.setSelected(page.ccMode[index]); ignoreModeCB = true; modeCB.setSelectedIndex(page.mode[index]); velocityTF.setText("" + page.velocity[index]); } }); } return rowColCB; } /** * This method initializes rowColLBL * * @return javax.swing.JLabel */ private JLabel getRowColLBL() { if (rowColLBL == null) { rowColLBL = new JLabel(); rowColLBL.setText("Row"); rowColLBL.setBounds(new Rectangle(20, 30, 26, 21)); } return rowColLBL; } /** * This method initializes rowRB * * @return javax.swing.JRadioButton */ private JRadioButton getRowRB() { if (rowRB == null) { rowRB = new JRadioButton(); rowRB.setBounds(new Rectangle(45, 60, 21, 21)); rowRB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { rowMode(); } }); } return rowRB; } /** * This method initializes rowLBL * * @return javax.swing.JLabel */ private JLabel getRowLBL() { if (rowLBL == null) { rowLBL = new JLabel(); rowLBL.setText("Rows"); rowLBL.setBounds(new Rectangle(70, 60, 46, 21)); } return rowLBL; } /** * This method initializes colRB * * @return javax.swing.JRadioButton */ private JRadioButton getColRB() { if (colRB == null) { colRB = new JRadioButton(); colRB.setBounds(new Rectangle(45, 80, 21, 21)); colRB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { colMode(); } }); } return colRB; } /** * This method initializes colLBL * * @return javax.swing.JLabel */ private JLabel getColLBL() { if (colLBL == null) { colLBL = new JLabel(); colLBL.setText("Cols"); colLBL.setBounds(new Rectangle(70, 80, 46, 21)); } return colLBL; } /** * This method initializes onAndOffCB * * @return javax.swing.JCheckBox */ private JCheckBox getOnAndOffCB() { if (onAndOffCB == null) { onAndOffCB = new JCheckBox(); onAndOffCB.setBounds(new Rectangle(35, 135, 21, 21)); onAndOffCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { String label = (String) rowColCB.getSelectedItem(); if (label == null) { return; } String[] pieces; if (rowRB.isSelected()) { pieces = label.split("Row "); } else { pieces = label.split("Col "); } int index = Integer.parseInt(pieces[1]) - 1; page.onAndOff[index] = onAndOffCB.isSelected(); } }); } return onAndOffCB; } /** * This method initializes onAndOffLBL * * @return javax.swing.JLabel */ private JLabel getOnAndOffLBL() { if (onAndOffLBL == null) { onAndOffLBL = new JLabel(); onAndOffLBL.setText("Toggles On And Off"); onAndOffLBL.setBounds(new Rectangle(60, 135, 131, 21)); } return onAndOffLBL; } /** * This method initializes modeCB * * @return javax.swing.JComboBox */ public JComboBox getModeCB() { if (modeCB == null) { modeCB = new JComboBox(); modeCB.setBounds(new Rectangle(45, 105, 151, 25)); modeCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { if (ignoreModeCB == true) { ignoreModeCB = false; return; } String mode = (String) modeCB.getSelectedItem(); int index = getRowColIndex(); if (mode.compareTo("Triggers") == 0) { page.mode[index] = page.MODE_TRIGGERS; } else if (mode.compareTo("Toggles") == 0) { page.mode[index] = page.MODE_TOGGLES; } else if (mode.compareTo("Ableton Clip") == 0) { page.mode[index] = page.MODE_CLIP_OVERLAY; } else if (mode.compareTo("Ableton Looper") == 0) { page.mode[index] = page.MODE_LOOPER_OVERLAY; } page.redrawDevice(); } }); modeCB.addItem("Triggers"); modeCB.addItem("Toggles"); modeCB.addItem("Ableton Clip"); modeCB.addItem("Ableton Looper"); } return modeCB; } public int getRowColIndex() { String label = (String) rowColCB.getSelectedItem(); int index = 0; if (label == null) { return index; } String[] pieces; if (rowRB.isSelected()) { pieces = label.split("Row "); } else { pieces = label.split("Col "); } if (pieces.length < 2) { return index; } index = Integer.parseInt(pieces[1]) - 1; return index; } /** * This method initializes ccCB * * @return javax.swing.JCheckBox */ private JCheckBox getCcCB() { if (ccCB == null) { ccCB = new JCheckBox(); ccCB.setBounds(new Rectangle(35, 160, 21, 21)); ccCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { String label = (String) rowColCB.getSelectedItem(); if (label == null) { return; } String[] pieces; if (rowRB.isSelected()) { pieces = label.split("Row "); } else { pieces = label.split("Col "); } int index = Integer.parseInt(pieces[1]) - 1; page.ccMode[index] = ccCB.isSelected(); } }); } return ccCB; } /** * This method initializes velocityTF * * @return javax.swing.JTextField */ private JTextField getVelocityTF() { if (velocityTF == null) { velocityTF = new JTextField(); velocityTF.setBounds(new Rectangle(40, 185, 46, 21)); velocityTF.addCaretListener(new javax.swing.event.CaretListener() { public void caretUpdate(javax.swing.event.CaretEvent e) { String value = velocityTF.getText(); try { int velocity = Integer.parseInt(value); if (velocity >= 0 && velocity <= 127) { String label = (String) rowColCB.getSelectedItem(); if (label == null) { return; } String[] pieces; if (rowRB.isSelected()) { pieces = label.split("Row "); } else { pieces = label.split("Col "); } int index = Integer.parseInt(pieces[1]) - 1; page.velocity[index] = velocity; } } catch (NumberFormatException ex) { } } }); } return velocityTF; } } // @jve:decl-index=0:visual-constraint="10,10"
true
c81de21069bb38e048d9848beffb015134d20d27
Java
mbgit1/src
/logica/inscripcion/Inscripciones.java
UTF-8
3,552
2.65625
3
[]
no_license
package logica.inscripcion; import java.io.Serializable; import java.util.LinkedList; import java.util.List; import logica.inscripcion.Inscripcion; import logica.vo.VOEscolaridad; @SuppressWarnings("serial") public class Inscripciones implements Serializable { LinkedList<Inscripcion> inscripciones; public Inscripciones() { inscripciones = new LinkedList<Inscripcion>(); } public void addInscripcion( Inscripcion inscripcion ) { inscripciones.add( inscripcion ); } public List<VOEscolaridad> listarEscolaridad(boolean parcial) { List<VOEscolaridad> lista = new LinkedList<VOEscolaridad>(); for(Inscripcion i: inscripciones) { if (!parcial) lista.add( new VOEscolaridad( i.getNumero(), i.getAnio(), i.getMonto(), i.getCalificacion(), i.getAsignatura().getNombre() ) ); else if (i.aprobada()) lista.add( new VOEscolaridad( i.getNumero(), i.getAnio(), 0 , i.getCalificacion(), i.getAsignatura().getNombre() ) ); } return lista; } public Inscripcion obtenerInscripcion( int numero ) { int pos = --numero; return inscripciones.get(pos); } public int ultimaInscripcion() { int ultimaIns = 0; if (!inscripciones.isEmpty()) ultimaIns = inscripciones.getLast().getNumero(); return ultimaIns; } public void registrarCalificacion(int numero, int calificacion) { int pos = --numero; inscripciones.get(pos).setCalificacion(calificacion); } public boolean calificada(int numero) { int pos = --numero; return inscripciones.get(pos).calificada(); } public int montoRecaudado(int anioLectivo) { int monto = 0; for(Inscripcion i: inscripciones) { if (i.getAnio() == anioLectivo) monto+= i.getMonto(); } return monto*10; } public boolean egresado() { int cantAprobadas = 0; for(Inscripcion i: inscripciones) { if (i.aprobada()) cantAprobadas++; } return cantAprobadas == 10; } public boolean anioInscripcionValido(int anioLectivo) { boolean anioValido = true; if(!inscripciones.isEmpty()) { anioValido = anioLectivo >= this.inscripciones.getLast().getAnio(); } return anioValido; } public boolean asignaturaAprobada(String codigoAsignatura) { boolean yaAprobada = false; int num = 0; while( inscripciones.size() > num && !yaAprobada) { Inscripcion ins = inscripciones.get(num); if( ins.getAsignatura().getCodigo().equals(codigoAsignatura) ) { if(ins.aprobada()) yaAprobada = true; } num++; } return yaAprobada; } public boolean asignaturaEnCurso(String codigoAsignatura, int anioLectivo) { boolean enCurso = false; int num = 0; while( inscripciones.size() > num && !enCurso) { Inscripcion ins = inscripciones.getFirst(); if( ins.getAsignatura().getCodigo() == codigoAsignatura) { if(ins.getAnio() == anioLectivo) enCurso = true; } num++; } return enCurso; } //1= parcial, 0= total public float promedioAprobacion (boolean total) { float suma = 0; int cantidad = 0; float promedio = 0; if (!inscripciones.isEmpty()) { for(Inscripcion i: inscripciones) { if (i.aprobada()) { suma+= i.getCalificacion(); cantidad++; }else if (total) { suma+= i.getCalificacion(); cantidad++; } } promedio = suma/cantidad; } return promedio; } }
true
588206ee1e84527aed1a4726f4d0cb57f8b56784
Java
sanvedj/MayuriC2WT
/Daily Flash/week 4/day 1/18-DailyFlash_Solutions/3_Feb_Solutions_One/Java/Program3.java
UTF-8
343
3.09375
3
[]
no_license
import java.io.*; class Program3{ public static void main(String args[])throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the Distance in Km"); int num = Integer.parseInt(br.readLine()); System.out.printf("Distance in meter %d m",num*1000); } }
true
5fc19d15cfd3388a5b4829e78a0bbf7bebc0cda6
Java
appleseed-wb/OrangeMsg
/src/main/java/com/orange/msg/service/BusinessService.java
UTF-8
867
2.03125
2
[]
no_license
package com.orange.msg.service; import com.orange.msg.entity.Business; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; /** * 业务操作 */ public interface BusinessService { /** * 保存业务操作 * @param business * @return */ public Business save(Business business); /** * 保存业务操作 * @param uuid * @param time * @param msg * @return */ public Business saveBusiness(String uuid, Long time, String msg); /** * 查询业务消息 * @return */ public Page<Business> findAll(Pageable pageable); /** * 修改消息 * @param business */ public void update(Business business); /** * 获取消息 * @param uuid * @return */ public Business findOne(String uuid); }
true
92541443db67e99ede79db2c8473a834d093d438
Java
ereilly89/uww-alumni-web-app
/JSPHelloWorld/src/tablemaker/Employee.java
UTF-8
2,331
3.125
3
[]
no_license
package tablemaker; public class Employee { String employee_id; String position; String startSalary; String startYear; String endYear; String employerID; String employer_name; String employer_location; Employee(String employee1, String employee2, String employee3, String employee4, String employee5, String employee6, String nameMatch, String locationMatch){ employee_id = employee1; position = employee2; startSalary = employee3; startYear = employee4; endYear = employee5; employerID = employee6; //Employer Name & Location (used for matching) employer_name = nameMatch; employer_location = locationMatch; } Employee(){ employee_id = "EmplID"; position = "Position"; startSalary = "Starting Salary"; startYear = "Start Year"; endYear = "End Year"; employerID = "EmployerID"; //DEFAULT employer_name = ""; employer_location = ""; } public String getEmployee_id() { return employee_id; } public void setEmployee_id(String employee_id) { this.employee_id = employee_id; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getStartSalary() { return startSalary; } public void setStartSalary(String startSalary) { this.startSalary = startSalary; } public String getStartYear() { return startYear; } public void setStartYear(String startYear) { this.startYear = startYear; } public String getEndYear() { return endYear; } public void setEndYear(String endYear) { this.endYear = endYear; } public String getEmployerID() { return employerID; } public void setEmployerID(String employerID) { this.employerID = employerID; } public String getEmployer_name() { return employer_name; } public void setEmployer_name(String employer_name) { this.employer_name = employer_name; } public String getEmployer_location() { return employer_location; } public void setEmployer_location(String employer_location) { this.employer_location = employer_location; } @Override public String toString() { return employee_id+", "+position+", "+startSalary+", "+startYear+", "+endYear+", "+employerID+"\n"; } }
true
546964fed823a9971026cab9097c98c3a065cadc
Java
wlsdntyd/eclipse
/src/chapter2/PersonExam2.java
UHC
1,078
3.828125
4
[]
no_license
package chapter2; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class PersonExam2 { static Person1[] members = new Person1[100]; static int n = 0; public static void main(String[] args) { try { Scanner in = new Scanner(new File("input.txt")); while(in.hasNext()) { members[n] = new Person1(); // ü . members[n].name = in.next(); members[n].number = in.next(); n++; } in.close(); } catch (FileNotFoundException e) { System.out.println("File not exist"); } bubbleSort(); for(int i = 0; i < n; i++) System.out.println(members[i].name + " : " + members[i].number); } public static void bubbleSort() { for(int i = n-1; i > 0; i--) { for(int j = 0; j < i; j++) { if(members[j].name.compareToIgnoreCase(members[j+1].name) > 1) { Person1 tmp = members[j]; // Ŭ ȿ ̸ ȣ Ƿ members[j] = members[j+1]; // ٲָ ȴ. members[j+1] = tmp; } } } } }
true
c19f221b7c9399bd92d39b55d78cf8f6753fe984
Java
zhongxingyu/Seer
/Diff-Raw-Data/6/6_5d5b4113c0a6b8e6fe63b2c3474b99c2aa9dfaed/DailyTransactionsTest/6_5d5b4113c0a6b8e6fe63b2c3474b99c2aa9dfaed_DailyTransactionsTest_s.java
UTF-8
11,342
2.515625
3
[]
no_license
/** * Swift Ticket -- Back End * * Copyright (C) 2013, Jonathan Gillett, Daniel Smullen, and Rayan Alfaheid * All rights reserved. * * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import static org.junit.Assert.*; import java.io.IOException; import org.junit.Rule; import org.junit.Test; import org.junit.contrib.java.lang.system.StandardErrorStreamLog; public class DailyTransactionsTest { /* Objects used for executing the test suite */ private DailyTransactions transactions; /* Parameters used for the tests */ private static final String logoutTransaction = "00_administrator___AA_000000.00"; private static final String createTransaction = "01_newuser_________BS_000000.00"; private static final String deleteTransaction = "02_buyer___________BS_000000.00"; private static final String addcreditTransaction = "06_buyer___________BS_000010.00"; private static final String refundTransaction = "05_buyer___________seller__________000005.00"; private static final String sellTransaction = "03_The_Goosebumps______administrator___023_012.00"; private static final String buyTransaction = "04_The_Godfather_______seller__________004_010.00"; @Rule public final StandardErrorStreamLog log = new StandardErrorStreamLog(); /** * Test method for {@link DailyTransactions#getTransactions()}. * * Tests the getTransaction method in the DailyTransactions class, by * executing the method. This method is a simple accessor method * with only one return call. * @throws IOException * @throws FatalError */ @Test public void testGetTransactions() throws FatalError, IOException { transactions = new DailyTransactions("files/DailyTransactionsTestGetTransactions.dtf"); /* Verify that the transaction was loaded into memory */ for (Transaction transaction : transactions.getTransactions()) { assertEquals(logoutTransaction, transaction.getTransaction()); } } /** * Test method for {@link DailyTransactions#load()}. * * Tests the load method in the DailyTransactions class, by executing the * DailyTransactions constructor, providing a nonexistent daily transaction * file. Verify that a File IO Exception is thrown and caught. A Fatal Error * exception must be thrown. * @throws IOException */ @Test public void testLoad1() throws IOException { /* Verify that a fatal error ExceptionCodes.DTF_NOT_FOUND is thrown */ try { transactions = new DailyTransactions("files/InvalidFileName.dtf"); } catch (FatalError e) { assertEquals(ExceptionCodes.DTF_NOT_FOUND.toString(), e.getMessage()); } } /** * Test method for {@link DailyTransactions#load()}. * * Tests the load method in the DailyTransactions class, by executing the * DailyTransactions constructor, providing a valid daily transaction file * with a valid transaction. Verify that the entry is added to the merged * list of transactions. * @throws IOException * @throws FatalError */ @Test public void testLoad2() throws FatalError, IOException { transactions = new DailyTransactions("files/DailyTransactionsTestGetTransactions.dtf"); /* Verify that the transaction was loaded into memory */ for (Transaction transaction : transactions.getTransactions()) { assertEquals(logoutTransaction, transaction.getTransaction()); } } /** * Test method for {@link DailyTransactions#load()}. * * Tests the load method in the DailyTransactions class, by executing * the DailyTransactions constructor, providing a valid daily transaction * file with an invalid transaction. A Fatal Error exception must be thrown. * @throws IOException * @throws FatalError */ @Test public void testLoad3() throws FatalError, IOException { /* Verify that a fatal error ExceptionCodes.CORRUPT_DTF is thrown */ try { transactions = new DailyTransactions("files/DailyTransactionsTestLoad3.dtf"); } catch (FatalError e) { assertEquals(ExceptionCodes.CORRUPT_DTF.toString(), e.getMessage()); } } /** * Test method for {@link DailyTransactions#parse()}. * * Tests the parse method for the DailyTransactions class by executing the * DailyTransactions constructor, providing a valid merged daily transaction * file, containing a logout transaction. Verify that the transaction is * added to the collection of transactions successfully. * @throws IOException * @throws FatalError */ @Test public void testParse1() throws FatalError, IOException { transactions = new DailyTransactions("files/DailyTransactionsTestParse1.dtf"); /* Verify that the delete transaction was parsed and is in memory */ for (Transaction transaction : transactions.getTransactions()) { assertEquals(logoutTransaction, transaction.getTransaction()); } } /** * Test method for {@link DailyTransactions#parse()}. * * Tests the parse method for the DailyTransactions class by executing * the DailyTransactions constructor, providing a valid merged daily * transaction file, containing a create transaction. Verify that the * transaction is added to the collection of transactions successfully. * @throws IOException * @throws FatalError */ @Test public void testParse2() throws FatalError, IOException { transactions = new DailyTransactions("files/DailyTransactionsTestParse2.dtf"); /* Verify that the delete transaction was parsed and is in memory */ for (Transaction transaction : transactions.getTransactions()) { assertEquals(createTransaction, transaction.getTransaction()); } } /** * Test method for {@link DailyTransactions#parse()}. * * Tests the parse method for the DailyTransactions class by executing * the DailyTransactions constructor, providing a valid merged daily * transaction file, containing a delete transaction. Verify that the * transaction is added to the collection of transactions successfully. * @throws IOException * @throws FatalError */ @Test public void testParse3() throws FatalError, IOException { transactions = new DailyTransactions("files/DailyTransactionsTestParse3.dtf"); /* Verify that the delete transaction was parsed and is in memory */ for (Transaction transaction : transactions.getTransactions()) { assertEquals(deleteTransaction, transaction.getTransaction()); } } /** * Test method for {@link DailyTransactions#parse()}. * * Tests the parse method for the DailyTransactions class by executing the * DailyTransactions constructor, providing a valid merged daily transaction * file, containing a addcredit transaction. Verify that the transaction is * added to the collection of transactions successfully. * @throws IOException * @throws FatalError */ @Test public void testParse4() throws FatalError, IOException { transactions = new DailyTransactions("files/DailyTransactionsTestParse4.dtf"); /* Verify that the addcredit transaction was parsed and is in memory */ for (Transaction transaction : transactions.getTransactions()) { assertEquals(addcreditTransaction, transaction.getTransaction()); } } /** * Test method for {@link DailyTransactions#parse()}. * * Tests the parse method for the DailyTransactions class by executing * the DailyTransactions constructor, providing a valid merged daily * transaction file, containing a refund transaction. Verify that the * transaction is added to the collection of transactions successfully. * @throws IOException * @throws FatalError */ @Test public void testParse5() throws FatalError, IOException { transactions = new DailyTransactions("files/DailyTransactionsTestParse5.dtf"); /* Verify that the refund transaction was parsed and is in memory */ for (Transaction transaction : transactions.getTransactions()) { assertEquals(refundTransaction, transaction.getTransaction()); } } /** * Test method for {@link DailyTransactions#parse()}. * * Tests the parse method for the DailyTransactions class by executing * the DailyTransactions constructor, providing a valid merged daily * transaction file, containing a sell transaction. Verify that the * transaction is added to the collection of transactions successfully. * @throws IOException * @throws FatalError */ @Test public void testParse6() throws FatalError, IOException { transactions = new DailyTransactions("files/DailyTransactionsTestParse6.dtf"); /* Verify that the sell transaction was parsed and is in memory */ for (Transaction transaction : transactions.getTransactions()) { assertEquals(sellTransaction, transaction.getTransaction()); } } /** * Test method for {@link DailyTransactions#parse()}. * * Tests the parse method for the DailyTransactions class by executing * the DailyTransactions constructor, providing a valid merged daily * transaction file, containing a buy transaction. Verify that the * transaction is added to the collection of transactions successfully. * @throws IOException * @throws FatalError */ @Test public void testParse7() throws FatalError, IOException { transactions = new DailyTransactions("files/DailyTransactionsTestParse7.dtf"); /* Verify that the buy transaction was parsed and is in memory */ for (Transaction transaction : transactions.getTransactions()) { assertEquals(buyTransaction, transaction.getTransaction()); } } }
true
308aecbc4ecb69391cce8c2844d3088bc5343acf
Java
DHAFFFFF/1-pemrograman-dasar
/3. live coding 1/transposmatriks.java
UTF-8
628
3.203125
3
[]
no_license
import java.util.*; public class transposmatriks { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int a, b, c, d, e, f, g, h, i; a = scan.nextInt(); b = scan.nextInt(); c = scan.nextInt(); d = scan.nextInt(); e = scan.nextInt(); f = scan.nextInt(); g = scan.nextInt(); h = scan.nextInt(); i = scan.nextInt(); System.out.println(a + " " + d + " " + g); System.out.println(b + " " + e + " " + h); System.out.println(c + " " + f + " " + i); } }
true
d27b50391ca6d5f48a21b546148fccd554779185
Java
quarkusio/quarkus
/extensions/amazon-lambda/runtime/src/main/java/io/quarkus/amazon/lambda/runtime/AmazonLambdaStaticRecorder.java
UTF-8
742
1.835938
2
[ "Apache-2.0" ]
permissive
package io.quarkus.amazon.lambda.runtime; import java.util.Set; import com.amazonaws.services.lambda.runtime.RequestHandler; import com.amazonaws.services.lambda.runtime.RequestStreamHandler; import io.quarkus.runtime.annotations.Recorder; @Recorder public class AmazonLambdaStaticRecorder { public void setHandlerClass(Class<? extends RequestHandler<?, ?>> handler) { AmazonLambdaRecorder.initializeHandlerClass(handler); } public void setStreamHandlerClass(Class<? extends RequestStreamHandler> handler) { AmazonLambdaRecorder.streamHandlerClass = handler; } public void setExpectedExceptionClasses(Set<Class<?>> classes) { AmazonLambdaRecorder.expectedExceptionClasses = classes; } }
true
c777e85343410346fe6b90082bb5089f59634936
Java
singhsharry7/rnr
/api-client/src/test/java/com/snapdeal/reviews/configuration/ConfigurationClientTest.java
UTF-8
15,070
2.0625
2
[]
no_license
package com.snapdeal.reviews.configuration; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.apache.commons.lang.RandomStringUtils; import org.junit.Assert; import org.junit.Test; import com.snapdeal.base.exception.SnapdealWSException; import com.snapdeal.base.model.common.ServiceResponse; import com.snapdeal.reviews.ReviewsApiTest; import com.snapdeal.reviews.commons.config.ReviewConfiguration; import com.snapdeal.reviews.commons.config.ReviewQualityWeightageConfiguration; import com.snapdeal.reviews.commons.dto.DeleteRejectionReason; import com.snapdeal.reviews.commons.dto.RejectionReason; import com.snapdeal.reviews.commons.dto.RejectionReasonResponse; import com.snapdeal.reviews.commons.dto.wrapper.CreateRejectionReasonResponse; import com.snapdeal.reviews.commons.dto.wrapper.DeleteRejectionReasonRequest; import com.snapdeal.reviews.commons.dto.wrapper.RejectionReasonsRequest; import com.snapdeal.reviews.commons.dto.wrapper.ReviewConfigurationRequest; import com.snapdeal.reviews.commons.dto.wrapper.ReviewConfigurationResponse; import com.snapdeal.reviews.commons.pagination.ReviewListingSortType; public class ConfigurationClientTest extends ReviewsApiTest { private ReviewConfiguration reviewConfiguration; private ReviewQualityWeightageConfiguration reviewQualityWeightageConfiguration; private Map<String , String> queryParams = new HashMap<String , String>(); private ReviewConfiguration getTestDataReviewConfiguration() { ReviewConfiguration reviewConfiguration = new ReviewConfiguration(); reviewConfiguration.setCreateReviewRecommendationMandatory(true); reviewConfiguration.setCreateReviewRecommendationVisibility(true); reviewConfiguration.setCreateReviewRichDataVisibilty(true); reviewConfiguration.setDefaultMinTitleSize(5); reviewConfiguration.setDefaultMaxTitleSize(20); reviewConfiguration.setDefaultMinCommentSize(20); reviewConfiguration.setDefaultMaxCommentSize(50); reviewConfiguration.setDefaultPaginationSize(500); reviewConfiguration .setDefaultReviewListingSortType(ReviewListingSortType.HELPFUL_DESC); return reviewConfiguration; } /* * private ReviewQualityWeightageConfiguration * getTestDataReviewQualityWeightageConfiguration() { * ReviewQualityWeightageConfiguration reviewQualityWeightageConfiguration = * new ReviewQualityWeightageConfiguration(); * reviewQualityWeightageConfiguration * .getFreshnessConfiguration().setWeightage(0.2f); * reviewQualityWeightageConfiguration.setGetsFlaggedWeightage(0.05f); * reviewQualityWeightageConfiguration * .getHelpFulVoteConfiguration().setWeightage(0.1f);getAllProductsReviewedByUser * reviewQualityWeightageConfiguration * .getModeratorConfiguration().setWeightage(.03f);; * reviewQualityWeightageConfiguration * .getLengthOfReviewConfiguration().setWeightage(.5f);; * reviewQualityWeightageConfiguration * .getTypeOfReviewerConfiguration().setWeightage(.1f);; * reviewQualityWeightageConfiguration.setLocalLanguageWeightage(0.1f); * * return reviewQualityWeightageConfiguration; } */ @SuppressWarnings("deprecation") @Test public void testSetConfigurationSettings() throws SnapdealWSException { ReviewConfigurationRequest reviewConfigurationRequest = new ReviewConfigurationRequest(); reviewConfiguration = getTestDataReviewConfiguration(); reviewConfigurationRequest.setReviewConfiguration(reviewConfiguration); ServiceResponse serviceResponse = (ServiceResponse) getConfigurationClient() .setReviewConfiguration(reviewConfigurationRequest); Assert.assertEquals(true, serviceResponse.isSuccessful()); } @Test public void testGetConfigurationSettings() throws SnapdealWSException { ReviewConfiguration expected = getTestDataReviewConfiguration(); ReviewConfigurationResponse reviewConfigurationResponse = getConfigurationClient() .getReviewConfiguration(); ReviewConfiguration actual = reviewConfigurationResponse .getReviewConfiguration(); Assert.assertEquals(expected.getDefaultReviewListingSortType().name(), actual.getDefaultReviewListingSortType().name()); Assert.assertEquals(expected.getDefaultMinTitleSize(), actual.getDefaultMinTitleSize()); Assert.assertEquals(expected.getDefaultMaxTitleSize(), actual.getDefaultMaxTitleSize()); Assert.assertEquals(expected.getDefaultMinCommentSize(), actual.getDefaultMinCommentSize()); Assert.assertEquals(expected.getDefaultMaxCommentSize(), actual.getDefaultMaxCommentSize()); Assert.assertEquals(expected.getDefaultPaginationSize(), actual.getDefaultPaginationSize()); Assert.assertEquals(expected.getCreateReviewRecommendationMandatory(), actual.getCreateReviewRecommendationMandatory()); Assert.assertEquals(expected.getCreateReviewRecommendationVisibility(), actual.getCreateReviewRecommendationVisibility()); Assert.assertEquals(expected.getCreateReviewRichDataVisibilty(), actual.getCreateReviewRichDataVisibilty()); } // Negative Scenario for set configuration APIs // maxTitleSize less than minTitleSize @Test public void testSetConfigurationSettingsMaxGreaterThanMinTitleSize() throws SnapdealWSException { ReviewConfigurationRequest reviewConfigurationRequest = new ReviewConfigurationRequest(); reviewConfiguration = getTestDataReviewConfiguration(); reviewConfiguration.setDefaultMinTitleSize(15); reviewConfiguration.setDefaultMaxTitleSize(10); reviewConfigurationRequest.setReviewConfiguration(reviewConfiguration); try { getConfigurationClient().setReviewConfiguration( reviewConfigurationRequest); } catch (Exception e) { Assert.assertTrue(e.getCause().getMessage() .contains("INPUT_INVALID_PAYLOAD")); } } // Negative Input @Test public void testSetConfigurationSettingsWithNegativeInput() throws SnapdealWSException { ReviewConfigurationRequest reviewConfigurationRequest = new ReviewConfigurationRequest(); reviewConfiguration = getTestDataReviewConfiguration(); reviewConfiguration.setDefaultPaginationSize(-1); reviewConfigurationRequest.setReviewConfiguration(reviewConfiguration); try { getConfigurationClient().setReviewConfiguration( reviewConfigurationRequest); } catch (Exception e) { Assert.assertTrue(e.getCause().getMessage() .contains("INPUT_INVALID_PAYLOAD")); } } /* * Test Cases For Review Quality Weightage Configuration Settings */ /* * @SuppressWarnings("deprecation") * * @Test public void testSetReviewQualityWeightageSettings() throws * SnapdealWSException { reviewQualityWeightageConfiguration = * getTestDataReviewQualityWeightageConfiguration(); * ReviewQualityWeightageConfigurationRequest request = new * ReviewQualityWeightageConfigurationRequest(); * request.setReviewQualityWeightageConfiguration * (reviewQualityWeightageConfiguration); ServiceResponse serviceResponse = * (ServiceResponse) getConfigurationClient() * .setReviewQualityWeightageConfiguration(request); * Assert.assertEquals(true, serviceResponse.isSuccessful()); } * * @Test public void testGetReviewQualityWeightageSettings() throws * SnapdealWSException { ReviewQualityWeightageConfiguration expected = * getTestDataReviewQualityWeightageConfiguration(); * ReviewQualityWeightageConfigurationResponse response = * getConfigurationClient() .getReviewQualityWeightageConfiguration(); * ReviewQualityWeightageConfiguration actual = response * .getReviewQualityWeightageConfiguration(); * * Assert.assertEquals(expected.getFreshnessConfiguration().getWeightage(), * actual.getFreshnessConfiguration().getWeightage()); * Assert.assertEquals(expected.getGetsFlaggedWeightage(), * actual.getGetsFlaggedWeightage()); * Assert.assertEquals(expected.getHelpFulVoteConfiguration * ().getWeightage(), actual.getHelpFulVoteConfiguration().getWeightage()); * Assert.assertEquals(expected.getLocalLanguageWeightage(), * actual.getLocalLanguageWeightage()); * Assert.assertEquals(expected.getModeratorConfiguration().getWeightage(), * actual.getModeratorConfiguration().getWeightage()); * Assert.assertEquals(expected * .getLengthOfReviewConfiguration().getWeightage(), * actual.getLengthOfReviewConfiguration().getWeightage()); * Assert.assertEquals * (expected.getTypeOfReviewerConfiguration().getWeightage(), * actual.getTypeOfReviewerConfiguration().getWeightage()); } * * // Negative Scenarios * * // If total weightage exceeds 1 * * @Test public void testSetWeightageConfigurationWithWeightageExceedsOne(){ * ReviewQualityWeightageConfigurationRequest request = new * ReviewQualityWeightageConfigurationRequest(); * reviewQualityWeightageConfiguration = * getTestDataReviewQualityWeightageConfiguration(); * reviewQualityWeightageConfiguration * .getFreshnessConfiguration().setWeightage(0.6f);; * request.setReviewQualityWeightageConfiguration * (reviewQualityWeightageConfiguration); try { * getConfigurationClient().setReviewQualityWeightageConfiguration(request); * } catch (Exception e) { Assert.assertTrue(e.getCause().getMessage() * .contains("INPUT_INVALID_PAYLOAD")); } } * * // If any input in negative * * @Test public void testSetWeightageConfigurationWithNegativeInputs(){ * ReviewQualityWeightageConfigurationRequest request = new * ReviewQualityWeightageConfigurationRequest(); * reviewQualityWeightageConfiguration = * getTestDataReviewQualityWeightageConfiguration(); * reviewQualityWeightageConfiguration * .getFreshnessConfiguration().setWeightage(-1f);; * request.setReviewQualityWeightageConfiguration * (reviewQualityWeightageConfiguration); try { * getConfigurationClient().setReviewQualityWeightageConfiguration(request); * } catch (Exception e) { Assert.assertTrue(e.getCause().getMessage() * .contains("INPUT_INVALID_PAYLOAD")); } } * * // If any input is greater than 1 /* @Test public void * testSetWeightageConfigurationWithInputsGreaterThanOne(){ * ReviewQualityWeightageConfigurationRequest request = new * ReviewQualityWeightageConfigurationRequest(); * reviewQualityWeightageConfiguration = * getTestDataReviewQualityWeightageConfiguration(); * reviewQualityWeightageConfiguration * .getFreshnessConfiguration().setWeightage(1.4f); * request.setReviewQualityWeightageConfiguration * (reviewQualityWeightageConfiguration); try { * getConfigurationClient().setReviewQualityWeightageConfiguration(request); * } catch (Exception e) { Assert.assertTrue(e.getCause().getMessage() * .contains("INPUT_INVALID_PAYLOAD")); } } */ // //////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * Test Cases For Rejection Reasons */ public RejectionReason prepareRejectionReason() { RejectionReason rejectionReason = new RejectionReason(); rejectionReason.setRejectionReason(RandomStringUtils .randomAlphabetic(20)); return rejectionReason; } @Test public void testCreateRejectionReason() throws SnapdealWSException { RejectionReasonsRequest request = new RejectionReasonsRequest(); request.setRejectionReasonRequest(prepareRejectionReason()); CreateRejectionReasonResponse response = getConfigurationClient() .addRejectionReasons(request); Assert.assertEquals(request.getRejectionReasonRequest() .getRejectionReason(), response.getRejectionReason().getValue()); } @Test public void testDeleteRejectionReason() throws SnapdealWSException { RejectionReasonsRequest request = new RejectionReasonsRequest(); request.setRejectionReasonRequest(prepareRejectionReason()); CreateRejectionReasonResponse response = getConfigurationClient() .addRejectionReasons(request); DeleteRejectionReasonRequest deleteRequest = new DeleteRejectionReasonRequest(); DeleteRejectionReason deleteRejectionReason = new DeleteRejectionReason(); deleteRejectionReason.setRejectionReasonUUID(response .getRejectionReason().getId().toString()); ServiceResponse deletionResponse = getConfigurationClient() .deleteRejectionReasons(deleteRequest); Assert.assertTrue(deletionResponse.isSuccessful()); } @Test public void testGetRejectionReasons() throws SnapdealWSException { RejectionReasonResponse response = getConfigurationClient() .getRejectionReasons(queryParams); Assert.assertTrue(response.isSuccessful()); } // Negative Scenarios for Rejection Reasons // creating an already created review @Test public void testCreationOfAlreadyCreatedReason() throws SnapdealWSException { RejectionReasonsRequest request = new RejectionReasonsRequest(); request.setRejectionReasonRequest(prepareRejectionReason()); CreateRejectionReasonResponse response = getConfigurationClient() .addRejectionReasons(request); try { getConfigurationClient().addRejectionReasons(request); } catch (SnapdealWSException e) { Assert.assertEquals(403, e.getWsErrorCode()); } } // Deletion with invalid reasonUUID @Test public void testDeletionWithInvalidReasonUUID() throws SnapdealWSException { DeleteRejectionReasonRequest deleteRequest = new DeleteRejectionReasonRequest(); DeleteRejectionReason deleteRejectionReason = new DeleteRejectionReason(); deleteRejectionReason.setRejectionReasonUUID("test1223"); deleteRequest.setDeleteRejectionReason(deleteRejectionReason); try { getConfigurationClient().deleteRejectionReasons(deleteRequest); } catch (SnapdealWSException e) { Assert.assertEquals(400, e.getWsErrorCode()); } } // Deletion with reason already deleted @Test public void testAlreadyDeletedReviewReasonUUID() throws SnapdealWSException { RejectionReasonsRequest request = new RejectionReasonsRequest(); request.setRejectionReasonRequest(prepareRejectionReason()); CreateRejectionReasonResponse response = getConfigurationClient() .addRejectionReasons(request); DeleteRejectionReasonRequest deleteRequest = new DeleteRejectionReasonRequest(); DeleteRejectionReason deleteRejectionReason = new DeleteRejectionReason(); deleteRejectionReason.setRejectionReasonUUID(response .getRejectionReason().getId().toString()); deleteRequest.setDeleteRejectionReason(deleteRejectionReason); getConfigurationClient().deleteRejectionReasons(deleteRequest); try { getConfigurationClient().deleteRejectionReasons(deleteRequest); } catch (SnapdealWSException e) { Assert.assertEquals(403, e.getWsErrorCode()); } } // Deletion with valid reason UUID but reason doesn't Exists @Test public void testForReasonNotExits() throws SnapdealWSException { String reasonUUID = UUID.randomUUID().toString(); DeleteRejectionReasonRequest deleteRequest = new DeleteRejectionReasonRequest(); DeleteRejectionReason deleteRejectionReason = new DeleteRejectionReason(); deleteRejectionReason.setRejectionReasonUUID(reasonUUID); deleteRequest.setDeleteRejectionReason(deleteRejectionReason); try { getConfigurationClient().deleteRejectionReasons(deleteRequest); } catch (SnapdealWSException e) { Assert.assertEquals(403, e.getWsErrorCode()); } } }
true
794fc2333ab327bb4bdaa806702904c33f20f643
Java
intuij/Tetris
/src/ui/ExpBlock.java
UTF-8
2,343
2.828125
3
[]
no_license
package ui; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import javax.swing.ImageIcon; import data.Dto; import util.DrawNumber; public class ExpBlock extends Block{ //private static final Image EXP_STR = new ImageIcon("graphics/string/exp.png").getImage(); private static final Image RM_STR = new ImageIcon("graphics/string/rmline.png").getImage(); private static final Image SC_STR = new ImageIcon("graphics/string/score.png").getImage(); private static final Image RECT = new ImageIcon("graphics/window/rect.png").getImage(); private static final int SPACING = 48; // Size of rect private static final int RECT_WIDTH = RECT.getWidth(null); private static final int RECT_HEIGHT = RECT.getHeight(null); // Size of exp slot private final int SLOT_WIDTH = this.width - PADDLE * 4 - 4; private final int SLOT_HEIGHT = 26; public ExpBlock(int x, int y, int width, int height) { super(x, y, width, height); } @Override void paint(Graphics g) { super.display(g); // Draw string g.drawImage(RM_STR, posX + PADDLE * 2, posY + PADDLE * 2, null); g.drawImage(SC_STR, posX + PADDLE * 2, posY + PADDLE * 2 + SPACING, null); //g.drawImage(EXP_STR, posX + PADDLE * 2, posY + PADDLE * 2 + SPACING * 2, null); // Draw digits DrawNumber.drawNum(this.posX + 150, posY + PADDLE * 2, 5, dto.getCurrLine(), g); DrawNumber.drawNum(this.posX + 150, posY + PADDLE * 2 + SPACING, 5, dto.getCurrScore(), g); // Draw exp slot g.setColor(Color.BLACK); g.fillRect(posX + PADDLE * 2, posY + PADDLE * 2 + SPACING * 2, width - PADDLE * 4, 30); g.setColor(Color.WHITE); g.fillRect(posX + PADDLE * 2 + 1, posY + PADDLE * 2 + SPACING * 2 + 1, width - PADDLE * 4 - 2, 28); g.setColor(Color.BLACK); g.fillRect(posX + PADDLE * 2 + 2, posY + PADDLE * 2 + SPACING * 2 + 2, width - PADDLE * 4 - 4, 26); fillSlot(g); } private void fillSlot(Graphics g) { double ratio = (double)(dto.getCurrLine() % Dto.LEVEL_UP) / Dto.LEVEL_UP; int len = (int)(ratio * SLOT_WIDTH); int pos = (int)(ratio * RECT_WIDTH); g.drawImage(RECT, posX + PADDLE * 2 + 2, posY + PADDLE * 2 + SPACING * 2 + 2, posX + PADDLE * 2 + 2 + len, posY + PADDLE * 2 + SPACING * 2 + 2 + SLOT_HEIGHT, pos, 0, pos + 1, RECT_HEIGHT, null); } }
true
1ccde0548d2b99090f56fcc63d13654be65e1ec3
Java
Psylence/CSE-4471
/src/edu/osu/AU13/cse4471/securevote/Poll.java
UTF-8
7,010
2.734375
3
[]
no_license
package edu.osu.AU13.cse4471.securevote; import java.io.File; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import org.json.JSONException; import org.json.JSONObject; import edu.osu.AU13.cse4471.securevote.JSONUtils.JSONSerializable; import edu.osu.AU13.cse4471.securevote.math.Group; import edu.osu.AU13.cse4471.securevote.math.GroupElement; import edu.osu.AU13.cse4471.securevote.math.IntegersModPrimePower; /** * This class represents a poll known to a single client. */ public class Poll implements JSONSerializable { private static final int SANITY_BOUND = 100; private static final String JSON_ID = "id"; private static final String JSON_TITLE = "title"; private static final String JSON_DESC = "desc"; private static final String JSON_VOTERS = "voters"; private static final String JSON_TALLIERS = "talliers"; private static final String JSON_GROUP = "group"; private static final String JSON_LITTLE_G = "g1"; private static final String JSON_BIG_G = "g2"; /** * Private ID, used internally to identify this Poll, especially when * recreating it from a file/DB */ private UUID id; /** * Title to identify this poll to users */ private String title; /** * Description of the poll shown to users */ private String desc; /** * List of voters in this poll. These are the users who can actually cast * votes. */ private List<String> voters; /** * List of talliers in this poll. These are the users to whom results are * sent to be decoded. */ private List<String> talliers; /** * Group used for encryption in this poll */ private Group group; /** * Parameters <i>g</i> and <i>G</i> are two group generators, used in * encryption */ private GroupElement g, G; /** * Keep track of files to delete when deleting this poll. */ private Set<File> filesToDelete = new HashSet<File>(); /** * Create a new Poll object * * @param id * unique identifier * @param title * Display title * @param desc * Display description * @param voters * List of voters * @param talliers * List of talliers */ public Poll(UUID id, String title, String desc, List<String> voters, List<String> talliers) { if (id == null || title == null || desc == null) { throw new NullPointerException(); } this.id = id; this.title = title; this.desc = desc; this.voters = voters; this.talliers = talliers; int outerSanity = 0; int sanity; do { IntegersModPrimePower gp = IntegersModPrimePower.generateRandom(); this.group = gp; // Create generators this.g = gp.getRandomGenerator(); sanity = 0; do { this.G = gp.getRandomGenerator(); sanity++; } while (g.equals(G) && sanity < Poll.SANITY_BOUND); outerSanity++; } while (sanity == Poll.SANITY_BOUND && outerSanity < Poll.SANITY_BOUND); if (outerSanity == Poll.SANITY_BOUND) { throw new RuntimeException( "You're insane: failed to create a group with two random generators."); } } /** * Deserialize a Poll from a JSONObject. * * @param obj * JSONObject as returned by {@link toJson()}. * @throws IllegalArgumentException */ public Poll(JSONObject obj) throws JSONException { try { id = UUID.fromString(obj.getString(Poll.JSON_ID)); title = obj.getString(Poll.JSON_TITLE); desc = obj.getString(Poll.JSON_DESC); // Must deserialize encryption parameters before deserializing // talliers! group = Group.fromString(obj.getString(Poll.JSON_GROUP)); g = group.elementFromString(obj.getString(Poll.JSON_LITTLE_G)); G = group.elementFromString(obj.getString(Poll.JSON_BIG_G)); voters = JSONUtils.fromArray(obj.getJSONArray(Poll.JSON_VOTERS)); talliers = JSONUtils .fromArray(obj.getJSONArray(Poll.JSON_TALLIERS)); } catch (IllegalArgumentException e) { JSONException e2 = new JSONException("Invalid Poll"); e2.initCause(e); throw e2; } } /** * Get the unique ID assigned to this poll. The poll can be referenced using * this ID. See {@link PollDB}. * * @return the id */ public UUID getId() { return id; } /** * Gets the title of this poll, used to identify the poll to users. * * @return the title */ public String getTitle() { return title; } /** * Gets the description of this poll, used to describe the poll to users. * * @return a description of the poll */ public String getDesc() { return desc; } /** * Returns the group used for cryptography in this poll * * @return A Group */ public Group getGroup() { return group; } /** * Return one of the generators of the group (see {@link #getGroup()}). This * is the generator denoted by <i>g</i>. * * @return <i>g</i> */ public GroupElement getg() { return g; } /** * Return the other generator of the group (see {@link #getGroup()}. This is * the generator denoted by <i>G</i>. * * @return <i>G</i> */ public GroupElement getG() { return G; } /** * Returns an (unmodifiable) list of voters in this poll. * * @return list of voters */ public List<String> getVoters() { return voters; } public List<String> getTalliers() { return talliers; } /** * Saves a new list of voters for this poll. This will fail if the poll * already has voters assigned to it. It is intended only for use with the * constructor that does not specify voters (see {@link Poll(UUID, String, * String, Group, GroupElement, GroupElement)}) * * @param voters */ public void setVoters(List<String> voters) { if (this.voters != null) { throw new IllegalStateException("Poll already has voters set"); } this.voters = Collections.unmodifiableList(voters); } /** * Saves a new list of talliers for this poll. This will fail if the poll * already has talliers assigned to it. It is intended only for use with the * constructor that does not specify talliers (see {@link Poll(UUID, String, * String, Group, GroupElement, GroupElement)}) * * @param voters */ public void setTalliers(List<String> talliers) { if (this.talliers != null) { throw new IllegalStateException("Poll already has talliers set"); } this.talliers = Collections.unmodifiableList(talliers); } @Override public JSONObject toJson() throws JSONException { JSONObject obj = new JSONObject(); obj.put(Poll.JSON_ID, id.toString()); obj.put(Poll.JSON_TITLE, title); obj.put(Poll.JSON_DESC, desc); obj.put(Poll.JSON_VOTERS, JSONUtils.toStringArray(voters)); obj.put(Poll.JSON_TALLIERS, JSONUtils.toStringArray(talliers)); obj.put(Poll.JSON_GROUP, group.toString()); obj.put(Poll.JSON_LITTLE_G, g.toString()); obj.put(Poll.JSON_BIG_G, G.toString()); return obj; } public void registerFileForDeletion(File extFile) { filesToDelete.add(extFile); } public void deleteFiles() { for (File f : filesToDelete) { f.delete(); } } }
true
ef8c25c75913101b46734c80c64fb499e30fe92d
Java
HanCheng/PrivateWords
/app/src/main/java/com/hancheng/privatewords/util/Utils.java
UTF-8
431
2.609375
3
[]
no_license
package com.hancheng.privatewords.util; import java.util.EnumMap; import java.util.Map; /** * Created by chan on 4/28/15. */ public class Utils { public enum FontType { LIGHT, MEDIUM, REGULAR, BOLD } private static final Map<FontType, String> sFontMap = new EnumMap<FontType, String>(FontType.class); static { sFontMap.put(FontType.LIGHT, "Roboto-Light.ttf"); } }
true
b0b8aa1e7f5ae70558f525d9669e64ddeee5eba9
Java
samuelcleiton/JogoDasPalavrasEmbaralhadas
/src/JogoCincoTentativas.java
UTF-8
607
3.015625
3
[]
no_license
import java.util.Objects; public class JogoCincoTentativas extends Jogo { public JogoCincoTentativas() { tentativas = 5; } @Override public boolean fimDoJogo() { if (tentativas <= 0 || level >= MecanicaDoJogo.levelParaConcluir) return true; return false; } @Override public void mensagemInicial() { System.out.println("\n>> JOGO DAS 5 TENTATIVAS \n"); } @Override public void responder(String palavra) { if (Objects.equals(palavra,palavraAtual)) { pontos += multiplicadorPontos(); level++; } else { tentativas--; } } }
true
b79813ef5e6eea9e38e3164efef88b42ceea2c71
Java
Nafisa-A-Ahmed/SuperMarioBros
/app/src/main/java/com/example/supermariobros/Camera.java
UTF-8
1,718
2.5625
3
[]
no_license
package com.example.supermariobros; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; public class Camera extends View { static World world; EnvironmentalEngine game; MainActivity active; Context context; Thread camView; //SurfaceHolder holder; //Canvas cam; public Camera(Context context, AttributeSet attributeSet){//Constructor super(context, attributeSet); this.context = context; active = (MainActivity) context; world = new World(); game = new EnvironmentalEngine(context, world); camView = new Thread(game); camView.start();/**/ } public static World getWorld(){ return world; } @Override protected void onDraw(Canvas cam){ //cam.drawARGB(255, 150, 150, 10); world.draw(cam); if(world.isNextLevel()){ world = new World(world.getCurrentLevel()+1, world.getMario()); game = new EnvironmentalEngine(context, world); camView = new Thread(game); camView.start(); active.getLevelView().setText("Level: " + Integer.toString(world.getCurrentLevel())); }//if if(world.isLevelReset()){ world = new World(world.getCurrentLevel(), world.getMario()); game = new EnvironmentalEngine(context, world); camView = new Thread(game); camView.start(); active.getLevelView().setText("Level: " + Integer.toString(world.getCurrentLevel())); }//if /**/ invalidate(); }// Draw // 20x12 }// class Camera /* EOF */
true
ef4c45e90ec78448e7550d26f23326a0fc4c58c1
Java
Yg0R2/DataManipulator
/src/main/java/yg0r2/dm/entry/DataManipulatorEntry.java
UTF-8
1,233
1.984375
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2016 Yg0R2 * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ package yg0r2.dm.entry; import java.util.List; import yg0r2.dm.liferay.LiferayUtilMethod; import yg0r2.dm.mvc.displayfield.DisplayField; /** * @author Yg0R2 */ public class DataManipulatorEntry { private LiferayUtilMethod _addEntryMethod; private List<DisplayField> _dDisplayFields; private LiferayUtilMethod _updateEntryMethod; public DataManipulatorEntry(List<DisplayField> displayFields, LiferayUtilMethod addMethod, LiferayUtilMethod updateMethod) { _dDisplayFields = displayFields; _addEntryMethod = addMethod; _updateEntryMethod = updateMethod; } public List<DisplayField> getDisplayFields() { return _dDisplayFields; } }
true
5b63b32fe466f73450aa0f6886082c12df093e9a
Java
wangpeijian/weixin_92ys
/web_api_v2.0/src/main/java/com/ys/mvc/service/OrderService.java
UTF-8
460
1.867188
2
[]
no_license
package com.ys.mvc.service; import com.ys.mvc.dao.pojo.Order; import com.ys.mvc.dao.pojo.Pageable; import com.ys.mvc.dao.pojo.User; import java.util.List; /** * Created by peijian.wang on 2017/6/18. */ public interface OrderService { Pageable<Order> getList(Pageable<Order> pageable, User user); List<Order> getUserOrder(User user); void addOrder(Order order); void closeOrder(Order order); Order getOrderDetail(Order order); }
true
ebd4c1f0e69ab3083afc1f491b5412ef9e5f8512
Java
morningblu/HWFramework
/Mate20-9.0/src/main/java/com/huawei/wallet/sdk/business/buscard/impl/SPIOperatorManager.java
UTF-8
910
2.203125
2
[]
no_license
package com.huawei.wallet.sdk.business.buscard.impl; import android.content.Context; import android.os.Handler; import android.util.SparseArray; import com.huawei.wallet.sdk.business.buscard.cloudtransferout.serveraccess.ServerAccessImp; public class SPIOperatorManager { private final Object lock = new Object(); private final SparseArray<TrafficCardOperator> mTrafficCardOperators = new SparseArray<>(); public SPIOperatorManager(Context context, Handler handler) { this.mTrafficCardOperators.put(20, new ServerAccessImp(context)); } public TrafficCardOperator getTrafficCardOpertor(int mode) { TrafficCardOperator trafficCardOperator; synchronized (this.lock) { if (mode == 22) { mode = 20; } trafficCardOperator = this.mTrafficCardOperators.get(mode); } return trafficCardOperator; } }
true
84c946c69fa1e14250785fef45f3b919580329a9
Java
natete/Structural_Design_Patterns
/01_Adapter/src/com/onewingsoft/adapter/definition/Adapter.java
UTF-8
540
2.765625
3
[]
no_license
package com.onewingsoft.adapter.definition; /** * Created by natete on 30/10/16. */ public class Adapter implements Target { private Adaptee instance; public Adapter(String param) { int adaptedParam; try { adaptedParam = Integer.parseInt(param); } catch (NumberFormatException e) { adaptedParam = 0; } this.instance = new Adaptee(adaptedParam); } @Override public String myMethod() { return Integer.toString(instance.specificMethod()); } }
true
0ff5df61541dee3ed0d1e025e709533dee27e6b1
Java
Maylinne/filmklubszov
/src/main/java/fksz/dao/SpotDao.java
UTF-8
278
1.742188
2
[]
no_license
package fksz.dao; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Component; import fksz.domain.Spot; @Component public interface SpotDao extends CrudRepository<Spot, Integer> { Spot findById(Integer id); }
true
55cdf647f853f3552dc22cb72c24c031e6299295
Java
qingjianmoxie/project
/common/src/main/java/com/bob/common/utils/excelmapping/exception/MappingExceptionResolver.java
UTF-8
804
2.28125
2
[]
no_license
package com.bob.common.utils.excelmapping.exception; /** * 映射异常处理器 * * @author dell-7359 * @create 2017-10-22 10:31 */ public interface MappingExceptionResolver { /** * 是否在Excel上直接编辑错误信息 * * @return */ default boolean excelEditorMode() { return false; } /** * 处理单元格数据类型与属性类型不匹配异常 * * @param ex * @return 是否继续解析 * @throws Exception */ boolean handleCellTypeMismatch(ExcelMappingException ex) throws Exception; /** * 处理行唯一性冲突异常 * * @param ex * @return 是否继续解析 * @throws Exception */ boolean handleRowUniqueConflict(ExcelMappingException ex) throws Exception; }
true
5087b236534a28caed17a30b5838d23abb4dc05f
Java
KYUNGSUB/myserver
/myserver/src/com/talanton/service/myweb/xmpp/EchoProcessor.java
UTF-8
1,546
1.835938
2
[]
no_license
/* * Modifications Copyright 2016 Nimrod Dayan * * Copyright 2014 Wolfram Rittmeyer. * * Portions Copyright Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.talanton.service.myweb.xmpp; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; import com.talanton.service.myweb.xmpp.messages.UpstreamMessage; /** * Handles an echo request. */ public class EchoProcessor implements PayloadProcessor { private JsonAdapter<UpstreamMessage.Response> mUpstreamResponseAdapter; @Override public void handleMessage(UpstreamMessage.Request msg) { PseudoDao dao = PseudoDao.getInstance(); CcsClient client = CcsClient.getInstance(); String msgId = dao.getUniqueMessageId(); // added by ksseo Moshi moshi = new Moshi.Builder().build(); mUpstreamResponseAdapter = moshi.adapter(UpstreamMessage.Response.class); String json = mUpstreamResponseAdapter.toJson(new UpstreamMessage.Response(msg.getFrom(), msgId)); client.send(json); } }
true
ef10cce320e1f6ad4341e04b8ea8d160dec32442
Java
thonnycleuton/GastosViagem
/app/src/main/java/com/thonnycleuton/gastosemviagem/NovaViagem.java
UTF-8
3,277
2.421875
2
[]
no_license
package com.thonnycleuton.gastosemviagem; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.support.annotation.NonNull; import android.support.v4.app.DialogFragment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import com.thonnycleuton.gastosemviagem.DAO.DAO; import com.thonnycleuton.gastosemviagem.modelo.Viagem; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import io.realm.Realm; public class NovaViagem extends AppCompatActivity { public final static String ADDED_NEW_TRIP = NovaViagem.class.getPackage().getName() + ".ADDED_NEW_TRIP"; private String tipo; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nova_viagem); } public void onRadioButtonClicked(View view) { tipo = view.getId() == R.id.radio_tipo_lazer ? "lazer":"negocios"; } public void showDatePickerDialog(View view) { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); } public void salvarViagem(View view) { EditText destino = (EditText) findViewById(R.id.txtDestino); TextView data = (TextView) findViewById(R.id.txtDataViagem); Viagem viagem = new Viagem(); viagem.setDestino(destino.getText().toString()); viagem.setTipoViagem(tipo); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); try { viagem.setData(dateFormat.parse(data.getText().toString())); } catch (ParseException e) { e.printStackTrace(); } DAO.getInstance(Realm.getDefaultInstance()).saveViagem(viagem); //TODO: Decidir se volta pra pagina inicial ou se gera um popup apenas e um backbutton Intent intent = new Intent(this, MainActivity.class); intent.putExtra(ADDED_NEW_TRIP, "Nova Viagem adicionada com successo"); startActivity(intent); } public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); return new DatePickerDialog(getActivity(), this, year, month, day); } @Override public void onDateSet(DatePicker datePicker, int year, int month, int day) { final Calendar c = Calendar.getInstance(); c.set(year, month, day); TextView txtDatePicker = (TextView) getActivity().findViewById(R.id.txtDataViagem); SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); txtDatePicker.setText(dateFormat.format(c.getTime())); } } }
true
38fbde8b6b4c98e42a9429ef169d51edaebcffb1
Java
cspela/upravljalko
/UpravljavecDelavcev/src/upravljalko/DodajPovezavo.java
UTF-8
17,981
2.21875
2
[]
no_license
package upravljalko; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /* * 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. */ /** * * @author spelacucko */ public class DodajPovezavo extends javax.swing.JFrame { /** * Creates new form dodajPovezavo */ Povezovanje pov = new Povezovanje(); Skupina sku = new Skupina(); Delavec del = new Delavec(); public static void resetComboDelavec() throws ClassNotFoundException, SQLException{ Delavec del = new Delavec(); if(jComboBox_IdDelavca != null){ jComboBox_IdDelavca.removeAllItems(); del.izpisDelavcevComboBox(jComboBox_IdDelavca); } } public static void resetComboSkupina() throws ClassNotFoundException, SQLException{ Skupina sku = new Skupina(); if(jComboBox_IdSkupine != null){ jComboBox_IdSkupine.removeAllItems(); sku.izpisSkupinComboBox(jComboBox_IdSkupine); } } public DodajPovezavo() throws ClassNotFoundException, SQLException { initComponents(); sku.izpisSkupinComboBox(jComboBox_IdSkupine); del.izpisDelavcevComboBox(jComboBox_IdDelavca); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jFrame1 = new javax.swing.JFrame(); jPanel1 = new javax.swing.JPanel(); dodaj = new javax.swing.JButton(); jTextField_ime = new javax.swing.JTextField(); jTextField_priimek = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); preklici = new javax.swing.JButton(); jComboBox_IdSkupine = new javax.swing.JComboBox(); jLabel3 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jComboBox_IdDelavca = new javax.swing.JComboBox(); dodaj1 = new javax.swing.JButton(); preklici1 = new javax.swing.JButton(); jLabel6 = new javax.swing.JLabel(); jFrame1.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); dodaj.setText("Dodaj"); dodaj.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { dodajActionPerformed(evt); } }); jTextField_ime.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField_imeActionPerformed(evt); } }); jLabel1.setText("Ime:"); jLabel2.setText("Priimek:"); jLabel4.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jLabel4.setText("Dodaj novega delavca"); preklici.setText("Prekliči"); preklici.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { prekliciActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup() .addGap(43, 43, 43) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1) .addGap(24, 24, 24))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTextField_priimek) .addComponent(jTextField_ime))) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(94, 94, 94) .addComponent(preklici, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(dodaj))) .addGap(43, 43, 43)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap(46, Short.MAX_VALUE) .addComponent(jLabel4) .addContainerGap(46, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(jLabel4) .addGap(32, 32, 32) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_ime, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel1)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField_priimek, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2)) .addGap(12, 12, 12) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(dodaj) .addComponent(preklici)) .addGap(40, 40, 40)) ); javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane()); jFrame1.getContentPane().setLayout(jFrame1Layout); jFrame1Layout.setHorizontalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jFrame1Layout.setVerticalGroup( jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jComboBox_IdSkupine.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox_IdSkupineActionPerformed(evt); } }); jLabel3.setText("Skupina:"); jLabel5.setText("Delavec:"); jComboBox_IdDelavca.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jComboBox_IdDelavcaActionPerformed(evt); } }); dodaj1.setText("Dodaj"); dodaj1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { dodaj1ActionPerformed(evt); } }); preklici1.setText("Prekliči"); preklici1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { preklici1ActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N jLabel6.setText("Dodaj delavca v skupino"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(preklici1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(dodaj1, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(43, 43, 43) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel3) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jComboBox_IdSkupine, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jComboBox_IdDelavca, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) .addGap(43, 43, 43)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(0, 36, Short.MAX_VALUE) .addComponent(jLabel6) .addContainerGap(33, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(jLabel6) .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jComboBox_IdDelavca, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(jComboBox_IdSkupine, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(12, 12, 12) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(preklici1) .addComponent(dodaj1)) .addGap(40, 40, 40)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void dodajActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dodajActionPerformed }//GEN-LAST:event_dodajActionPerformed private void jTextField_imeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField_imeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField_imeActionPerformed private void prekliciActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_prekliciActionPerformed this.dispose(); }//GEN-LAST:event_prekliciActionPerformed private void jComboBox_IdSkupineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_IdSkupineActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBox_IdSkupineActionPerformed private void jComboBox_IdDelavcaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox_IdDelavcaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jComboBox_IdDelavcaActionPerformed private int pridobiIdDelavca() throws ClassNotFoundException, SQLException{ String imePriimek = (String) jComboBox_IdDelavca.getSelectedItem(); String[] splitImePriimek = imePriimek.split(" "); String ime = splitImePriimek[0]; String priimek = splitImePriimek[1]; int delavec_id = del.getIdDelavca(ime, priimek); return delavec_id; } private int pridobiIdSkupine() throws ClassNotFoundException, SQLException{ String nazivSkupine = (String) jComboBox_IdSkupine.getSelectedItem(); int skupina_id = sku.getIdSkupine(nazivSkupine); return skupina_id; } private void dodaj1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dodaj1ActionPerformed try { int delavec_id = pridobiIdDelavca(); int skupina_id = pridobiIdSkupine(); if(pov.clanstvo('c', delavec_id, skupina_id, null)){ JOptionPane.showMessageDialog(null, "Delavec je že član te skupine."); }else if(pov.clanstvo('e', delavec_id, skupina_id, null)){ JOptionPane.showMessageDialog(null, "Delavec je že bil član skupine. Vsak delavec je lahko član iste skupine samo enkrat."); }else{ pov.dodajOdstraniPovezavo('i', delavec_id, skupina_id, null); MainForm.resetirajTabelo(""); IzbrisiPovezavo.resetirajTabelo(""); } } catch (ClassNotFoundException ex) { } catch (SQLException ex) { Logger.getLogger(IzbrisiPovezavo.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_dodaj1ActionPerformed private void preklici1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_preklici1ActionPerformed this.dispose(); }//GEN-LAST:event_preklici1ActionPerformed /** * @param args the command line arguments */ // public static void main(String args[]) { // /* Set the Nimbus look and feel */ // //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> // /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. // * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html // */ // try { // for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { // if ("Nimbus".equals(info.getName())) { // javax.swing.UIManager.setLookAndFeel(info.getClassName()); // break; // } // } // } catch (ClassNotFoundException ex) { // java.util.logging.Logger.getLogger(DodajPovezavo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (InstantiationException ex) { // java.util.logging.Logger.getLogger(DodajPovezavo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (IllegalAccessException ex) { // java.util.logging.Logger.getLogger(DodajPovezavo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } catch (javax.swing.UnsupportedLookAndFeelException ex) { // java.util.logging.Logger.getLogger(DodajPovezavo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); // } // //</editor-fold> // //</editor-fold> // // /* Create and display the form */ // java.awt.EventQueue.invokeLater(new Runnable() { // public void run() { // try { // new DodajPovezavo().setVisible(true); // } catch (ClassNotFoundException ex) { // Logger.getLogger(DodajPovezavo.class.getName()).log(Level.SEVERE, null, ex); // } // } // }); // } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton dodaj; private javax.swing.JButton dodaj1; public static javax.swing.JComboBox jComboBox_IdDelavca; public static javax.swing.JComboBox jComboBox_IdSkupine; private javax.swing.JFrame jFrame1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JTextField jTextField_ime; private javax.swing.JTextField jTextField_priimek; private javax.swing.JButton preklici; private javax.swing.JButton preklici1; // End of variables declaration//GEN-END:variables }
true