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
125fc93704c66c71832bc3dd3afec7ae755c19c9
Java
guruguha/incubator-pinot
/pinot-core/src/main/java/org/apache/pinot/core/query/pruner/ColumnValueSegmentPruner.java
UTF-8
9,078
2.0625
2
[ "Apache-2.0", "EPL-1.0", "BSD-3-Clause", "CDDL-1.1", "EPL-2.0", "LicenseRef-scancode-unknown-license-reference", "CDDL-1.0", "MIT", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "CC-BY-2.5", "LicenseRef-scancode-free-unknown", "CPL-1.0", "bzip2-1.0.6", "CC-BY-SA-3.0", "LicenseRef-scancode-unicode", "CC-PDDC", "NAIST-2003", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-other-copyleft", "LGPL-2.0-or-later", "LicenseRef-scancode-proprietary-license" ]
permissive
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.pinot.core.query.pruner; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.pinot.core.common.DataSource; import org.apache.pinot.core.common.DataSourceMetadata; import org.apache.pinot.core.data.partition.PartitionFunction; import org.apache.pinot.core.indexsegment.IndexSegment; import org.apache.pinot.core.query.exception.BadQueryRequestException; import org.apache.pinot.core.query.request.context.ExpressionContext; import org.apache.pinot.core.query.request.context.FilterContext; import org.apache.pinot.core.query.request.context.QueryContext; import org.apache.pinot.core.query.request.context.predicate.EqPredicate; import org.apache.pinot.core.query.request.context.predicate.Predicate; import org.apache.pinot.core.query.request.context.predicate.RangePredicate; import org.apache.pinot.core.segment.index.readers.BloomFilterReader; import org.apache.pinot.spi.data.FieldSpec.DataType; import org.apache.pinot.spi.env.PinotConfiguration; import org.apache.pinot.spi.utils.BytesUtils; /** * The {@code ColumnValueSegmentPruner} is the segment pruner that prunes segments based on the value inside the filter. * <ul> * <li> * For EQUALITY filter, prune the segment based on: * <ul> * <li>Column min/max value</li> * <li>Column partition</li> * <li>Column bloom filter</li> * </ul> * </li> * <li> * For RANGE filter, prune the segment based on: * <ul> * <li>Column min/max value<</li> * </ul> * </li> * </ul> */ @SuppressWarnings({"rawtypes", "unchecked"}) public class ColumnValueSegmentPruner implements SegmentPruner { @Override public void init(PinotConfiguration config) { } @Override public boolean prune(IndexSegment segment, QueryContext query) { FilterContext filter = query.getFilter(); if (filter == null) { return false; } // This map caches the data sources Map<String, DataSource> dataSourceCache = new HashMap<>(); return pruneSegment(segment, filter, dataSourceCache); } private boolean pruneSegment(IndexSegment segment, FilterContext filter, Map<String, DataSource> dataSourceCache) { switch (filter.getType()) { case AND: for (FilterContext child : filter.getChildren()) { if (pruneSegment(segment, child, dataSourceCache)) { return true; } } return false; case OR: for (FilterContext child : filter.getChildren()) { if (!pruneSegment(segment, child, dataSourceCache)) { return false; } } return true; case PREDICATE: Predicate predicate = filter.getPredicate(); // Only prune columns if (predicate.getLhs().getType() != ExpressionContext.Type.IDENTIFIER) { return false; } Predicate.Type predicateType = predicate.getType(); if (predicateType == Predicate.Type.EQ) { return pruneEqPredicate(segment, (EqPredicate) predicate, dataSourceCache); } else if (predicateType == Predicate.Type.RANGE) { return pruneRangePredicate(segment, (RangePredicate) predicate, dataSourceCache); } else { return false; } default: throw new IllegalStateException(); } } /** * For EQ predicate, prune the segment based on: * <ul> * <li>Column min/max value</li> * <li>Column partition</li> * <li>Column bloom filter</li> * </ul> */ private boolean pruneEqPredicate(IndexSegment segment, EqPredicate eqPredicate, Map<String, DataSource> dataSourceCache) { String column = eqPredicate.getLhs().getIdentifier(); DataSource dataSource = dataSourceCache.computeIfAbsent(column, segment::getDataSource); // NOTE: Column must exist after DataSchemaSegmentPruner assert dataSource != null; DataSourceMetadata dataSourceMetadata = dataSource.getDataSourceMetadata(); Comparable value = convertValue(eqPredicate.getValue(), dataSourceMetadata.getDataType()); // Check min/max value Comparable minValue = dataSourceMetadata.getMinValue(); if (minValue != null) { if (value.compareTo(minValue) < 0) { return true; } } Comparable maxValue = dataSourceMetadata.getMaxValue(); if (maxValue != null) { if (value.compareTo(maxValue) > 0) { return true; } } // Check column partition PartitionFunction partitionFunction = dataSourceMetadata.getPartitionFunction(); if (partitionFunction != null) { Set<Integer> partitions = dataSourceMetadata.getPartitions(); assert partitions != null; if (!partitions.contains(partitionFunction.getPartition(value))) { return true; } } // Check bloom filter BloomFilterReader bloomFilter = dataSource.getBloomFilter(); if (bloomFilter != null) { if (!bloomFilter.mightContain(value.toString())) { return true; } } return false; } /** * For RANGE predicate, prune the segment based on: * <ul> * <li>Column min/max value</li> * </ul> */ private boolean pruneRangePredicate(IndexSegment segment, RangePredicate rangePredicate, Map<String, DataSource> dataSourceCache) { String column = rangePredicate.getLhs().getIdentifier(); DataSource dataSource = dataSourceCache.computeIfAbsent(column, segment::getDataSource); // NOTE: Column must exist after DataSchemaSegmentPruner assert dataSource != null; DataSourceMetadata dataSourceMetadata = dataSource.getDataSourceMetadata(); // Get lower/upper boundary value DataType dataType = dataSourceMetadata.getDataType(); String lowerBound = rangePredicate.getLowerBound(); Comparable lowerBoundValue = null; if (!lowerBound.equals(RangePredicate.UNBOUNDED)) { lowerBoundValue = convertValue(lowerBound, dataType); } boolean lowerInclusive = rangePredicate.isLowerInclusive(); String upperBound = rangePredicate.getUpperBound(); Comparable upperBoundValue = null; if (!upperBound.equals(RangePredicate.UNBOUNDED)) { upperBoundValue = convertValue(upperBound, dataType); } boolean upperInclusive = rangePredicate.isUpperInclusive(); // Check if the range is valid // TODO: This check should be performed on the broker if (lowerBoundValue != null && upperBoundValue != null) { if (lowerInclusive && upperInclusive) { if (lowerBoundValue.compareTo(upperBoundValue) > 0) { return true; } } else { if (lowerBoundValue.compareTo(upperBoundValue) >= 0) { return true; } } } // Check min/max value Comparable minValue = dataSourceMetadata.getMinValue(); if (minValue != null) { if (upperBoundValue != null) { if (upperInclusive) { if (upperBoundValue.compareTo(minValue) < 0) { return true; } } else { if (upperBoundValue.compareTo(minValue) <= 0) { return true; } } } } Comparable maxValue = dataSourceMetadata.getMaxValue(); if (maxValue != null) { if (lowerBoundValue != null) { if (lowerInclusive) { if (lowerBoundValue.compareTo(maxValue) > 0) { return true; } } else { if (lowerBoundValue.compareTo(maxValue) >= 0) { return true; } } } } return false; } private static Comparable convertValue(String stringValue, DataType dataType) { try { switch (dataType) { case INT: return Integer.valueOf(stringValue); case LONG: return Long.valueOf(stringValue); case FLOAT: return Float.valueOf(stringValue); case DOUBLE: return Double.valueOf(stringValue); case STRING: return stringValue; case BYTES: return BytesUtils.toByteArray(stringValue); default: throw new IllegalStateException(); } } catch (Exception e) { throw new BadQueryRequestException(String.format("Cannot convert value: '%s' to type: %s", stringValue, dataType), e); } } }
true
a1c65477643fba466923a3ed9bca4c6c2ae71665
Java
liweisnake/isi
/src/test/java/skynet/isi/service/impl/ImportDataServiceImplTest.java
UTF-8
1,256
2.046875
2
[]
no_license
package skynet.isi.service.impl; import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import skynet.isi.DBEnablerTestBase; import skynet.isi.service.ModifyDataService; @ContextConfiguration(locations = { "/applicationContext.xml" }) @RunWith(SpringJUnit4ClassRunner.class) @ActiveProfiles("test") public class ImportDataServiceImplTest extends DBEnablerTestBase { @Autowired ModifyDataService update; @Override public String dataSetFileName() { return "clear.xml"; } @Test public void testImport() { try { int t1 = (int) System.currentTimeMillis(); List<String> failed = update.process("65-3.xls", false); int t2 = (int) System.currentTimeMillis(); System.out.println("Total time is: " + (t2 - t1)); for (String msg : failed) System.out.println(msg); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
true
ce0f9c10096163072878148c2f6bbe16b81a06b4
Java
RainerJava/gl_shop
/gl_shop_datas/src/main/java/com/appabc/datas/dao/order/IOrderFindMatchDAO.java
UTF-8
2,198
1.945313
2
[]
no_license
package com.appabc.datas.dao.order; import java.util.List; import com.appabc.bean.enums.OrderFindInfo.OrderFindMatchStatusEnum; import com.appabc.bean.pvo.TOrderFindMatch; import com.appabc.bean.pvo.TOrderFindMatchEx; import com.appabc.common.base.QueryContext; import com.appabc.common.base.dao.IBaseDao; import com.appabc.datas.exception.ServiceException; /** * @Description : * @Copyright : GL. All Rights Reserved * @Company : 江苏国立网络技术有限公司 * @author : 黄建华 * @version : 1.0 * @Create_Date : 2015年4月30日 下午4:43:53 */ public interface IOrderFindMatchDAO extends IBaseDao<TOrderFindMatch> { /** * @description 根据状态和所有者查询询单匹配信息 * @param owner,status * @return List<TOrderFindMatch> * @since 1.0 * @throws null * @author Bill Huang * */ List<TOrderFindMatch> queryOrderFindMatchInfoWithStatus(String owner,OrderFindMatchStatusEnum status); /** * @description 根据状态和所有者查询询单匹配信息 * @param owner,status * @return List<TOrderFindMatch> * @since 1.0 * @throws null * @author Bill Huang * */ List<TOrderFindMatchEx> queryOrderFindMatchExInfoWithStatus(String owner,OrderFindMatchStatusEnum status); /** * @Description : 分页查询撮合保存信息列表 * @param qContext * @return QueryContext<TOrderFindMatchEx> * @since 1.0 * @throws null * @author Bill Huang * */ QueryContext<TOrderFindMatchEx> findOrderFindMatchExInfoForPagination(QueryContext<TOrderFindMatchEx> qContext); /** * @description 根据父询单ID和状态更新匹配信息 * @param parentFId,status * @return void * @since 1.0 * @throws ServiceException * @author Bill Huang * */ void updateOrderFindMatchStatusByPFid(String parentFId,OrderFindMatchStatusEnum status) throws ServiceException; /** * @description 根据rid和状态更新匹配信息 * @param rid,status * @return void * @since 1.0 * @throws ServiceException * @author Bill Huang * */ void updateOrderFindMatchStatusByRid(String rid,OrderFindMatchStatusEnum status) throws ServiceException; }
true
43be9420ed34fe25e554f1c2c91f397e3d3588db
Java
ShaneLC/iHelin
/src/main/java/me/ianhe/utils/WechatUtil.java
UTF-8
12,045
1.859375
2
[ "MIT" ]
permissive
package me.ianhe.utils; import com.google.common.collect.Lists; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.core.util.QuickWriter; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import com.thoughtworks.xstream.io.xml.PrettyPrintWriter; import com.thoughtworks.xstream.io.xml.XppDriver; import me.ianhe.model.Button; import me.ianhe.model.ClickButton; import me.ianhe.model.Menu; import me.ianhe.model.ViewButton; import me.ianhe.model.WXAccessToken; import me.ianhe.model.req.LocationMessage; import me.ianhe.model.resp.Article; import me.ianhe.model.resp.ImageMessage; import me.ianhe.model.resp.MusicMessage; import me.ianhe.model.resp.NewsMessage; import me.ianhe.model.resp.TextMessage; import org.apache.commons.lang3.CharEncoding; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.io.InputStream; import java.io.Writer; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * 微信常用工具类 * <p> * Created by iHelin on 16/11/4. */ public class WechatUtil { public static final String MESSAGE_TEXT = "text"; public static final String MESSAGE_NEWS = "news"; public static final String MESSAGE_IMAGE = "image"; public static final String MESSAGE_VOICE = "voice"; public static final String MESSAGE_MUSIC = "music"; public static final String MESSAGE_VIDEO = "video"; public static final String MESSAGE_LINK = "link"; public static final String MESSAGE_LOCATION = "location"; public static final String MESSAGE_EVNET = "event"; public static final String MESSAGE_SUBSCRIBE = "subscribe"; public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe"; public static final String MESSAGE_CLICK = "CLICK"; public static final String MESSAGE_VIEW = "VIEW"; public static final String MESSAGE_SCANCODE = "scancode_push"; private static final String MEDIA_COUNT_URL = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=ACCESS_TOKEN"; private static final String GET_MEDIA_URL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN"; private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; private static final String UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE"; private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN"; private static final String QUERY_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCESS_TOKEN"; private static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN"; private static final Logger LOGGER = LoggerFactory.getLogger(WechatUtil.class); // get请求,返回String public static String doGetStr(String url) { HttpGet httpGet = new HttpGet(url); try { DefaultHttpClient client = new DefaultHttpClient(); HttpResponse httpResponse = client.execute(httpGet); HttpEntity entity = httpResponse.getEntity(); return EntityUtils.toString(entity, CharEncoding.UTF_8); } catch (Exception e) { LOGGER.warn("error while doGet url:" + url, e); return null; } finally { httpGet.releaseConnection(); } } // post请求 public static String doPostStr(String url, String outStr) { HttpPost httpPost = new HttpPost(url); try { DefaultHttpClient client = new DefaultHttpClient(); HttpEntity reqEntity = new StringEntity(outStr, ContentType.APPLICATION_JSON); httpPost.setEntity(reqEntity); HttpResponse response = client.execute(httpPost); HttpEntity respEntity = response.getEntity(); return EntityUtils.toString(respEntity, CharEncoding.UTF_8); } catch (Exception e) { LOGGER.warn("error while doPost url:" + url, e); return null; } finally { httpPost.releaseConnection(); } } /** * 解析微信发来的请求 xml转为Map * * @param request * @return */ public static Map<String, String> xml2Map(HttpServletRequest request) { Map<String, String> msgMap = new HashMap<>();// 将解析结果存储在Map中 // 从request中取得输入流 try (InputStream inStream = request.getInputStream()) { SAXReader reader = new SAXReader(); Document doc = reader.read(inStream); Element root = doc.getRootElement();// 得到xml根元素 List<Element> elementList = root.elements();// 得到根元素的所有子节点 // 遍历所有子节点 for (Element e : elementList) { msgMap.put(e.getName(), e.getText()); } } catch (Exception e) { LOGGER.warn("error to load xml", e); return msgMap; } return msgMap; } // 获取微信access_token public static WXAccessToken getAccessToken(String appId, String secret) { if (StringUtils.isBlank(appId) || StringUtils.isBlank(secret)) { throw new RuntimeException("appId or secret is empty,please check your configuration!"); } String url = ACCESS_TOKEN_URL.replace("APPID", appId).replace("APPSECRET", secret); String res = doGetStr(url); WXAccessToken token = JSON.parseObject(res, WXAccessToken.class); LOGGER.info("从微信服务器获取token成功,有效期为" + token.getExpires_in() + "秒"); return token; } /** * 文本消息组装 * * @param toUserName * @param fromUserName * @param content * @return */ public static String sendTextMsg(String toUserName, String fromUserName, String content) { TextMessage text = new TextMessage(); text.setFromUserName(toUserName); text.setToUserName(fromUserName); text.setMsgType(MESSAGE_TEXT); text.setCreateTime(System.currentTimeMillis()); text.setContent(content); xstream.alias("xml", TextMessage.class); return xstream.toXML(text); } /** * 图文消息组装 * * @param toUserName * @param fromUserName * @return */ public static String sendArticleMsg(String toUserName, String fromUserName, NewsMessage newsMessage) { newsMessage.setToUserName(fromUserName); newsMessage.setFromUserName(toUserName); xstream.alias("xml", NewsMessage.class); xstream.alias("item", Article.class); return xstream.toXML(newsMessage); } /** * 图片消息组装 * * @param toUserName * @param fromUserName * @return */ public static String sendImageMsg(String toUserName, String fromUserName, ImageMessage imageMessage) { imageMessage.setFromUserName(toUserName); imageMessage.setToUserName(fromUserName); xstream.alias("xml", ImageMessage.class); return xstream.toXML(imageMessage); } /** * 音乐消息转XML * * @param musicMessage * @return */ public static String musicMessageToXml(MusicMessage musicMessage) { xstream.alias("xml", MusicMessage.class); return xstream.toXML(musicMessage); } public static String map2XML(Map<String, Object> map) { String xml = "<xml>"; Iterator<Map.Entry<String, Object>> iter = map.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, Object> entry = iter.next(); String key = entry.getKey(); String val = entry.getValue().toString(); if (IsNumeric(val)) { xml += "<" + key + ">" + val + "</" + key + ">"; } else xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">"; } xml += "</xml>"; return xml; } /** * 扩展xstream,使其支持CDATA块 */ private static XStream xstream = new XStream(new XppDriver() { public HierarchicalStreamWriter createWriter(Writer out) { return new PrettyPrintWriter(out) { public void startNode(String name, Class clazz) { super.startNode(name, clazz); } protected void writeText(QuickWriter writer, String text) { if (IsNumeric(text)) { writer.write(text); } else { writer.write("<![CDATA["); writer.write(text); writer.write("]]>"); } } }; } }); /** * 判断是否为number * * @param str * @return */ public static boolean IsNumeric(String str) { try { Long.parseLong(str); } catch (Exception e) { return false; } return true; } // 组装菜单 public static Menu initMenu() { Menu menu = new Menu(); List<Button> buttons = Lists.newArrayList(); ClickButton button11 = new ClickButton(); button11.setName("click菜单"); button11.setType("click"); button11.setKey("11"); buttons.add(button11); ViewButton button2 = new ViewButton(); button2.setName("官方网站"); button2.setType("view"); button2.setUrl("http://www.tcqcw.cn"); buttons.add(button2); List<Button> subButtons = Lists.newArrayList(); ClickButton button31 = new ClickButton(); button31.setName("扫码"); button31.setType("scancode_push"); button31.setKey("31"); subButtons.add(button31); ClickButton button32 = new ClickButton(); button32.setName("地理位置"); button32.setType("location_select"); button32.setKey("32"); subButtons.add(button32); Button button = new Button(); button.setName("新菜单"); button.setSub_button(subButtons); buttons.add(button); menu.setButton(buttons); return menu; } // 创建菜单 public static String createMenu(String accessToken, String menu) { String url = CREATE_MENU_URL.replace("ACCESS_TOKEN", accessToken); return doPostStr(url, menu); } // 查询菜单 public static String queryMenu(String token) { String url = QUERY_MENU_URL.replace("ACCESS_TOKEN", token); return doGetStr(url); } // 删除菜单 public static String deleteMenu(String token) { String url = DELETE_MENU_URL.replace("ACCESS_TOKEN", token); return doGetStr(url); } // 组装地理位置消息 public static LocationMessage MapToLocation(Map<String, String> map) { LocationMessage location = new LocationMessage(); location.setLabel(map.get("Label")); location.setLocation_X(map.get("Location_X")); location.setLocation_Y(map.get("Location_Y")); location.setScale(Integer.parseInt(map.get("Scale"))); location.setMsgId(Long.valueOf(map.get("MsgId"))); return location; } private WechatUtil() { //工具类不允许实例化 } }
true
8a7ea92822a7815f1aa9149de4363911f3d6e53d
Java
mandres26/sigedu
/sigedu/sigedu/src/main/java/pe/com/consultisoft/service/administrativo/DocenteService.java
UTF-8
393
1.851563
2
[]
no_license
package pe.com.consultisoft.service.administrativo; import java.util.List; import pe.com.consultisoft.model.Docente; public interface DocenteService{ public List<Docente> list(); public int add(Docente docente); public int update(Docente docente); public int delete(int int_iddocente); public List<Docente> find(Docente docente); public Docente find(int int_iddocente); }
true
308eec37b9dd263bd51e4f6bd5440fb77150bbf3
Java
spykins/CurrencyCalculator
/app/src/main/java/com/andela/currencycalculator/model/currency/TopTen.java
UTF-8
444
2.578125
3
[ "MIT" ]
permissive
package com.andela.currencycalculator.model.currency; import java.util.ArrayList; /** * Created by Spykins on 04/03/2016. */ public class TopTen { private ArrayList<String> topTen; public TopTen() { topTen = new ArrayList<>(); for (TopTenList topTenList : TopTenList.values()){ topTen.add(topTenList.name()); } } public ArrayList<String> getTopTen(){ return topTen; } }
true
7b8705a449567fcba28f9e66d83d85432c0a0627
Java
Inuyasha-Monster/gulimall-study
/gulimall-ware/src/main/java/com/atguigu/gulimall/ware/listener/StockReleaseListener.java
UTF-8
3,318
2.375
2
[]
no_license
package com.atguigu.gulimall.ware.listener; import com.atguigu.common.to.OrderTo; import com.atguigu.common.to.mq.StockLockedTo; import com.atguigu.gulimall.ware.service.WareSkuService; import com.rabbitmq.client.Channel; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.Message; import org.springframework.amqp.rabbit.annotation.RabbitHandler; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; /** * @Description: 库存解锁的消息队列 * @Created: with IntelliJ IDEA. * @author: djl * @createTime: 2020-07-07 00:20 **/ @Slf4j @RabbitListener(queues = "stock.release.stock.queue") @Service public class StockReleaseListener { @Autowired private WareSkuService wareSkuService; /** * 1、库存自动解锁 * 下订单成功,库存锁定成功,接下来的业务调用失败,导致订单回滚。之前锁定的库存就要自动解锁 * <p> * 2、订单失败 * 库存锁定失败 * <p> * 只要解锁库存的消息失败,一定要告诉服务解锁失败 */ @RabbitHandler public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException { log.info("******收到超时-解锁库存的信息******"); try { //当前消息是否被第二次及以后(重新)派发过来了 // Boolean redelivered = message.getMessageProperties().getRedelivered(); //解锁库存 wareSkuService.unlockStock(to); // 手动删除消息 channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); } catch (Exception e) { log.error("解锁库存出现未知异常", e); // 解锁失败 将消息重新放回队列,让别人消费 channel.basicReject(message.getMessageProperties().getDeliveryTag(), true); } } /** * 订单关闭之后给解锁库存MQ发送一个消息,消费者拿到这个消息进行解锁库存 * 存在的必要性:防止因为程序卡顿,导致超时解锁库存的消息比订单自动关闭先行执行,所以再关闭订单的时候有必要再进行库存的解锁操作来确保一定能够解锁成功 * * @param orderTo * @param message * @param channel * @throws IOException */ @RabbitHandler public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException { log.info("******收到订单关闭-准备解锁库存的信息******"); // 消费者需要进行可靠的消息消费,进行ack机制的运用 try { wareSkuService.unlockStock(orderTo); // 手动删除消息 channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); } catch (Exception e) { // 解锁失败 将消息重新放回队列,让别人消费 // 如果这行代码出现了问题,你觉的此条消息会回到MQ Broker里面吗?回答:会的 channel.basicReject(message.getMessageProperties().getDeliveryTag(), true); } } }
true
74279a35acb021db427cb873ec2c043a0e01b08e
Java
CaptainMayonnaise/HexiGames
/src/com/hexicraft/games/commands/GameCreateCommand.java
UTF-8
1,232
2.40625
2
[]
no_license
package com.hexicraft.games.commands; import com.sk89q.worldedit.bukkit.WorldEditPlugin; import com.sk89q.worldedit.bukkit.selections.Selection; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * @author Ollie * @version 1.0 */ public class GameCreateCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { if (sender instanceof Player) { Player player = (Player) sender; WorldEditPlugin worldEdit = (WorldEditPlugin) Bukkit.getServer().getPluginManager().getPlugin("WorldEdit"); Selection selection = worldEdit.getSelection(player); if (selection != null) { World world = selection.getWorld(); Location min = selection.getMinimumPoint(); Location max = selection.getMaximumPoint(); // Do something with min/max } else { // No selection available } } return false; } }
true
4f3e5d75c5d4c6c567b53ac78d6603b00c50118a
Java
prabhjyotsingh/cloudbreak
/redbeams/src/main/java/com/sequenceiq/redbeams/service/validation/DatabaseConnectionValidator.java
UTF-8
832
2.25
2
[ "LicenseRef-scancode-warranty-disclaimer", "ANTLR-PD", "CDDL-1.0", "bzip2-1.0.6", "Zlib", "BSD-3-Clause", "MIT", "EPL-1.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-jdbm-1.00", "Apache-2.0" ]
permissive
package com.sequenceiq.redbeams.service.validation; import org.springframework.stereotype.Component; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.sequenceiq.redbeams.domain.DatabaseConfig; @Component public class DatabaseConnectionValidator extends BaseConnectionValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return DatabaseConfig.class.equals(clazz); } @Override public void validate(Object target, Errors errors) { DatabaseConfig database = (DatabaseConfig) target; validate(database.getConnectorJarUrl(), database.getDatabaseVendor(), database.getConnectionURL(), database.getConnectionUserName().getRaw(), database.getConnectionPassword().getRaw(), errors); } }
true
fe2a61e7f4863c6a68ec7cf9886f41bc8311c780
Java
sparkchain-cn/obcp
/obcp-user/src/main/java/cn/obcp/user/VO/NavsNodeTree.java
UTF-8
3,755
2.515625
3
[ "MIT" ]
permissive
/** * TODO * * * lmf 创建于2018年11月22日 */ package cn.obcp.user.VO; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import cn.obcp.user.domain.TResources; import cn.obcp.user.enmu.ResourceStateEnmu; import cn.obcp.user.enmu.ResourceType; /** * @author lmf * */ public class NavsNodeTree { private String title; //标题 private String value; //id private String icon; //图标 private String href;//链接 private boolean spread; //默认选中 private List<NavsNodeTree> children; //子节点 public NavsNodeTree(String title,String icon,String value, String href,boolean spread,List<NavsNodeTree> children) { this.title = title; this.icon = icon; this.href = href; this.value = value; this.spread = spread; this.children = children; } public NavsNodeTree() { // TODO Auto-generated constructor stub } public static NavsNodeTree create(String title,String icon,String value, String href,boolean spread,List<NavsNodeTree> children) { NavsNodeTree node = new NavsNodeTree(); node.title = title; node.icon = icon; node.value = value; node.href = href; node.spread = spread; node.children = children; return node; } private static NavsNodeTree addChild(List<TResources> list,NavsNodeTree parent) { Iterator<TResources> iterator = list.iterator(); while(iterator.hasNext()){ TResources resources = iterator.next(); if( String.valueOf(resources.getParentid()).equals(parent.getValue())) {//父级id等资源父级id List<NavsNodeTree> childrens = parent.getChildren(); // boolean state = resources.getState().equals(ResourceStateEnmu.DISABLED.getStatus()); List<NavsNodeTree> children = new ArrayList<>(); childrens.add(NavsNodeTree.create(resources.getAliasName(),resources.getIcon(),String.valueOf( resources.getId()),resources.getPath(), false,children)); parent.setChildren(childrens); } } if(parent.getChildren() != null && parent.getChildren().size() > 0) { Iterator<NavsNodeTree> treeitr = parent.getChildren().iterator(); while(treeitr.hasNext()) { NavsNodeTree node = treeitr.next(); addChild(list, node); } }else { return parent; } return parent; } public static List<NavsNodeTree> bulid(List<TResources> list) { List<NavsNodeTree> baseNode = new ArrayList<NavsNodeTree>(); //父节点 list.forEach( r -> { if(r.getParentid() == null && r.getResTypeCode().equalsIgnoreCase(ResourceType.PAGEFOLDER.getType())) { //必须要文件夹佳能作为父级菜单 //boolean state = r.getState().equals(ResourceStateEnmu.DISABLED.getStatus()); List<NavsNodeTree> children = new ArrayList<>(); baseNode.add(NavsNodeTree.create(r.getAliasName(), r.getIcon(), String.valueOf(r.getId()), r.getPath(),false, children)); } }); //得到全部根节点 baseNode.forEach(node ->{ NavsNodeTree current = addChild(list, node); }); return baseNode; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public boolean isSpread() { return spread; } public void setSpread(boolean spread) { this.spread = spread; } public List<NavsNodeTree> getChildren() { return children; } public void setChildren(List<NavsNodeTree> children) { this.children = children; } }
true
4b4b68c023d22a327e0cd6d555ca1b000ffd484e
Java
codpod/Java
/Line/TwoDPoint.java
UTF-8
523
3.484375
3
[]
no_license
/************************************************ This class is called TwoDPoint. It has 2 public data members called x and y and a constructor that accepts two integer arguments and stores them in x and y. *************************************************/ package mcantirelinepackage; public class TwoDPoint { //2 public data members x and y public int x; public int y; //constructor that accepts two ints and stores in x and y public TwoDPoint(int x, int y) { this.x = x; this.y = y; } }
true
bfac9699467e50bd51646be343d901a538cf241c
Java
matejsnoha/linkeddatamap
/app/src/main/java/info/snoha/matej/linkeddatamap/app/gui/fragments/SettingsFragment.java
UTF-8
2,144
2.359375
2
[]
no_license
package info.snoha.matej.linkeddatamap.app.gui.fragments; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import info.snoha.matej.linkeddatamap.Log; import info.snoha.matej.linkeddatamap.R; import info.snoha.matej.linkeddatamap.app.gui.settings.screens.AbstractSettingsScreen; import info.snoha.matej.linkeddatamap.app.gui.settings.screens.GeneralSettingsScreen; import info.snoha.matej.linkeddatamap.app.gui.settings.screens.SettingsScreenRegistry; public class SettingsFragment extends Fragment { private AbstractSettingsScreen screen; public static SettingsFragment getInstance(String screenName) { SettingsFragment fragment = new SettingsFragment(); Bundle arguments = new Bundle(); arguments.putString("screen", screenName); fragment.setArguments(arguments); return fragment; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // root view View rootView = inflater.inflate(R.layout.fragment_settings, container, false); // settings layout ViewGroup settingsLayout = rootView.findViewById(R.id.settings_layout); // settings screen String screenName = getArguments().getString("screen", GeneralSettingsScreen.class.getSimpleName()); screen = SettingsScreenRegistry.get(screenName); if (screen == null) { Log.warn("Invalid settings screen name " + screenName); screen = new GeneralSettingsScreen(getContext()); } // parent activity title getActivity().setTitle(screen.getTitle()); // content if (screen.getParent() != null) { ((ViewGroup) screen.getParent()).removeView(screen); } settingsLayout.addView(screen); return rootView; } public void refresh(){ if (screen != null){ screen.refresh(); } } @Override public void onResume() { super.onResume(); refresh(); } }
true
3647989236a47ade154e8668db21c91f200da7f7
Java
jianlins/EasyCIE_GUI
/src/main/java/edu/utah/bmi/nlp/uima/ae/NERCoordinator_AE.java
UTF-8
3,107
2.3125
2
[ "Apache-2.0", "LicenseRef-scancode-jdom", "EPL-1.0", "GPL-2.0-only" ]
permissive
package edu.utah.bmi.nlp.uima.ae; import edu.utah.bmi.nlp.core.*; import edu.utah.bmi.nlp.uima.ae.RuleBasedAEInf; import org.apache.uima.UimaContext; import org.apache.uima.analysis_component.JCasAnnotator_ImplBase; import org.apache.uima.analysis_engine.AnalysisEngineProcessException; import org.apache.uima.fit.util.JCasUtil; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.tcas.Annotation; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.logging.Logger; /** * Find overlapped annotations with the same annotation type, choose the widest one * * @author Jianlin Shi * Created on 7/6/16. */ public class NERCoordinator_AE extends JCasAnnotator_ImplBase implements RuleBasedAEInf { private static Logger logger = IOUtil.getLogger(edu.utah.bmi.nlp.uima.ae.NERCoordinator_AE.class); public static final String PARAM_RULE_STR = DeterminantValueSet.PARAM_RULE_STR; protected LinkedHashSet<Class> inclusions = new LinkedHashSet<>(); public void initialize(UimaContext cont) { String ruleStr = (String) (cont .getConfigParameterValue(PARAM_RULE_STR)); IOUtil ioUtil = new IOUtil(ruleStr, true); for (ArrayList<String> row : ioUtil.getRuleCells()) { if (row.size() > 1 && row.get(1).trim().length() > 0) { String inclusionTypeName = DeterminantValueSet.checkNameSpace(row.get(1).trim()); try { Class annoCls = Class.forName(inclusionTypeName).asSubclass(Annotation.class); inclusions.add(annoCls); } catch (ClassNotFoundException e) { logger.fine(" NERCoordinator_AE rules contain undefined annotation type: " + row.get(1) + " at row " + row.get(0)); } } } } @Override public void process(JCas jCas) throws AnalysisEngineProcessException { for (Class annoCls : inclusions) { IntervalST<Annotation> existingTree = new IntervalST(); for(Object annoObj:JCasUtil.select(jCas,annoCls)){ Annotation anno = (Annotation) annoObj; checkOverlap(existingTree, anno); } } } /** * Because FastNER and FastCNER may have overlapped matches. * * @param intervalTree * @param concept */ private void checkOverlap(IntervalST<Annotation> intervalTree, Annotation concept) { Interval1D interval = new Interval1D(concept.getBegin(), concept.getEnd()); Iterator<Annotation> overlaps = intervalTree.getAll(interval).iterator(); if(!overlaps.hasNext()){ intervalTree.put(interval, concept); }else { while (overlaps.hasNext()) { Annotation overlapped = overlaps.next(); if (overlapped != null) { if ((overlapped.getEnd() - overlapped.getBegin()) < (concept.getEnd() - concept.getBegin())) { overlapped.removeFromIndexes(); intervalTree.remove(new Interval1D(overlapped.getBegin(), overlapped.getEnd())); intervalTree.put(interval, concept); } else { concept.removeFromIndexes(); } } else { intervalTree.put(interval, concept); } } } } @Override public LinkedHashMap<String, TypeDefinition> getTypeDefs(String ruleStr) { return new LinkedHashMap<>(); } }
true
626d15b0cab53145c1eaf27be19c36f3c2af8ce3
Java
patryk35/nsm
/networkservicesmonitor/src/main/java/pdm/networkservicesmonitor/workers/WebServiceWorker.java
UTF-8
6,608
2.109375
2
[]
no_license
package pdm.networkservicesmonitor.workers; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import pdm.networkservicesmonitor.NetworkServicesMonitorApplication; import pdm.networkservicesmonitor.exceptions.NotFoundException; import pdm.networkservicesmonitor.exceptions.ResourceNotFoundException; import pdm.networkservicesmonitor.model.agent.MonitorAgent; import pdm.networkservicesmonitor.model.agent.Packet; import pdm.networkservicesmonitor.model.data.AgentError; import pdm.networkservicesmonitor.model.data.CollectedLog; import pdm.networkservicesmonitor.model.data.MonitoredParameterValue; import pdm.networkservicesmonitor.model.service.MonitoredParameterType; import pdm.networkservicesmonitor.model.service.Service; import pdm.networkservicesmonitor.payload.agent.packet.AgentDataPacket; import pdm.networkservicesmonitor.repository.*; import pdm.networkservicesmonitor.service.util.DataPacketWrapper; import java.sql.Timestamp; import java.util.Date; @Slf4j @Component("webServiceWorker") @Scope(BeanDefinition.SCOPE_PROTOTYPE) public class WebServiceWorker implements Runnable { @Autowired private ServiceRepository serviceRepository; @Autowired private MonitoredParameterTypeRepository monitoredParameterTypeRepository; @Autowired private MonitoredParametersValuesRepository monitoredParametersValuesRepository; @Autowired private CollectedLogsRepository collectedLogsRepository; @Autowired private PacketRepository packetRepository; @Autowired private AgentErrorRepository agentErrorRepository; private boolean exitNow = false; @Override public void run() { log.trace("Starting worker"); while (!exitNow) { DataPacketWrapper dataPacketWrapper; while ((dataPacketWrapper = NetworkServicesMonitorApplication.getPacketFromQueue()) != null) { AgentDataPacket agentDataPacket = dataPacketWrapper.getAgentDataPacket(); if (packetRepository.existsById(agentDataPacket.getPacketId())) { log.warn("Packet with id %s was proceeded, rejecting"); continue; } MonitorAgent monitorAgent = dataPacketWrapper.getMonitorAgent(); agentDataPacket.getLogs().forEach(serviceLogs -> { Service service = serviceRepository .findById(serviceLogs.getServiceId()) .orElseThrow(() -> new NotFoundException(String.format( "Service %s not found. Service serviceId not valid", serviceLogs.getServiceId().toString())) ); if (!monitorAgent.getId().equals(service.getAgent().getId())) { throw new ResourceNotFoundException(String.format( "agent %s service", service.getAgent().getId()), "id", service.getId() ); } serviceLogs.getLogs().forEach(logEntry -> { CollectedLog collectedLog = new CollectedLog( service, serviceLogs.getPath(), logEntry.getTimestamp(), logEntry.getLog() ); collectedLogsRepository.save(collectedLog); }); }); agentDataPacket.getMonitoring().forEach(serviceMonitoringParameters -> { Service service = serviceRepository .findById(serviceMonitoringParameters.getServiceId()) .orElseThrow(() -> new NotFoundException(String.format( "Service %s not found. Service serviceId not valid", serviceMonitoringParameters.getServiceId().toString())) ); if (!monitorAgent.getId().equals(service.getAgent().getId())) { log.trace(monitorAgent.getId().toString()); log.trace((service.getAgent()).getId().toString()); throw new ResourceNotFoundException(String.format( "agent %s service", service.getAgent().getId()), "id", service.getId() ); } MonitoredParameterType monitoredParameterType = monitoredParameterTypeRepository .findById(serviceMonitoringParameters.getParameterId()) .orElseThrow(() -> new NotFoundException(String.format( "Monitored Parameter %s not found. ParameterId not valid", serviceMonitoringParameters.getParameterId().toString())) ); serviceMonitoringParameters.getMonitoredParameters().forEach(monitoredParameterEntry -> { MonitoredParameterValue monitoredParameterValue = new MonitoredParameterValue( monitoredParameterType, service, monitoredParameterEntry.getTimestamp(), monitoredParameterEntry.getValue() ); monitoredParametersValuesRepository.save(monitoredParameterValue); }); }); agentDataPacket.getAgentErrors().forEach(e -> { agentErrorRepository.save(new AgentError(e.getTimestamp(), e.getMessage(), monitorAgent)); }); packetRepository.save(new Packet(agentDataPacket.getPacketId(), monitorAgent, new Timestamp((new Date()).getTime()))); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } log.trace("Stopping worker"); } public void kill() { exitNow = true; } }
true
709ba3de017194eb15ee29655c6936d261ce632f
Java
laramartin/android_animation_samples
/app/src/main/java/eu/laramartin/uianimationsamples/GridAdapter.java
UTF-8
3,377
2.34375
2
[]
no_license
package eu.laramartin.uianimationsamples; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import butterknife.ButterKnife; import static eu.laramartin.uianimationsamples.AnimationType.EXPLODE; import static eu.laramartin.uianimationsamples.AnimationType.FADE_IN; import static eu.laramartin.uianimationsamples.AnimationType.FADE_IN_OUT; import static eu.laramartin.uianimationsamples.AnimationType.FADE_OUT; import static eu.laramartin.uianimationsamples.AnimationType.SLIDE_DOWN; import static eu.laramartin.uianimationsamples.AnimationType.SLIDE_LEFT; import static eu.laramartin.uianimationsamples.AnimationType.SLIDE_RIGHT; import static eu.laramartin.uianimationsamples.AnimationType.SLIDE_UP; public class GridAdapter extends RecyclerView.Adapter<GridAdapter.GridAdapterViewHolder> { private final int[] animationsList; private final ClickAdapter clickAdapter; public GridAdapter(int[] animationsList, ClickAdapter clickAdapter) { this.animationsList = animationsList; this.clickAdapter = clickAdapter; } @Override public GridAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.grid_item, parent, false); GridAdapterViewHolder viewHolder = new GridAdapterViewHolder(view); return viewHolder; } @Override public void onBindViewHolder(GridAdapterViewHolder holder, int position) { holder.bind(animationsList[position]); } @Override public int getItemCount() { return animationsList.length; } public class GridAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public GridAdapterViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); itemView.setOnClickListener(this); } @Override public void onClick(View view) { clickAdapter.onClickAdapterItem(view, animationsList[getAdapterPosition()]); } public void bind(int animationType) { switch (animationType) { case SLIDE_UP: ((TextView) itemView).setText(R.string.slide_up); break; case SLIDE_DOWN: ((TextView) itemView).setText(R.string.slide_down); break; case SLIDE_LEFT: ((TextView) itemView).setText(R.string.slide_left); break; case SLIDE_RIGHT: ((TextView) itemView).setText(R.string.slide_right); break; case FADE_IN: ((TextView) itemView).setText(R.string.fade_in); break; case FADE_OUT: ((TextView) itemView).setText(R.string.fade_out); break; case FADE_IN_OUT: ((TextView) itemView).setText(R.string.fade_in_out); break; case EXPLODE: ((TextView) itemView).setText(R.string.explode); break; } } } }
true
59f637d5ff38d1bfe2882c00d2e3911b076667c0
Java
luminocean/Distribution
/IndependentSystems/src/retail/bank/ListHistoryResponse.java
UTF-8
1,847
2.125
2
[]
no_license
package retail.bank; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for listHistoryResponse complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="listHistoryResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="recordList" type="{http://bank/}record" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "listHistoryResponse", propOrder = { "recordList" }) public class ListHistoryResponse { protected List<Record> recordList; /** * Gets the value of the recordList property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the recordList property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRecordList().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Record } * * */ public List<Record> getRecordList() { if (recordList == null) { recordList = new ArrayList<Record>(); } return this.recordList; } }
true
3790af125895aff7ad2791a15572d1bb382eef47
Java
cplisboa/sigasBeans
/src/sigas/Gerais.java
ISO-8859-1
3,797
2.484375
2
[]
no_license
package sigas; import java.sql.ResultSet; public class Gerais { public String nome; public String idSistema; public String endereco; public String localidade; public String municipio; public String uf; public String cep; public String utmNorte; public String utmSul; public String latitude; public String longitude; public String outorga_no; public String art; public String tecnico; public String artNo; public String finalidade; public String vazaoOutorgada; public String volumeOut; public String situacao; public String reativadoData; public String obs; public int manutencao; public Gerais() { super(); // TODO Auto-generated constructor stub } // Carregar dados gerais para apresentar na pagina public Gerais fillGerais(String nomePoco) { System.out.println("Recuperando dados do poo de nome: " + nomePoco); Database db = new Database(); String sql = "select * from poco_gerais where nome='"+ nomePoco + "'"; ResultSet rs = db.execQuery(sql); try { if (rs.next()) { localidade = rs.getString("localidade"); endereco = rs.getString("endereco"); municipio = rs.getString("municipio"); uf=rs.getString("uf"); cep=rs.getString("cep"); utmNorte=rs.getString("utm_norte"); utmSul=rs.getString("utm_sul"); latitude=rs.getString("latitude"); longitude=rs.getString("longitude"); outorga_no=rs.getString("outorga_no"); art=rs.getString("art"); tecnico=rs.getString("tecnico"); artNo=rs.getString("art_no"); finalidade=rs.getString("finalidade"); vazaoOutorgada=rs.getString("vazao_outorgada"); volumeOut=rs.getString("volume_outorgado"); situacao=rs.getString("situacao"); reativadoData=rs.getString("reativado_data"); obs=rs.getString("observacoes"); manutencao = rs.getInt("manutencao"); } rs.close(); } catch (Exception e) { System.out.println("Excesso recuperando Gerais"); } db.close(); return this; } public void atualiza() { System.out.println("Atualizao de poo...."); Database db = new Database(); String sql = "update poco_gerais set endereco = '" + endereco + "', " + "localidade='" + localidade +"', " + "municipio='" + municipio +"', " + "uf='" + uf +"', " + "cep='" + cep +"', " + "utm_norte='" + utmNorte +"', " + "utm_sul='" + utmSul +"', " + "latitude='" + latitude +"', " + "longitude='" + longitude +"', " + "outorga_no='" + outorga_no +"', " + "art='" + art +"', " + "tecnico='" + tecnico +"', " + "art_no='" + artNo +"', " + "finalidade='" + finalidade +"', " + "vazao_outorgada='" + vazaoOutorgada +"', " + "volume_outorgado='" + volumeOut +"', " + "manutencao=" + manutencao +", " + "reativado_data='" + reativadoData +"', " + "observacoes='" + obs +"' " + "where nome='" + nome + "'"; System.out.println(sql); try { System.out.println("Executando atualizao de poo"); db.insert(sql); System.out.println("poo atualizado"); } catch(Exception e) { System.out.println("Erro atualizando Poco "+e.getMessage()); } System.out.println("close banco de dados"); db.close(); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Gerais gera = new Gerais(); gera.fillGerais("Superior"); System.out.println(""+gera.municipio); System.out.println(""+gera.latitude); System.out.println(""+gera.cep); System.out.println(""+gera.endereco); System.out.println(""+gera.finalidade); } }
true
824478555f0617c6b61f8109581e76501dc2379c
Java
AhmedGamil/vehicles-status-app
/customer-vehicle-service/src/main/java/com/vehicle/data/store/customer/repository/CustomerRepository.java
UTF-8
260
1.585938
2
[]
no_license
package com.vehicle.data.store.customer.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.vehicle.data.store.customer.model.Customer; public interface CustomerRepository extends JpaRepository<Customer, Long> { }
true
e32ab6876ef0dd04191069a656bd8b262e987cbf
Java
GuillaumeMuret/PosterMaster
/code/android/PosterMaster/app/src/main/java/com/murey/poster/postermaster/communication/requests/EseoGetJuryListRequest.java
UTF-8
4,059
2.0625
2
[]
no_license
package com.murey.poster.postermaster.communication.requests; import android.content.Context; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.murey.poster.postermaster.communication.message.WebMessage; import com.murey.poster.postermaster.communication.message.WebMessageFactory; import com.murey.poster.postermaster.communication.message.data.Member; import com.murey.poster.postermaster.communication.requests.protocole.ProtocolVocabulary; import com.murey.poster.postermaster.model.database.tables.Juries; import com.murey.poster.postermaster.model.database.tables.JuryMembers; import com.murey.poster.postermaster.model.database.tables.JuryProjects; import com.murey.poster.postermaster.model.database.tables.Projects; import com.murey.poster.postermaster.model.database.tables.Teams; import com.murey.poster.postermaster.model.database.tables.Users; import com.murey.poster.postermaster.utils.LogUtils; import retrofit2.Call; import retrofit2.Converter; import retrofit2.Response; import retrofit2.converter.gson.GsonConverterFactory; public class EseoGetJuryListRequest extends EseoBaseRequest { public static final String REQUEST_GET_JURY_LIST ="REQUEST_GET_JURY_LIST"; public static boolean isRequestRunning = false; public EseoGetJuryListRequest(String requestId, boolean isShowLoadingDialog, Context context, Users appUser) { super(requestId, isShowLoadingDialog, context); this.appUsers = appUser; } @Override protected void onSuccess(int responseCode, WebMessage webMessage) { try{ if (webMessage.getResult().equals(ProtocolVocabulary.JSON_RESULT_VALUE_OK)) { // Manage save in databases Juries.updateJuriesReceivedFromEseo(context,webMessage.getJuries()); for(int i=0;i<webMessage.getJuries().length;i++){ JuryMembers.updateRangeJuryMembersReceivedFromEseo( context, webMessage.getJuries()[i].getIdJury(), webMessage.getJuries()[i].getInfo().getMembers() ); Projects.updateProjectReceivedFromEseo(context,webMessage.getJuries()[i].getInfo().getProjects()); for(int j=0;j<webMessage.getJuries()[i].getInfo().getProjects().length;j++){ JuryProjects.updateJuryProjectsFromEseo(context, webMessage.getJuries()[i].getIdJury(), webMessage.getJuries()[i].getInfo().getProjects()[j].getProjectId() ); } } } }catch(NullPointerException npe){ LogUtils.e(LogUtils.DEBUG_TAG,"Exception => ",npe); } } @Override protected String getBaseUrl() { return EseoService.BASE_URL; } @Override protected Class getServiceInterface() { return EseoService.class; } @Override protected Call createCall(Object interfaceObject) { Call call = ((EseoService)interfaceObject).getJuryList( ProtocolVocabulary.PROCESS_LIST_ALL_JURIES_INFO, appUsers.getUsername(), appUsers.getToken() ); LogUtils.d(LogUtils.DEBUG_TAG,"Call = "+call.request().url()); return call; } @Override protected Converter.Factory getConverterFactory() { Gson gson = new GsonBuilder().registerTypeAdapter(WebMessage.class, new WebMessageFactory.WebMessageDeserializer()).create(); return GsonConverterFactory.create(gson); } @Override public void onResponse(Call call, Response response) { super.onResponse(call, response); isRequestRunning = false; } @Override public void onFailure(Call call, Throwable t) { super.onFailure(call, t); isRequestRunning = false; } @Override public void startRequest() { super.startRequest(); isRequestRunning = true; } }
true
0938593c246990fb8ff4e1d1ab217f68ec3d5662
Java
dowsam/rebirth-search-core
/src/main/java/cn/com/rebirth/search/core/index/query/TermFilterParser.java
UTF-8
3,527
2
2
[]
no_license
/* * Copyright (c) 2005-2012 www.china-cti.com All rights reserved * Info:rebirth-search-core TermFilterParser.java 2012-7-6 14:29:48 l.xue.nong$$ */ package cn.com.rebirth.search.core.index.query; import java.io.IOException; import org.apache.lucene.index.Term; import org.apache.lucene.search.Filter; import cn.com.rebirth.commons.xcontent.XContentParser; import cn.com.rebirth.core.inject.Inject; import cn.com.rebirth.search.commons.lucene.search.TermFilter; import cn.com.rebirth.search.core.index.cache.filter.support.CacheKeyFilter; import cn.com.rebirth.search.core.index.mapper.MapperService; import cn.com.rebirth.search.core.index.query.support.QueryParsers; /** * The Class TermFilterParser. * * @author l.xue.nong */ public class TermFilterParser implements FilterParser { /** The Constant NAME. */ public static final String NAME = "term"; /** * Instantiates a new term filter parser. */ @Inject public TermFilterParser() { } /* (non-Javadoc) * @see cn.com.rebirth.search.core.index.query.FilterParser#names() */ @Override public String[] names() { return new String[] { NAME }; } /* (non-Javadoc) * @see cn.com.rebirth.search.core.index.query.FilterParser#parse(cn.com.rebirth.search.core.index.query.QueryParseContext) */ @Override public Filter parse(QueryParseContext parseContext) throws IOException, QueryParsingException { XContentParser parser = parseContext.parser(); boolean cache = true; CacheKeyFilter.Key cacheKey = null; String fieldName = null; String value = null; String filterName = null; String currentFieldName = null; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token.isValue()) { if ("_name".equals(currentFieldName)) { filterName = parser.text(); } else if ("_cache".equals(currentFieldName)) { cache = parser.booleanValue(); } else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) { cacheKey = new CacheKeyFilter.Key(parser.text()); } else { fieldName = currentFieldName; value = parser.text(); } } } if (fieldName == null) { throw new QueryParsingException(parseContext.index(), "No field specified for term filter"); } if (value == null) { throw new QueryParsingException(parseContext.index(), "No value specified for term filter"); } Filter filter = null; MapperService.SmartNameFieldMappers smartNameFieldMappers = parseContext.smartFieldMappers(fieldName); if (smartNameFieldMappers != null && smartNameFieldMappers.hasMapper()) { if (smartNameFieldMappers.explicitTypeInNameWithDocMapper()) { String[] previousTypes = QueryParseContext.setTypesWithPrevious(new String[] { smartNameFieldMappers .docMapper().type() }); try { filter = smartNameFieldMappers.mapper().fieldFilter(value, parseContext); } finally { QueryParseContext.setTypes(previousTypes); } } else { filter = smartNameFieldMappers.mapper().fieldFilter(value, parseContext); } } if (filter == null) { filter = new TermFilter(new Term(fieldName, value)); } if (cache) { filter = parseContext.cacheFilter(filter, cacheKey); } filter = QueryParsers.wrapSmartNameFilter(filter, smartNameFieldMappers, parseContext); if (filterName != null) { parseContext.addNamedFilter(filterName, filter); } return filter; } }
true
4c3a3c232acc0e92fb26cbecb429295a257f82a4
Java
gglfxx/system-parent
/system-web/src/main/java/com/online/system/web/service/VersionService.java
UTF-8
852
1.953125
2
[]
no_license
package com.online.system.web.service; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.online.system.web.entity.Result; import com.online.system.web.entity.Version; import java.util.List; /** * 版本Service */ public interface VersionService { /** * 查询 * @param page * @param versionType * @return */ Result<List<Version>> queryVersion(Page<Version> page, String versionType); /** * 新增或更新版本 * @param version * @return */ Result<String> addOrUpdateVersion(Version version); /** * 根据id查询版本信息 * @param id * @return */ Result<Version> findVersionById(String id); /** * 根据主键删除版本信息 * @param id * @return */ Result<String> delVersion(String id); }
true
89c4ea146054f21310835eb71e3086859768834a
Java
usopp9/View_Study
/app/src/main/java/kr/or/dgit/it/view_study/ViewBasicActivity.java
UTF-8
1,535
2.390625
2
[]
no_license
package kr.or.dgit.it.view_study; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ViewBasicActivity extends AppCompatActivity implements View.OnClickListener { private TextView mTextView; Button trueBtn; Button falseBtn; TextView mTextView02; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /*Intent intent = getIntent(); int titleId = intent.getIntExtra("title", 0 );*/ setTitle(getIntent().getStringExtra("title")); setContentView(R.layout.activity_view_basic); mTextView = findViewById(R.id.tv); trueBtn = findViewById(R.id.trueBtn); falseBtn = findViewById(R.id.falseBtn); mTextView02 = findViewById(R.id.tv02); trueBtn.setOnClickListener(this); falseBtn.setOnClickListener(this); } @Override public void onClick(View v) { if (v == trueBtn) { mTextView02.setVisibility(View.VISIBLE); } else { mTextView02.setVisibility(View.GONE); } } public void trueBtn01Click(View view) { if (!mTextView.isShown()) { mTextView.setVisibility(View.VISIBLE); } } public void falseBtn02Click(View view) { if (mTextView.isShown()) { mTextView.setVisibility(View.INVISIBLE); } } }
true
039d46ca4fb6a801f17db1801fcb34a97f784697
Java
PesGospoda/chat_bot_RPG
/src/MySQL.java
UTF-8
2,414
3.140625
3
[]
no_license
import java.sql.*; public class MySQL { private Connection connection; private static String selectPlayerString = "SELECT * FROM players WHERE userID=?"; private static String updateString = "UPDATE players SET experience=?, hp=? WHERE userID=?"; private static String insertNewPlayerString = "INSERT INTO players VALUES (?, ?, ?, ?)"; private static PreparedStatement selectPlayerCommand; private static PreparedStatement updateCommand; private static PreparedStatement insertNewPlayerCommand; public MySQL(String url, String user, String password) { try { connection = DriverManager.getConnection(url, user, password); selectPlayerCommand = connection.prepareStatement(selectPlayerString); updateCommand = connection.prepareStatement(updateString); insertNewPlayerCommand = connection.prepareStatement(insertNewPlayerString); } catch (SQLException sqlEx) { sqlEx.printStackTrace(); } } public void updatePlayer(Player player) { try { updateCommand.setInt(1, player.getExperience()); updateCommand.setInt(2, player.getHealth()); updateCommand.setInt(3, player.getPlayerID()); updateCommand.executeUpdate(); } catch (SQLException sqlEx) { sqlEx.printStackTrace(); } } public void insertPlayer(Player player) { try { insertNewPlayerCommand.setInt(1, player.getPlayerID());// playerID insertNewPlayerCommand.setString(2, player.getName());//player name insertNewPlayerCommand.setInt(3, player.getExperience());//experience insertNewPlayerCommand.setInt(4, player.getHealth());//health insertNewPlayerCommand.executeUpdate(); } catch (SQLException sqlEx) { sqlEx.printStackTrace(); } } public void loadInfo(Player player) { try { selectPlayerCommand.setInt(1, player.getPlayerID()); ResultSet resultSet = selectPlayerCommand.executeQuery(); if (resultSet.next()) { player.setHealth(resultSet.getInt("hp")); player.setExperience(resultSet.getInt("experience")); } else insertPlayer(player); } catch (SQLException sqlEx) { sqlEx.printStackTrace(); } } }
true
5367e3de6d4e66e54cb8cd9e81b63f9f0d2516a7
Java
novakst6/komuniti
/src/main/java/cz/komuniti/model/form/admin/RegionAddFrom.java
UTF-8
861
2.046875
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cz.komuniti.model.form.admin; import org.hibernate.validator.constraints.NotEmpty; /** * * @author novakst6 */ public class RegionAddFrom { private String parentName; private String name; private Long parentId; @NotEmpty(message="Jméno regionu musí být vyplněno.") public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getParentId() { return parentId; } public void setParentId(Long parentId) { this.parentId = parentId; } public String getParentName() { return parentName; } public void setParentName(String parentName) { this.parentName = parentName; } }
true
bdc9160e21c437253b8e0082fc9fd837982f1e65
Java
thanapol2/tour
/temp/rowPaymentHead.java
UTF-8
1,611
2.625
3
[]
no_license
package temp; import java.util.ArrayList; public class rowPaymentHead { private String paymanetType; private String paymanetNo; private String invoiceNo; private String customerName; private String reject; private String issueDate; private String paymentDate; private ArrayList<String> data; public rowPaymentHead(){ paymanetType = ""; invoiceNo = ""; reject = ""; issueDate = ""; customerName = ""; paymanetNo = ""; paymentDate = ""; data = new ArrayList<String>(); setAllData(); } public rowPaymentHead(ArrayList<String> data){ this.data = new ArrayList<String>(); this.data = data; paymanetType = data.get(0); paymanetNo = data.get(1); invoiceNo = data.get(2); reject = this.data.get(3); paymentDate = data.get(4); customerName = data.get(5); issueDate = data.get(6); } private void setAllData(){ this.data.add(paymanetType); this.data.add(paymanetNo); this.data.add(invoiceNo); this.data.add(paymentDate); this.data.add(customerName); this.data.add(issueDate); } public ArrayList<String> getStringData() { return this.data; } public String getElementData(int index){ return this.data.get(index); } public void setElementData(String data,int index){ this.data.set(index, data); paymanetType = this.data.get(0); paymanetNo = this.data.get(1); invoiceNo = this.data.get(2); reject = this.data.get(3); paymentDate = this.data.get(4); customerName = this.data.get(5); issueDate = this.data.get(6); } public String getReject() { return reject; } public void setReject(String reject) { this.reject = reject; } }
true
56f40338876079de735389291aa66660aaed4a85
Java
charlenetshos/biblioteca
/src/com/twu29/biblioteca/Item.java
UTF-8
278
2.890625
3
[]
no_license
package com.twu29.biblioteca; public class Item { private String text; private String message; public Item(String text, String message){ this.text = text; this.message = message; } public String deliver() { return message; } }
true
27582e13b7bf95d30bea55644143406d19a72ec3
Java
hou171/20171113
/src/abc.java
UTF-8
314
2.609375
3
[]
no_license
import java.util.Scanner; public class abc { public static void main(String[] args){ Scanner sc=new Scanner(System.in); Integer i; Integer sum=0; for(i=0;i<=10;i=i+2){ System.out.println(i); sum=sum+i; } System.out.println(sum); } }
true
fc52f1d6e8013f48f08f39396ca0053119e8957f
Java
tobrother272/ssc.video.download
/src/Utils/XmlUtils.java
UTF-8
2,119
2.375
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Utils; import java.io.File; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; import org.w3c.dom.Document; import org.w3c.dom.NodeList; /** * * @author simplesolution.co */ public class XmlUtils { public static String getValueOfNodeByKey(String path,String node,String key) { String result = ""; try { File inputFile = new File(path); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName(node); result =nList.item(0).getAttributes().getNamedItem(key).getNodeValue(); } catch (Exception e) { } return result; } public static int getPortLeapDroid(String path) { int result = -1; try { File inputFile = new File(path); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(inputFile); doc.getDocumentElement().normalize(); NodeList nList = doc.getElementsByTagName("GuestProperty"); for (int i = 0; i < nList.getLength(); i++) { if(nList.item(i).getAttributes().getNamedItem("name").toString().contains("adb_port")){ return Integer.parseInt(nList.item(i).getAttributes().getNamedItem("value").getNodeValue()) -1; } } //result =nList.item(0).getAttributes().getNamedItem(key).getNodeValue(); } catch (Exception e) { } return result; } }
true
8ab7691046e9d96afd401f71154c1c2d4eee9131
Java
marcellodesales/hadoop-clusternet
/stub-src/src/index/WordCountsForDocsReducer.java
UTF-8
1,785
2.578125
3
[]
no_license
// (c) Copyright 2009 Cloudera, Inc. // Hadoop 0.20.1 API Updated by Marcello de Sales (marcello.desales@gmail.com) package index; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; /** * WordCountsForDocsReducer counts the number of documents in the */ public class WordCountsForDocsReducer extends Reducer<Text, Text, Text, Text> { private Text wordAtDoc = new Text(); private Text wordAvar = new Text(); public WordCountsForDocsReducer() { } /** * @param key is the key of the mapper * @param values are all the values aggregated during the mapping phase * @param context contains the context of the job run * * PRE-CONDITION: receive a list of <document, ["word=n", "word-b=x"]> * pairs <"a.txt", ["word1=3", "word2=5", "word3=5"]> * * POST-CONDITION: <"word1@a.txt, 3/13">, * <"word2@a.txt, 5/13"> */ protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { int sumOfWordsInDocument = 0; Map<String, Integer> tempCounter = new HashMap<String, Integer>(); for (Text val : values) { String[] wordCounter = val.toString().split("="); tempCounter.put(wordCounter[0], Integer.valueOf(wordCounter[1])); sumOfWordsInDocument += Integer.parseInt(val.toString().split("=")[1]); } for (String wordKey : tempCounter.keySet()) { this.wordAtDoc.set(wordKey + "@" + key.toString()); this.wordAvar.set(tempCounter.get(wordKey) + "/" + sumOfWordsInDocument); context.write(this.wordAtDoc, this.wordAvar); } } }
true
542ff63a7f9cd5ab8f5297cf8bb93c1affde88d2
Java
Kamrul28/redfita-integration-tests
/src/test/java/ui/pages/EarringsPage.java
UTF-8
1,784
2.390625
2
[]
no_license
package ui.pages; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.FindBy; import ui.common.PageHelper; /** * Created by KAMRUBY on 4/4/2017. */ public class EarringsPage extends PageHelper{ private WebDriver driver; @FindBy(xpath = ".//*[@id='Menu']/li[1]/a") private WebElement bodyJewelry; @FindBy(xpath = ".//*[@id='Menu']/li[1]/ul/li[1]/a") private WebElement earringLink; @FindBy(name = "qty3") private WebElement earringQuantityField; @FindBy(xpath = ".//*[@id='items']/table/tbody/tr/td/table/tbody/tr[2]/td/input[2]") private WebElement addToCartButton; @FindBy(xpath = "//*[@id='items']/table/tbody/tr/td/table/tbody/tr[2]/td/input[3]") private WebElement goToCart; @FindBy (xpath = "html/body/div[1]/table/tbody/tr/td/table/tbody/tr[2]/td[4]") private WebElement cartQuantityText; public EarringsPage(WebDriver driver){ super(driver); this.driver = driver; } public void navigateToEarringPage(){ Actions action = new Actions(driver); action.moveToElement(bodyJewelry).perform(); action.moveToElement(earringLink).click().perform(); } public void enterQuantityField(String enterQuantity){ driverWaitUntil(earringQuantityField,90); earringQuantityField.sendKeys(enterQuantity); // ----------------review } public void clickAddToCartButton(){ addToCartButton.click(); } public void clickGoToCart() { goToCart.click(); } public void acceptAlert(){ driver.switchTo().alert().accept();} public String getCartQuantityTest(){ return cartQuantityText.getText(); } }
true
3ee067020e25ca27a40e8457fda0fd8233a1c65c
Java
OBerger96/flightGear-server-side
/src/server_side/BestFirstSearch.java
UTF-8
1,184
3.015625
3
[]
no_license
package model.server_side; import java.util.LinkedHashSet; import java.util.List; public class BestFirstSearch<T> extends CommonSearcher<T> { @Override public List<State<T>> search(Searchable<T> searchable) { State<T> initialState = new State<T>(searchable.getInitialState()); initialState.setCost(0); addToOpenList(initialState); LinkedHashSet<State<T>> closedSet = new LinkedHashSet<>(); while(isOpenListEmpty() == false) { State<T> currentState = this.popOpenList(); closedSet.add(currentState); if(searchable.isGoal(currentState)) { return backTrace(currentState); } List<State<T>> successors = searchable.getAllPossibleStates(currentState); for(State<T> neighbor : successors) { if((closedSet.contains(neighbor) == false) && (isContainedInOpenList(neighbor) == false)) { neighbor.setCameFrom(currentState); addToOpenList(neighbor); } else if((closedSet.contains(neighbor) == false) && (currentState.getCost() + neighbor.getCost() < findInOpenList(neighbor).getCost())) { removeFromOpenList(neighbor); addToOpenList(neighbor); } } } return null; } }
true
413af7a82e3de1b20341a5179e0c5f7d334f983b
Java
pedrograu/bayes-dota-challenge
/src/main/java/gg/bayes/challenge/db/entities/MatchItemEntity.java
UTF-8
760
2.375
2
[]
no_license
package gg.bayes.challenge.db.entities; public class MatchItemEntity { private Long matchId; private String hero; private String item; private Long timePurchase; public Long getMatchId() { return matchId; } public void setMatchId(Long matchId) { this.matchId = matchId; } public String getHero() { return hero; } public void setHero(String hero) { this.hero = hero; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public Long getTimePurchase() { return timePurchase; } public void setTimePurchase(Long timePurchase) { this.timePurchase = timePurchase; } }
true
873346c2280678780344dba62361bcc1c7f69b57
Java
Axe-hay/Mind-Your-Money
/app/src/main/java/com/example/mindyourmoney/BorrowerDatabase.java
UTF-8
897
2.171875
2
[]
no_license
package com.example.mindyourmoney; import android.content.Context; import android.os.AsyncTask; import androidx.annotation.NonNull; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.sqlite.db.SupportSQLiteDatabase; @Database(entities = {Borrower.class},version = 1) public abstract class BorrowerDatabase extends RoomDatabase { private static BorrowerDatabase sBorrowerDatabaseInstance; public abstract BorrowersTableDataAccessObject borrowersDao(); public static synchronized BorrowerDatabase getInstance(Context context){ if(sBorrowerDatabaseInstance==null) sBorrowerDatabaseInstance= Room.databaseBuilder(context.getApplicationContext(),BorrowerDatabase.class,"borrower_database") .fallbackToDestructiveMigration().build(); return sBorrowerDatabaseInstance; } }
true
ac80cffe2cc09326430712b6ddd5263b8f64e91d
Java
a3535ed54a5ee6917a46cfa6c3f12679/7c314649_Menoria_OLD_SemiObf
/class_977.java
UTF-8
4,636
1.71875
2
[]
no_license
import java.util.Arrays; import org.apache.commons.lang3.ArrayUtils; // $FF: renamed from: mc public class class_977 extends class_972 { // $FF: renamed from: w lG private final class_194 field_4931; // $FF: renamed from: x bao private final bao field_4932; // $FF: renamed from: y l9[] private final class_31[] field_4933; // $FF: renamed from: z int private int field_4934; // $FF: renamed from: A java.lang.String private static final String field_4935 = "CL_00000732"; // $FF: renamed from: <init> (lG, bao) void public void method_5619(class_194 var1, bao var2) { super.method_5549(var2, var1.width, var1.height, 63, var1.height - 32, 20); this.field_4934 = 0; this.field_4931 = var1; String[] var10000 = class_752.method_4253(); this.field_4932 = var2; class_1357[] var4 = (class_1357[])((class_1357[])ArrayUtils.clone(var2.canLoseFocus7.field_4556)); this.field_4933 = new class_31[var4.length + class_1357.getEnableBackgroundDrawing0().size()]; Arrays.sort(var4); int var5 = 0; String[] var3 = var10000; String var6 = null; class_1357[] var7 = var4; int var8 = var4.length; int var9 = 0; while(var9 < var8) { class_1357 var10 = var7[var9]; String var11 = var10.getEnableBackgroundDrawing3(); int var13 = var11.equals(var6); class_31[] var14; int var10001; if(var3 != null) { if(var13 == 0) { var6 = var11; var14 = this.field_4933; var10001 = var5++; Gui3 var10002 = new Gui3; var10002.setEnabled4(this, var11); var14[var10001] = var10002; } var13 = var2.enableBackgroundDrawing4.getCharWidth(class_1450.method_7896(var10.getEnableBackgroundDrawing6(), new Object[0])); } int var12 = var13; if(var3 != null) { if(var12 > this.field_4934) { this.field_4934 = var12; } var14 = this.field_4933; var10001 = var5++; Gui4 var15 = new Gui4; var15.setEnabled7(this, var10, (Object)null); var14[var10001] = var15; ++var9; } if(var3 == null) { break; } } } // $FF: renamed from: b () int protected int method_5553() { return this.field_4933.length; } // $FF: renamed from: c (int) l9 public class_31 method_5606(int var1) { return this.field_4933[var1]; } // $FF: renamed from: d () int protected int method_5575() { return super.method_5575() + 15; } // $FF: renamed from: c () int public int method_5573() { return super.method_5573() + 32; } // $FF: renamed from: b (mc) bao static bao method_5620(class_977 var0) { return var0.field_4932; } // $FF: renamed from: c (mc) lG static class_194 method_5621(class_977 var0) { return var0.field_4931; } // $FF: renamed from: d (mc) int static int method_5622(class_977 var0) { return var0.field_4934; } // $FF: renamed from: <clinit> () void static void method_5579() { boolean var10000 = true; char[] var10003 = "].³Ë„‡M.UßÉ".toCharArray(); Object var10004 = var10003.length; Object var4 = true; char[] var10002 = var10003; char[] var10001 = (char[])var10004; int var0 = 0; while(true) { var10003 = var10002; var10002 = var10001; var10001 = var10003; char[] var5 = var10002; var10002 = var10003; if(var10003 <= var0) { field_4935 = (new String((char[])var4)).intern(); String var2 = field_4935; return; } char var10007 = (char)((Object[])var4)[var0]; short var10009; switch(var0 % 7) { case 0: var10009 = 98; break; case 1: var10009 = 30; break; case 2: var10009 = 144; break; case 3: var10009 = 135; break; case 4: var10009 = 200; break; case 5: var10009 = 203; break; default: var10009 = 1; } ((Object[])var4)[var0] = (char)(var10007 ^ var5 ^ var10009); ++var0; } } }
true
2a27f623fe9e82648910b98160eb634e72ee2b92
Java
SaiPrudhviG/BasicFragmentExample
/app/src/main/java/com/example/prudhvi/fragmentex/MainActivity.java
UTF-8
1,275
2.234375
2
[]
no_license
package com.example.prudhvi.fragmentex; import android.app.Activity; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity{ Button b1,b2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1=(Button)findViewById(R.id.b1); b2=(Button)findViewById(R.id.b2); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FragmentManager fragmentManager =null; FragmentTransaction ft=fragmentManager.beginTransaction(); ft.add(R.id.frame1,new BlankFragment()); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { FragmentManager fragmentManager = null; FragmentTransaction ft=fragmentManager.beginTransaction(); ft.add(R.id.frame1,new BlankFragment2()); } }); } }
true
127d20c3ba13bd5f79544a0159297505c6b01b22
Java
deepdivedylan/college-applicant-classifier
/src/main/java/io/deepdivedylan/collegeapplicantclassifier/collegeapplication/types/GpaField.java
UTF-8
503
2.59375
3
[ "Apache-2.0" ]
permissive
package io.deepdivedylan.collegeapplicantclassifier.collegeapplication.types; public class GpaField { private double gpa; private double perfectGpa; public GpaField(double newGpa, double newPerfectGpa) { gpa = newGpa; perfectGpa = newPerfectGpa; } public double getGpa() { return gpa; } public double getPerfectGpa() { return perfectGpa; } @Override public String toString() { return gpa + " / " + perfectGpa; } }
true
cb3e86eb905afd43d7cb1f15a2902ae3707bf3ed
Java
chenfei0928/Util
/library/src/main/java/io/github/chenfei0928/view/asyncinflater/AsyncLayoutInflater.java
UTF-8
4,558
2.390625
2
[ "MIT" ]
permissive
package io.github.chenfei0928.view.asyncinflater; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.LayoutRes; import androidx.annotation.MainThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.annotation.UiThread; import io.github.chenfei0928.concurrent.ExecutorUtil; import io.github.chenfei0928.util.Log; import kotlin.jvm.functions.Function2; /** * 使用自定义的次线程执行器来替换其类的布局加载器,并简化逻辑 * {@link androidx.asynclayoutinflater.view.AsyncLayoutInflater} * * @author MrFeng * @date 2018/4/10 */ public class AsyncLayoutInflater { private static final String TAG = "KW_AsyncLayoutInflater"; private final LayoutInflater mInflater; public AsyncLayoutInflater(@NonNull Context context) { mInflater = new BasicInflater(context); } /** * 通过自定义的布局创建者在子线程创建子布局 * * @param onCreateView 子视图创建者 * @param parent 父布局,用于生成LayoutParam * @param callback 子视图创建完成后在主线程的回调 * @param <VG> 父布局的类型 */ @UiThread public <VG extends ViewGroup> void inflate( Function2<LayoutInflater, VG, View> onCreateView, @Nullable VG parent, @NonNull OnInflateFinishedListener callback) { ExecutorUtil.execute(() -> { try { return onCreateView.invoke(mInflater, parent); } catch (RuntimeException ex) { // Probably a Looper failure, retry on the UI thread Log.w(TAG, "Failed to inflate resource in the background! Retrying on the UI" + " thread", ex); return null; } }, view -> { if (view == null) { view = onCreateView.invoke(mInflater, parent); } callback.onInflateFinished(view); }); } /** * 通过布局文件创建者在子线程创建子布局 * * @param resid 子视图布局id * @param parent 父布局,用于生成LayoutParam * @param callback 子视图创建完成后在主线程的回调 * @param <VG> 父布局的类型 */ @UiThread public <VG extends ViewGroup> void inflate( @LayoutRes int resid, @Nullable VG parent, @NonNull OnInflateFinishedListener callback) { ExecutorUtil.execute(() -> { try { return mInflater.inflate(resid, parent, false); } catch (RuntimeException ex) { // Probably a Looper failure, retry on the UI thread Log.w(TAG, "Failed to inflate resource in the background! Retrying on the UI" + " thread", ex); return null; } }, view -> { if (view == null) { view = mInflater.inflate(resid, parent, false); } callback.onInflateFinished(view); }); } public interface OnInflateFinishedListener { /** * 当View加载完成后的回调,此方法会在主线程回调 * * @param view 加载完成的View */ @MainThread void onInflateFinished(@NonNull View view); } static class BasicInflater extends LayoutInflater { private static final String[] sClassPrefixList = { "android.widget.", "android.webkit.", "android.app." }; BasicInflater(Context context) { super(context); } @Override public LayoutInflater cloneInContext(Context newContext) { return new BasicInflater(newContext); } @Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException { for (String prefix : sClassPrefixList) { try { View view = createView(name, prefix, attrs); if (view != null) { return view; } } catch (ClassNotFoundException e) { // In this case we want to let the base class take a crack // at it. } } return super.onCreateView(name, attrs); } } }
true
d223768dc1504988e9bb4621192eaa2c0c75a612
Java
nikstarlord/AutomationRepo
/EndToEndSelenium/src/test/java/RegisterTest.java
UTF-8
1,277
2.15625
2
[]
no_license
import org.openqa.selenium.WebElement; import org.testng.annotations.AfterTest; import org.testng.annotations.Test; import pageObject.AutoReg; import resources.Base; import java.io.IOException; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class RegisterTest extends Base { @Test public void testLanguage() throws IOException { driver = initializeDriver(); driver.get("http://demo.automationtesting.in/Register.html"); List<String> ls= Stream.of(prop.getProperty("language").split(",")).collect(Collectors.toList()); AutoReg reg = new AutoReg(driver); reg.getLan().click(); List<WebElement> te = reg.getList(); for(String s:ls){ System.out.println(s); } int propSize = ls.size(); int listSize = te.size(); System.out.println(propSize+" "+listSize); for(int i=0;i<propSize;i++){ for(int j=0;j<listSize;j++){ String s = te.get(i).getText(); System.out.println(s); if(s.equals(ls.get(j))){ te.get(i).click(); } } } } @AfterTest public void close(){ driver.quit(); } }
true
002d83c4c1423552c83e3d20d93f93a54e866e49
Java
musaogural/CleanCode
/java/src/ch03/srp/task/SorterTaskFactory.java
UTF-8
141
1.867188
2
[]
no_license
package org.javaturk.cc.ch03.srp.task; public class SorterTaskFactory { public Sorter<Product> create() { return new SorterTask(); } }
true
fe6831b6fbc297dea4f95218169a40c3b65c5354
Java
haobtc/electrum
/android/app/src/main/java/org/haobtc/wallet/event/MainpageWalletEvent.java
UTF-8
481
2.203125
2
[ "MIT" ]
permissive
package org.haobtc.wallet.event; public class MainpageWalletEvent { String status; int pos; public MainpageWalletEvent(String status, int pos) { this.status = status; this.pos = pos; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public int getPos() { return pos; } public void setPos(int pos) { this.pos = pos; } }
true
841d49d464e5b62efa16c55913b6c12e2803119d
Java
noamsml/pitchcoach
/PitchRecognizeAlgorithm/src/umich/pitchcoach/PitchAnalyzerDCT_HPS.java
UTF-8
2,948
2.546875
3
[]
no_license
package umich.pitchcoach; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import edu.emory.mathcs.jtransforms.dct.FloatDCT_1D; public class PitchAnalyzerDCT_HPS implements IPitchAnalyzer { private FloatDCT_1D dct; private float MINENERGY = (float) Math.pow(10, 15); int size; float[] floatbuf; float[] floatbuf_copy; // again, minimize allocations // private static final double SEARCH_LOW = 10; // private static final double SEARCH_HIGH = 5000; IPeakDetector peakdetect; HammingWindow hamming; SpikeEliminator spikeelim; public PitchAnalyzerDCT_HPS(int size) { dct = new FloatDCT_1D(size); this.size = size; floatbuf = new float[size]; floatbuf_copy = new float[size]; peakdetect = new PeakDetectorRunningMaxRMS(); hamming = new HammingWindow(size); spikeelim = new SpikeEliminator(Math.pow(LetterNotes.stepVal, 6)); } @SuppressWarnings("unused") @Override public double getPitch(ISampleSource buf, int sampleRate) throws NoMoreDataException { for (int i = 0; i < size; i++) { floatbuf[i] = 0; } buf.readData(floatbuf); hamming.applyHammingWindow(floatbuf); dct.forward(floatbuf, false); for (int i = 0; i < size; i++) { floatbuf[i] = Math.abs(floatbuf[i]); } for (int i = 0; i < floatbuf.length; i++) { floatbuf_copy[i] = floatbuf[i]; } for (int compression = 2; compression < 4; compression++) { for (int i = 1; i < floatbuf.length; i++) { floatbuf[i] = floatbuf[i] * sample_compressed(floatbuf_copy, 1, compression, i); } } String diagWriteToDisk = null; peakdetect.prepareData(floatbuf, 1, floatbuf.length / 3); /* * if (diagWriteToDisk != null) { try { PrintWriter write = new * PrintWriter(new FileOutputStream(diagWriteToDisk)); for (int i = 1; i * < floatbuf.length; i++) write.println(floatbuf[i]); write.close(); } * catch (FileNotFoundException e) { // TODO Auto-generated catch block * e.printStackTrace(); } } */ int peak; peak = peakdetect.findNextPeak(); if (peak == -1) return -1; if (floatbuf[peak] < MINENERGY) return -1; return spikeelim.getSmoothedSample(DCTIndexToFreq(peak, size, sampleRate)); } private int getMax(float[] buffer, int begin, int end) { int peak = begin; for (int i = begin; i < end; i++) { if (buffer[i] > buffer[peak]) { peak = i; } } return peak; } private float sample_compressed(float[] buffer, int offset, int compression, int loc) { if (offset + loc * compression < buffer.length) return buffer[offset + loc * compression]; return 0; } private double DCTIndexToFreq(int index, int size, int rate) { return ((double) (index * rate)) / ((double) 2 * size); } private int freqToDCTIndex(double freq, int size, int rate) { return (int) ((freq * 2 * size) / (rate)); } @Override public double bucketSize(int rate) { return ((double) rate) / ((double) 2 * size); } }
true
1bf8525a2218d028fd7dacebe98387017db96618
Java
assaflavi/AntennaPod
/src/de/danoeh/antennapod/service/download/HttpDownloader.java
UTF-8
6,470
2.3125
2
[ "MIT" ]
permissive
package de.danoeh.antennapod.service.download; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; import java.net.UnknownHostException; import org.apache.commons.io.IOUtils; import org.apache.http.HttpConnection; import org.apache.http.HttpStatus; import android.util.Log; import de.danoeh.antennapod.AppConfig; import de.danoeh.antennapod.R; import de.danoeh.antennapod.asynctask.DownloadStatus; import de.danoeh.antennapod.util.DownloadError; import de.danoeh.antennapod.util.StorageUtils; public class HttpDownloader extends Downloader { private static final String TAG = "HttpDownloader"; private static final int MAX_REDIRECTS = 5; private static final int BUFFER_SIZE = 8 * 1024; private static final int CONNECTION_TIMEOUT = 5000; public HttpDownloader(DownloaderCallback downloaderCallback, DownloadStatus status) { super(downloaderCallback, status); } /** * This method is called by establishConnection(String). Don't call it * directly. * */ private HttpURLConnection establishConnection(String location, int redirectCount) throws MalformedURLException, IOException { URL url = new URL(location); HttpURLConnection connection = null; int responseCode = -1; connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(CONNECTION_TIMEOUT); // try with 'follow redirect' connection.setInstanceFollowRedirects(true); try { responseCode = connection.getResponseCode(); } catch (IOException e) { e.printStackTrace(); if (AppConfig.DEBUG) Log.d(TAG, "Failed to establish connection with 'follow redirects. Disabling 'follow redirects'"); connection.disconnect(); connection.setInstanceFollowRedirects(false); responseCode = connection.getResponseCode(); } if (AppConfig.DEBUG) Log.d(TAG, "Response Code: " + responseCode); switch (responseCode) { case HttpStatus.SC_TEMPORARY_REDIRECT: if (redirectCount < MAX_REDIRECTS) { final String redirect = connection.getHeaderField("Location"); if (redirect != null) { return establishConnection(redirect, redirectCount + 1); } } case HttpStatus.SC_OK: return connection; default: onFail(DownloadError.ERROR_HTTP_DATA_ERROR, String.valueOf(responseCode)); return null; } } /** * Establish connection to resource. This method will also try to handle * different response codes / redirect issues. * * @return the HttpURLConnection object if the connection could be opened, * null otherwise. * @throws MalformedURLException * , IOException * */ private HttpURLConnection establishConnection(String location) throws MalformedURLException, IOException { return establishConnection(location, 0); } @Override protected void download() { HttpURLConnection connection = null; OutputStream out = null; try { connection = establishConnection(status.getFeedFile() .getDownload_url()); if (connection != null) { if (AppConfig.DEBUG) { Log.d(TAG, "Connected to resource"); } if (StorageUtils.externalStorageMounted()) { File destination = new File(status.getFeedFile() .getFile_url()); if (!destination.exists()) { InputStream in = new BufferedInputStream( connection.getInputStream()); out = new BufferedOutputStream(new FileOutputStream( destination)); byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; status.setStatusMsg(R.string.download_running); if (AppConfig.DEBUG) Log.d(TAG, "Getting size of download"); status.setSize(connection.getContentLength()); if (AppConfig.DEBUG) Log.d(TAG, "Size is " + status.getSize()); if (status.getSize() == -1) { status.setSize(DownloadStatus.SIZE_UNKNOWN); } long freeSpace = StorageUtils.getFreeSpaceAvailable(); if (AppConfig.DEBUG) Log.d(TAG, "Free space is " + freeSpace); if (status.getSize() == DownloadStatus.SIZE_UNKNOWN || status.getSize() <= freeSpace) { if (AppConfig.DEBUG) Log.d(TAG, "Starting download"); while (!cancelled && (count = in.read(buffer)) != -1) { out.write(buffer, 0, count); status.setSoFar(status.getSoFar() + count); status.setProgressPercent((int) (((double) status .getSoFar() / (double) status.getSize()) * 100)); } if (cancelled) { onCancelled(); } else { onSuccess(); } } else { onFail(DownloadError.ERROR_NOT_ENOUGH_SPACE, null); } } else { Log.w(TAG, "File already exists"); onFail(DownloadError.ERROR_FILE_EXISTS, null); } } else { onFail(DownloadError.ERROR_DEVICE_NOT_FOUND, null); } } } catch (MalformedURLException e) { e.printStackTrace(); onFail(DownloadError.ERROR_MALFORMED_URL, e.getMessage()); } catch (SocketTimeoutException e) { e.printStackTrace(); onFail(DownloadError.ERROR_CONNECTION_ERROR, e.getMessage()); } catch (UnknownHostException e) { e.printStackTrace(); onFail(DownloadError.ERROR_UNKNOWN_HOST, e.getMessage()); } catch (IOException e) { e.printStackTrace(); onFail(DownloadError.ERROR_IO_ERROR, e.getMessage()); } catch (NullPointerException e) { // might be thrown by connection.getInputStream() e.printStackTrace(); onFail(DownloadError.ERROR_CONNECTION_ERROR, status.getFeedFile() .getDownload_url()); } finally { IOUtils.close(connection); IOUtils.closeQuietly(out); } } private void onSuccess() { if (AppConfig.DEBUG) Log.d(TAG, "Download was successful"); status.setSuccessful(true); status.setDone(true); } private void onFail(int reason, String reasonDetailed) { if (AppConfig.DEBUG) { Log.d(TAG, "Download failed"); } status.setReason(reason); status.setReasonDetailed(reasonDetailed); status.setDone(true); status.setSuccessful(false); } private void onCancelled() { if (AppConfig.DEBUG) Log.d(TAG, "Download was cancelled"); status.setReason(DownloadError.ERROR_DOWNLOAD_CANCELLED); status.setDone(true); status.setSuccessful(false); status.setCancelled(true); } }
true
86ad48c1167cd23ef654c1b4d07384545bb14fab
Java
soko8/MyWork
/java/algorithm/src/multiThread/threadCoordination/test.java
UTF-8
1,669
2.859375
3
[]
no_license
package multiThread.threadCoordination; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class test { public static void main(String[] args) { Storage storage = new Storage(); ExecutorService exec = Executors.newFixedThreadPool(16); ExecutorService exec2 = Executors.newFixedThreadPool(16); for (int i = 0; i < 100; i++) { exec.execute(new Consumer(storage)); exec2.execute(new Producer(storage)); } exec.shutdown(); exec2.shutdown(); /* // 生产者对象 Producer p1 = new Producer(storage); Producer p2 = new Producer(storage); Producer p3 = new Producer(storage); Producer p4 = new Producer(storage); Producer p5 = new Producer(storage); Producer p6 = new Producer(storage); Producer p7 = new Producer(storage); // 消费者对象 Consumer c1 = new Consumer(storage); Consumer c2 = new Consumer(storage); Consumer c3 = new Consumer(storage); Thread tc1 = new Thread(c1); Thread tc2 = new Thread(c2); Thread tc3 = new Thread(c3); Thread t1 = new Thread(p1); Thread t2 = new Thread(p2); Thread t3 = new Thread(p3); Thread t4 = new Thread(p4); Thread t5 = new Thread(p5); Thread t6 = new Thread(p6); Thread t7 = new Thread(p7); tc1.start(); tc2.start(); tc3.start(); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t6.start(); t7.start(); */ } }
true
8cc7eec208875459b2802bcceecb82c90ebda88a
Java
ElcyJ/Pet-Donation
/app/src/main/java/com/example/elcy/apppet/Favorites/FavoritesAdapter.java
UTF-8
2,938
2.1875
2
[]
no_license
package com.example.elcy.apppet.Favorites; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.elcy.apppet.Chat.ChatActivity; import com.example.elcy.apppet.R; import java.util.List; public class FavoritesAdapter extends RecyclerView.Adapter<FavoritesAdapter.FavoriteViewHolder>{ private Context context; private List<FavoritesObject> favoriteList; public FavoritesAdapter(Context context, List<FavoritesObject> favoriteList) { this.context = context; this.favoriteList = favoriteList; } public static class FavoriteViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{ TextView mFavoriteId, mFavoriteSex, mFavoriteAge, mFavoriteOwner; ImageView mFavoriteImage; public FavoriteViewHolder(View itemView) { super(itemView); itemView.setOnClickListener(this); mFavoriteId = itemView.findViewById(R.id.favoriteId); mFavoriteSex = itemView.findViewById(R.id.favoriteSex); mFavoriteAge = itemView.findViewById(R.id.favoriteAge); mFavoriteOwner = itemView.findViewById(R.id.favoriteOwner); mFavoriteImage = itemView.findViewById(R.id.favoriteImage); } @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), ChatActivity.class); Bundle b = new Bundle(); b.putString("ownerId", mFavoriteOwner.getText().toString()); intent.putExtras(b); v.getContext().startActivity(intent); } } @Override public FavoriteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate((R.layout.item_favorite), null, false); RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); view.setLayoutParams(lp); return new FavoriteViewHolder(view); } @Override public void onBindViewHolder(FavoriteViewHolder holder, int position) { holder.mFavoriteId.setText(favoriteList.get(position).getFavoriteId()); holder.mFavoriteSex.setText(favoriteList.get(position).getFavoriteSex()); holder.mFavoriteAge.setText(favoriteList.get(position).getFavoriteAge()); holder.mFavoriteOwner.setText(favoriteList.get(position).getFavoriteOwnerId()); Glide.with(context).load(favoriteList.get(position).getFavoriteImamgeUrl()).into(holder.mFavoriteImage); } @Override public int getItemCount() { return favoriteList.size(); } }
true
ec3202348638254b70f5ee519e2ce59ab6b66781
Java
IvanPletinskiy/wt-5sem-2
/src/main/java/com/handen/wt2/service/ApplianceService.java
UTF-8
243
1.835938
2
[]
no_license
package com.handen.wt2.service; import com.handen.wt2.domain.Appliance; import com.handen.wt2.domain.Teapot; import java.util.List; public interface ApplianceService { List<Teapot> getTeapots(); Appliance getCheapestAppliance(); }
true
7f1c84043d7fa3a3f9a0c0096171bdfbdd2c53dc
Java
xiaohei0131/springcloud-permission
/permission/src/main/java/org/sike/permission/annotation/EnableAiCloudPermissionServer.java
UTF-8
404
1.773438
2
[]
no_license
package org.sike.permission.annotation; import org.sike.permission.config.PermissionServerImportBeanDefinitionRegistrer; import org.springframework.context.annotation.Import; import java.lang.annotation.*; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented @Import(value = PermissionServerImportBeanDefinitionRegistrer.class) public @interface EnableAiCloudPermissionServer { }
true
720e805ff4fd85fef56e69bbed59e19dd071e2a9
Java
llNicoleta/Veterinarian
/backend/service/src/main/java/com/example/veterinarian/appointment/service/AppointmentService.java
UTF-8
530
2
2
[]
no_license
package com.example.veterinarian.appointment.service; import com.example.veterinarian.appointment.domain.Appointment; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; public interface AppointmentService { Iterable<Appointment> getAllAppointments(); void save(Appointment appointment); Appointment findAppointment(Long appointmentId); void updateAppointment(Appointment appointment); Page<Appointment> getPagedAppointments(Pageable pageable, String doctorName); }
true
1ffd3e27f9fac8233f9c5c4b270ed91d5297b57b
Java
BackupTheBerlios/woops2-svn
/trunk/src/woops2/hibernate/role/RoleDefinitionDao.java
UTF-8
1,614
2.671875
3
[]
no_license
package woops2.hibernate.role ; import java.util.HashSet ; import java.util.Set ; import org.hibernate.StaleObjectStateException ; import org.springframework.orm.hibernate3.support.HibernateDaoSupport ; import woops2.model.role.RoleDefinition ; /** * RoleDefinitionDao manage requests from the system to store RoleDefinition to the database * * @author soosuske */ public class RoleDefinitionDao extends HibernateDaoSupport { /** * Save or update an role * * @param _roleDefinition */ public void saveOrUpdateRole(RoleDefinition _roleDefinition) { this.getHibernateTemplate().saveOrUpdate(_roleDefinition) ; } /** * Return a list of role * * @return */ public Set<RoleDefinition> getAllRole() { Set<RoleDefinition> loadAll = new HashSet<RoleDefinition>() ; loadAll.addAll(this.getHibernateTemplate().loadAll(RoleDefinition.class)) ; return loadAll ; } /** * Return the role which have the id _id * * @param _id * @return */ public RoleDefinition getRole(String _id) { return (RoleDefinition) this.getHibernateTemplate().get(RoleDefinition.class, _id) ; } /** * Delete the role * * @param _roleDefinition */ public void deleteRole(RoleDefinition _roleDefinition) { try{ this.getHibernateTemplate().delete(_roleDefinition) ; } catch(StaleObjectStateException e){ // Catch normally errors when we delete an unexisting role into the // db. logger.error("#### ERROR #### --- RoleDefinitionDao => deleteRole : trying to delete unexisting object \n" + e) ; } } }
true
3de23850be301b52a2413ea3e95dcfc2d5841cb9
Java
momo02/algorithm_baekjoon
/BAEKJOON/src/q2558/Main.java
UTF-8
440
3.15625
3
[]
no_license
package q2558; import java.util.Scanner; //문제 : 두 정수 A와 B를 입력받은 다음, A+B를 출력하는 프로그램을 작성하시오. //입력 : 첫째 줄에 A, 둘째 줄에 B가 주어진다. (0 < A, B < 10) //출력 : 첫째 줄에 A+B를 출력한다. public class Main { public static void main(String[] args){ Scanner s = new Scanner(System.in); System.out.println(s.nextInt() +s.nextInt()); s.close(); } }
true
c4cccfa04ff1d4a8e0bec10c67d514a26d3705b1
Java
Deltharis/RemoteNAO
/src/main/java/pl/agh/edu/nao/actions/AngleInterpolation.java
UTF-8
765
2.46875
2
[]
no_license
package pl.agh.edu.nao.actions; import java.util.List; public class AngleInterpolation extends AbstractAction { private List<String> names; private List<Float> angles; private List<Float> times; public AngleInterpolation(List<String> names, List<Float> angles, List<Float> times) { super("angle"); this.names = names; this.angles = angles; this.times = times; } public List<String> getNames() { return names; } public void setNames(List<String> names) { this.names = names; } public List<Float> getAngles() { return angles; } public void setAngles(List<Float> angles) { this.angles = angles; } public List<Float> getTimes() { return times; } public void setTimes(List<Float> times) { this.times = times; } }
true
e845469b53a7c88c36a6b4d06c73daeead06a4d9
Java
wolf4ood/java-gobject-introspection
/src/gobject/internals/GTypeMapper.java
UTF-8
9,337
1.96875
2
[]
no_license
/* * Copyright (c) 2008 Colin Walters <walters@verbum.org> * * This file is part of java-gobject-introspection. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307 USA. * */ /* * Copyright (c) 2007 Wayne Meissner * * This file was originally part of gstreamer-java; modified for use in * jgir. By permission of author, this file has been relicensed from LGPLv3 * to the license of jgir; see below. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307 USA. */ package gobject.internals; import gobject.runtime.GObject; import java.net.URI; import java.util.Date; import com.sun.jna.CallbackParameterContext; import com.sun.jna.FromNativeContext; import com.sun.jna.FromNativeConverter; import com.sun.jna.FunctionResultContext; import com.sun.jna.MethodResultContext; import com.sun.jna.Pointer; import com.sun.jna.StructureReadContext; import com.sun.jna.ToNativeContext; import com.sun.jna.ToNativeConverter; import com.sun.jna.TypeConverter; /** * * @author wayne */ public class GTypeMapper extends com.sun.jna.DefaultTypeMapper { private static GTypeMapper instance; public synchronized static GTypeMapper getInstance() { if (instance == null) instance = new GTypeMapper(); return instance; } public GTypeMapper() { addToNativeConverter(URI.class, uriConverter); } private static ToNativeConverter nativeValueArgumentConverter = new ToNativeConverter() { public Object toNative(Object arg, ToNativeContext context) { return arg != null ? ((NativeValue) arg).nativeValue() : null; } public Class<?> nativeType() { return Void.class; // not really correct, but not used in this instance } }; private static TypeConverter nativeObjectConverter = new TypeConverter() { public Object toNative(Object arg, ToNativeContext context) { if (arg == null) { return null; } Pointer ptr = ((NativeObject) arg).getNativeAddress(); return ptr; } @SuppressWarnings(value = "unchecked") public Object fromNative(Object result, FromNativeContext context) { if (result == null) { return null; } if (context instanceof FunctionResultContext) { return NativeObject.Internals.objectFor((Pointer) result, context.getTargetType(), true); } if (context instanceof CallbackParameterContext || context instanceof StructureReadContext) { return NativeObject.Internals.objectFor((Pointer) result, context.getTargetType(), false); } if (context instanceof MethodResultContext) { throw new RuntimeException("Got illegal MethodResultContext in GTypeMapper"); } throw new IllegalStateException("Cannot convert to NativeObject from " + context); } public Class<?> nativeType() { return Pointer.class; } }; private static TypeConverter enumConverter = new TypeConverter() { @SuppressWarnings(value = "unchecked") public Object fromNative(Object value, FromNativeContext context) { return EnumMapper.getInstance().valueOf((Integer) value, context.getTargetType()); } public Class<?> nativeType() { return Integer.class; } @SuppressWarnings("unchecked") public Object toNative(Object arg, ToNativeContext context) { if (arg == null) { return null; } return EnumMapper.getInstance().intValue((Enum) arg); } }; private TypeConverter booleanConverter = new TypeConverter() { public Object toNative(Object arg, ToNativeContext context) { return Integer.valueOf(((Boolean) arg).booleanValue() ? 1 : 0); } public Object fromNative(Object arg0, FromNativeContext arg1) { return Boolean.valueOf(((Integer)arg0).intValue() != 0); } public Class<?> nativeType() { return Integer.class; } }; private TypeConverter gquarkConverter = new TypeConverter() { public Object fromNative(Object arg0, FromNativeContext arg1) { return new GQuark((Integer) arg0); } public Class<?> nativeType() { return Integer.class; } public Object toNative(Object arg0, ToNativeContext arg1) { return ((GQuark) arg0).intValue(); } }; private TypeConverter intptrConverter = new TypeConverter() { public Object toNative(Object arg, ToNativeContext context) { return ((IntPtr)arg).value; } public Object fromNative(Object arg0, FromNativeContext arg1) { return new IntPtr(((Number) arg0).intValue()); } public Class<?> nativeType() { return Pointer.SIZE == 8 ? Long.class : Integer.class; } }; private static ToNativeConverter uriConverter = new ToNativeConverter() { public Object toNative(Object arg0, ToNativeContext arg1) { URI uri = (URI) arg0; String uriString = uri.toString(); // Need to fixup file:/ to be file:/// for gstreamer if ("file".equals(uri.getScheme()) && uri.getHost() == null) { final String path = uri.getRawPath(); if (com.sun.jna.Platform.isWindows()) { uriString = "file:/" + path; } else { uriString = "file://" + path; } } return uriString; } public Class<?> nativeType() { return String.class; } }; private TypeConverter dateConverter = new TypeConverter() { public Object toNative(Object arg, ToNativeContext context) { return ((Date)arg).getTime(); } public Object fromNative(Object arg0, FromNativeContext arg1) { return new Date(((Long) arg0)); } public Class<?> nativeType() { return Pointer.SIZE == 8 ? Long.class : Integer.class; } }; @SuppressWarnings("unchecked") public FromNativeConverter getFromNativeConverter(Class type) { if (Enum.class.isAssignableFrom(type)) { return enumConverter; } else if (GObject.GObjectProxy.class.isAssignableFrom(type)) { return nativeObjectConverter; } else if (NativeObject.class.isAssignableFrom(type)) { return nativeObjectConverter; } else if (Boolean.class == type || boolean.class == type) { return booleanConverter; } else if (IntPtr.class == type) { return intptrConverter; } else if (GQuark.class == type) { return gquarkConverter; } else if (Date.class.isAssignableFrom(type)) { return dateConverter; } return super.getFromNativeConverter(type); } @SuppressWarnings("unchecked") public ToNativeConverter getToNativeConverter(Class type) { if (NativeObject.class.isAssignableFrom(type)) { return nativeObjectConverter; } else if (GObject.GObjectProxy.class.isAssignableFrom(type)) { return nativeObjectConverter; } else if (NativeValue.class.isAssignableFrom(type)) { return nativeValueArgumentConverter; } else if (Enum.class.isAssignableFrom(type)) { return enumConverter; } else if (Boolean.class == type || boolean.class == type) { return booleanConverter; } else if (IntPtr.class == type) { return intptrConverter; } else if (GQuark.class == type) { return gquarkConverter; } else if (Date.class.isAssignableFrom(type)) { return dateConverter; } return super.getToNativeConverter(type); } }
true
c6dde6623a4f9c7748c75baed6ce22a453a70f8c
Java
serAL26/AdopteSer
/AdopteUnDevEntities/src/main/resources/entity/Operation_.java
UTF-8
688
1.75
2
[]
no_license
package entity; import java.util.Date; import javax.annotation.Generated; import javax.persistence.metamodel.SingularAttribute; import javax.persistence.metamodel.StaticMetamodel; @Generated(value="Dali", date="2016-02-01T10:34:48.351+0100") @StaticMetamodel(Operation.class) public class Operation_ { public static volatile SingularAttribute<Operation, Double> montant; public static volatile SingularAttribute<Operation, Date> date; public static volatile SingularAttribute<Operation, Integer> idOperation; public static volatile SingularAttribute<Operation, Livrable> livrable; public static volatile SingularAttribute<Operation, TypeOperation> typeOperation; }
true
ed2c300eb99954d491944da713a42b2875db66c3
Java
longgvph03666/UngDungDocTruyen
/UngDungDocTruyen/src/com/group1/app/ungdungdoctruyen/EcomicType.java
UTF-8
4,043
1.882813
2
[]
no_license
package com.group1.app.ungdungdoctruyen; import com.group1.app.ungdungdoctruyen.adapter.RssCustomLv; import android.annotation.SuppressLint; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.Toast; @SuppressLint("NewApi") public class EcomicType extends Activity { BroadcastReceiver broadcastReceiver; boolean network = false; ListView lvEcomicType; String[] arrTypeEcomic = { "18+", "Comedy", "Horror", "Action", "Anime", "Trinh thám", "Truyện full", "Romance", "VN comic", "School life", "Super Natural", "Người lớn" }; String[] arrTitle = new String[20]; String[] arrDate = new String[20]; String[] arrLink = new String[20]; String[] arrURL = new String[20]; RssCustomLv adapter; int index1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ecomic_type); lvEcomicType = (ListView) findViewById(R.id.lvEcomicType); listenNetwork(); getActionBar().setDisplayHomeAsUpEnabled(true); Intent it = getIntent(); int index = it.getIntExtra("index", MODE_PRIVATE); this.setTitle(arrTypeEcomic[index]); switch (index) { case 0: index1 = 0; break; case 1: index1 = 20; break; case 2: index1 = 40; break; case 3: index1 = 60; break; case 4: index1 = 80; break; case 5: index1 = 100; break; case 6: index1 = 120; break; case 7: index1 = 140; break; case 8: index1 = 160; break; case 9: index1 = 180; break; case 10: index1 = 200; break; // case 11: // index1 = 220; // index2 = index1 + 18; } for (int i = 0; i < 20; i++) { arrTitle[i] = Tab1.arrlData.get(i+index1).getTitle(); arrDate[i] = Tab1.arrlData.get(i+index1).getDate(); arrLink[i] = Tab1.arrlData.get(i+index1).getLink(); arrURL[i] = Tab1.arrlData.get(i+index1).getImages(); } adapter = new RssCustomLv(EcomicType.this, arrTitle, arrDate, arrURL); lvEcomicType.setAdapter(adapter); lvEcomicType.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if (network) { Intent it = new Intent(EcomicType.this, RssWebView.class); it.putExtra("link", arrLink[arg2]); startActivity(it); overridePendingTransition(R.animator.push_up_in, R.animator.push_up_out); }else{ Intent it = new Intent(EcomicType.this, ActivityErrorNetwork.class); startActivity(it); overridePendingTransition(R.animator.push_up_in, R.animator.push_up_out); } } }); } @Override public void onBackPressed() { // TODO Auto-generated method stub //super.onBackPressed(); finish(); overridePendingTransition(R.animator.push_down_in, R.animator.push_down_out); } public void listenNetwork(){ broadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectivityManager .getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { network = true; } else { network = false; } } }; IntentFilter filter = new IntentFilter(); filter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); registerReceiver(broadcastReceiver, filter); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (android.R.id.home == item.getItemId()) { onBackPressed(); } return super.onOptionsItemSelected(item); } }
true
0de59530d1d2feccd0aaa6ed89fb1638fe1cd879
Java
sjainit/xmldataprocessor-master
/Manage_Customer_Data/src/main/java/com/companyname/ManageCustomerData/data/service/TestDataService.java
UTF-8
1,021
2.203125
2
[]
no_license
package com.companyname.ManageCustomerData.data.service; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.companyname.ManageCustomerData.domain.KeyValue;; @Service public class TestDataService { public Map<String, KeyValue> getJson(MultipartFile File) throws Exception { File file = convert(File); System.out.println(File); return FragmentControlHandler.passfile(file); } public Map<String, KeyValue> getJson1(File file) throws Exception { System.out.println(FragmentControlHandler.passfile(file)); return FragmentControlHandler.passfile(file); } public static File convert(MultipartFile file) throws IOException { File convFile = new File(file.getOriginalFilename()); convFile.createNewFile(); FileOutputStream fos = new FileOutputStream(convFile); fos.write(file.getBytes()); fos.close(); return convFile; } }
true
0f317c94fc7faaa57e50f95037a2cba651a67fef
Java
chenrunlin/BasicUtils
/BasicUtils/src/test/java/com/test/simple_test/IntegetTest.java
UTF-8
1,271
3.5
4
[]
no_license
package com.test.simple_test; public class IntegetTest { /** * 结论: Integer 类型的值在[-128,127] 期间,Integer 用 “==”是可以的。Integer与 int 类型比较(==)比较的是值。 */ public static void main(String[] args) throws Exception { Integer a = -129; Integer a1 = -129; Integer aaa = new Integer(-129); Integer aa = -128; Integer aa1 = -128; System.out.println("a==a1:" + (a == a1)); // a==a1:false System.out.println("aa==aa1:" + (aa == aa1)); // aa==aa1:true System.out.println("aaa==a:" + (aaa == a)); // aaa==a:false System.out.println("aaa==a1:" + (aaa == a1)); // aaa==a1:false System.out.println("a.equals(a1):" + a.equals(a1)); // a.equals(a1):true Integer b = 128; Integer b1 = 128; System.out.println("b==b1:" + (b == b1)); // b==b1:false System.out.println("b.equals(b1):" + b.equals(b1)); // b.equals(b1):true Integer c = 127; Integer cc = 127; Integer d = 1; Integer dd = 1; System.out.println("c==cc:" + (c == cc)); // c==cc:true System.out.println("d==dd:" + (d == dd)); // d==dd:true Integer e = 128; int e1 = 128; System.out.println("e == e1:" + (e == e1)); // e == e1:true } }
true
26f5d7fffcbd21048e3c38349c3da7ff23ccb3ab
Java
janiojunior/PetShop
/src/br/unitins/petshop/dao/UsuarioDAO.java
UTF-8
8,630
2.421875
2
[]
no_license
package br.unitins.petshop.dao; import java.sql.Connection; import java.sql.Date; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import br.unitins.petshop.model.Perfil; import br.unitins.petshop.model.Usuario; public class UsuarioDAO implements DAO<Usuario> { public Usuario validarLogin(Usuario usuario) { Connection conn = DAO.getConnection(); Usuario usuarioLogado = null; StringBuffer sql = new StringBuffer(); sql.append("SELECT "); sql.append(" u.id, "); sql.append(" u.cpf, "); sql.append(" u.nome, "); sql.append(" u.email, "); sql.append(" u.data_nascimento, "); sql.append(" u.login, "); sql.append(" u.senha, "); sql.append(" u.perfil "); sql.append("FROM "); sql.append(" usuario u "); sql.append("WHERE "); sql.append(" u.login = ? "); sql.append(" AND u.senha = ? "); PreparedStatement stat = null; try { stat = conn.prepareStatement(sql.toString()); stat.setString(1, usuario.getLogin()); stat.setString(2, usuario.getSenha()); ResultSet rs = stat.executeQuery(); if(rs.next()) { usuarioLogado = new Usuario(); usuarioLogado.setId(rs.getInt("id")); usuarioLogado.setCpf(rs.getString("cpf")); usuarioLogado.setNome(rs.getString("nome")); usuarioLogado.setEmail(rs.getString("email")); Date data = rs.getDate("data_nascimento"); usuarioLogado.setDataNascimento(data == null ? null : data.toLocalDate()); usuarioLogado.setLogin(rs.getString("login")); usuarioLogado.setSenha(rs.getString("senha")); usuarioLogado.setPerfil(Perfil.valueOf(rs.getInt("perfil"))); } } catch (Exception e) { e.printStackTrace(); usuarioLogado = null; } finally { try { stat.close(); } catch (Exception e) { e.printStackTrace(); } try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } return usuarioLogado; } @Override public boolean inserir(Usuario obj) { Connection conn = DAO.getConnection(); boolean deuErro = false; StringBuffer sql = new StringBuffer(); sql.append("INSERT INTO usuario "); sql.append(" (cpf, nome, email, data_nascimento, login, senha, perfil) "); sql.append("VALUES "); sql.append(" (?, ?, ?, ?, ?, ?, ? ) "); PreparedStatement stat = null; try { stat = conn.prepareStatement(sql.toString()); stat.setString(1, obj.getCpf()); stat.setString(2, obj.getNome()); stat.setString(3, obj.getEmail()); if (obj.getDataNascimento() == null) stat.setDate(4, null); else stat.setDate(4, Date.valueOf(obj.getDataNascimento())); stat.setString(5, obj.getLogin()); stat.setString(6, obj.getSenha()); if (obj.getPerfil() != null) stat.setInt(7, obj.getPerfil().getValue()); else stat.setObject(7, null); stat.execute(); } catch (SQLException e) { e.printStackTrace(); deuErro = true; } finally { try { stat.close(); } catch (Exception e) { e.printStackTrace(); } try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } if (deuErro) return false; return true; } @Override public boolean alterar(Usuario obj) { Connection conn = DAO.getConnection(); boolean deuErro = false; StringBuffer sql = new StringBuffer(); sql.append("UPDATE usuario SET "); sql.append(" cpf = ?, "); sql.append(" nome = ?, "); sql.append(" email = ?, "); sql.append(" data_nascimento = ?, "); sql.append(" login = ?, "); sql.append(" senha = ?, "); sql.append(" perfil = ? "); sql.append("WHERE "); sql.append(" id = ? "); PreparedStatement stat = null; try { stat = conn.prepareStatement(sql.toString()); stat.setString(1, obj.getCpf()); stat.setString(2, obj.getNome()); stat.setString(3, obj.getEmail()); if (obj.getDataNascimento() == null) stat.setDate(4, null); else stat.setDate(4, Date.valueOf(obj.getDataNascimento())); stat.setString(5, obj.getLogin()); stat.setString(6, obj.getSenha()); if (obj.getPerfil() != null) stat.setInt(7, obj.getPerfil().getValue()); else stat.setObject(7, null); stat.setInt(8, obj.getId()); stat.execute(); } catch (Exception e) { e.printStackTrace(); deuErro = true; } finally { try { stat.close(); } catch (Exception e) { e.printStackTrace(); } try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } if (deuErro) return false; return true; } @Override public boolean excluir(Integer id) { Connection conn = DAO.getConnection(); boolean deuErro = false; StringBuffer sql = new StringBuffer(); sql.append("DELETE FROM usuario WHERE id = ? "); PreparedStatement stat = null; try { stat = conn.prepareStatement(sql.toString()); stat.setInt(1, id); stat.execute(); } catch (SQLException e) { e.printStackTrace(); deuErro = true; } finally { try { stat.close(); } catch (Exception e) { e.printStackTrace(); } try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } if (deuErro) return false; return true; } @Override public List<Usuario> obterTodos() { Connection conn = DAO.getConnection(); List<Usuario> listaUsuario = new ArrayList<Usuario>(); StringBuffer sql = new StringBuffer(); sql.append("SELECT "); sql.append(" u.id, "); sql.append(" u.cpf, "); sql.append(" u.nome, "); sql.append(" u.email, "); sql.append(" u.data_nascimento, "); sql.append(" u.login, "); sql.append(" u.senha, "); sql.append(" u.perfil "); sql.append("FROM "); sql.append(" usuario u "); sql.append("ORDER BY u.nome "); PreparedStatement stat = null; try { stat = conn.prepareStatement(sql.toString()); ResultSet rs = stat.executeQuery(); while(rs.next()) { Usuario usuario = new Usuario(); usuario.setId(rs.getInt("id")); usuario.setCpf(rs.getString("cpf")); usuario.setNome(rs.getString("nome")); usuario.setEmail(rs.getString("email")); Date data = rs.getDate("data_nascimento"); usuario.setDataNascimento(data == null ? null : data.toLocalDate()); usuario.setLogin(rs.getString("login")); usuario.setSenha(rs.getString("senha")); usuario.setPerfil(Perfil.valueOf(rs.getInt("perfil"))); listaUsuario.add(usuario); } } catch (Exception e) { e.printStackTrace(); listaUsuario = null; } finally { try { stat.close(); } catch (Exception e) { e.printStackTrace(); } try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } if (listaUsuario == null || listaUsuario.isEmpty()) return null; return listaUsuario; } @Override public Usuario obterUm(Integer id) { Connection conn = DAO.getConnection(); Usuario usuario = null; StringBuffer sql = new StringBuffer(); sql.append("SELECT "); sql.append(" u.id, "); sql.append(" u.cpf, "); sql.append(" u.nome, "); sql.append(" u.email, "); sql.append(" u.data_nascimento, "); sql.append(" u.login, "); sql.append(" u.senha, "); sql.append(" u.perfil "); sql.append("FROM "); sql.append(" usuario u "); sql.append("WHERE "); sql.append(" u.id = ? "); PreparedStatement stat = null; try { stat = conn.prepareStatement(sql.toString()); stat.setInt(1, id); ResultSet rs = stat.executeQuery(); if(rs.next()) { usuario = new Usuario(); usuario.setId(rs.getInt("id")); usuario.setCpf(rs.getString("cpf")); usuario.setNome(rs.getString("nome")); usuario.setEmail(rs.getString("email")); Date data = rs.getDate("data_nascimento"); usuario.setDataNascimento(data == null ? null : data.toLocalDate()); usuario.setLogin(rs.getString("login")); usuario.setSenha(rs.getString("senha")); usuario.setPerfil(Perfil.valueOf(rs.getInt("perfil"))); } } catch (Exception e) { e.printStackTrace(); usuario = null; } finally { try { stat.close(); } catch (Exception e) { e.printStackTrace(); } try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } return usuario; } }
true
9c6ed8f4698f9f6a96dc51cd3a9b86d2c66ba807
Java
eddy0055/xFaceRepo
/xfaceV2/src/main/java/com/xpand/xface/dao/BoatDAO.java
UTF-8
1,016
2.078125
2
[ "Apache-2.0" ]
permissive
package com.xpand.xface.dao; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.xpand.xface.entity.Boat; @Repository public interface BoatDAO extends JpaRepository<Boat, Integer>{ public Boat findByBoatCode(String boatCode); public Boat findByBoatShortName(String boatShortName); public Boat findByCardNo(String cardNo); @Override public List<Boat> findAll(); @Query("SELECT bo FROM Boat bo where boatCode <> :unknownBoatCode ") public List<Boat> findNormalBoat(@Param("unknownBoatCode") String unknownBoatCode); @Modifying @Query("delete from Boat where boatId = :boatId ") public void deleteById(@Param("boatId") Integer boatId); public Boat findOneByBoatCode(String boatCode); public void deleteByBoatCode(String boatCode); }
true
55afb253c05e0ca15fcc4a4bbaa9efde91712906
Java
rockguo2015/med
/com.fudanmed.platform.core.web/src/main/java/com/fudanmed/platform/core/web/client/warehouse/TopLevelProductCategoryProvider.java
UTF-8
764
1.789063
2
[]
no_license
package com.fudanmed.platform.core.web.client.warehouse; import com.fudanmed.platform.core.warehouse.proxy.RCProductCategoryProxy; import com.fudanmed.platform.core.web.client.warehouse.TopLevelProductCategoryProviderServiceAsync; import com.google.inject.Inject; import com.uniquesoft.gwt.client.common.ServiceCallback; import com.uniquesoft.gwt.client.common.widgets.contentprovider.AbstractAsyncContentProvider; import java.util.Collection; public class TopLevelProductCategoryProvider extends AbstractAsyncContentProvider<RCProductCategoryProxy> { @Inject private TopLevelProductCategoryProviderServiceAsync service; protected void doGetContent(final ServiceCallback<Collection<RCProductCategoryProxy>> callback) { service.load(callback); } }
true
fd274e2084db670060ab0c106aa5f56340f4fc53
Java
kvburke/charterassessment
/src/main/java/com/charter/assessment/entity/Purchase.java
UTF-8
2,052
2.4375
2
[]
no_license
package com.charter.assessment.entity; import com.charter.assessment.repository.CustomerRepository; import javax.persistence.*; import java.math.BigDecimal; @Entity(name="Purchase") public class Purchase { @Id @SequenceGenerator( name="purchase_sequence", sequenceName = "purchase_sequence", allocationSize = 1 ) @GeneratedValue( strategy = GenerationType.SEQUENCE, generator = "purchase_sequence" ) @Column( name="id", updatable = false ) private Long id; @Column( name="name", nullable= false ) private String name; @Column( name="price", nullable= false ) private BigDecimal price; @ManyToOne @JoinColumn( name= "customer_id", nullable = false, referencedColumnName = "id", foreignKey = @ForeignKey( name= "customer_order_fk" ) ) private Customer customer; public Purchase(String name, BigDecimal price, Customer customer) { this.name = name; this.price = price; this.customer= customer; } public Purchase() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } @Override public String toString() { return "Purchase{" + "id=" + id + ", name='" + name + '\'' + ", price=" + price + ", customer=" + customer + '}'; } }
true
3583dc730fde310674548fe7d9ac0bf6cc9f4204
Java
cellosofia/jboss-common-core
/src/main/java/org/jboss/util/loading/Translator.java
UTF-8
3,070
2.09375
2
[ "Apache-2.0" ]
permissive
/* * JBoss, Home of Professional Open Source * Copyright 2015, Red Hat, Inc., and individual contributors as indicated * by the @authors tag. * * 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.jboss.util.loading; import java.security.ProtectionDomain; /** An interface for transforming byte code before Class creation. This is * compatible with the JDK1.5 java.lang.instrument.ClassFileTransformer * proposal. * * @author Scott.Stark@jboss.org * @version $Revision$ */ public interface Translator { /** Optionally transform the supplied class file and return a new replacement * class file. * * <P> If a transformer has been registered with the class loading layer, * the transformer will be called for every new class definition. * The request for a new class definition is made with defineClass * The transformer is called during the processing of the request, before * the class file bytes have been verified or applied. * * <P> * If the implementing method determines that no transformations are needed, * it should return <code>null</code>. Otherwise, it should create a new * byte[] array and copy the input <code>classfileBuffer</code> into it, * along with all desired transformations. The input <code>classfileBuffer</code> * must not be modified. * * @param loader - the defining loader of the class to be transformed, may * be <code>null</code> if the bootstrap loader * @param className - the fully-qualified name of the class * @param classBeingRedefined - if this is a redefine, the class being * redefined, otherwise <code>null</code> * @param protectionDomain - the protection domain of the class being * defined or redefined * @param classfileBuffer - the input byte buffer in class file format - must * not be modified * * @throws Exception - if the input does not represent a well-formed class file * @return a well-formed class file buffer (the result of the transform), * or <code>null</code> if no transform is performed. */ public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws Exception; /** Called to indicate that the ClassLoader is being discarded by the server. * * @param loader - a class loader that has possibly been used previously * as an argument to transform. */ public void unregisterClassLoader(ClassLoader loader); }
true
7f85ed9fc1a3dad71f3f6635a9c013d663ef3b3d
Java
anuragmadde/kafka
/KafkaSpringBoot/src/main/java/com/hackathon/kafka/ProducerCallback.java
UTF-8
486
2.546875
3
[]
no_license
package com.hackathon.kafka; import org.apache.kafka.clients.producer.Callback; import org.apache.kafka.clients.producer.RecordMetadata; public class ProducerCallback implements Callback{ @Override public void onCompletion(RecordMetadata metadata, Exception exception) { if(exception !=null){ System.out.println("asynchrous callback exception - " +exception); } else{ System.out.println("asynchronous callback successfull. Metadata : "+ metadata.toString()); } } }
true
d0565d6ba0d952b0a685630e27219a7dfc80ca08
Java
OCrespoJ/HDN2_NAVES
/app/src/main/java/com/oscar/hdn2_oscar_crespo/modelos/ModelosPersonajes.java
UTF-8
2,060
2.890625
3
[]
no_license
package com.oscar.hdn2_oscar_crespo.modelos; import com.oscar.hdn2_oscar_crespo.R; import java.util.ArrayList; import com.oscar.hdn2_oscar_crespo.beans.PersonajeBean; public class ModelosPersonajes { public static ArrayList <PersonajeBean> getPersonaje () { ArrayList<PersonajeBean> personajes = new ArrayList<>(); personajes.add(new PersonajeBean( R.drawable.prota, "Protagonista", "Esta es la nave que controlaremos nosotros. Es una rápida nave de carreras" + "que usaremos para acabar con todos los enemigos. " + "Podremos movernos arriba y abajo " + " con las flechas del teclado y disparar pulsando el boton espacio", "Esta nave dispondrá de 10 vidas y unas balas láser con una velocidad normal y un daño bajo." + "Podrá tener más tipos de balas recogiendo esferas por el mapa, como pueden ser " + "disparos explisivos, rápidos, o bombas")); personajes.add(new PersonajeBean( R.drawable.enemy, "Enemigo", "Esta es la nave que usarán los enemigos más débiles. Nuestro objetivo será abatir " + "a tantas de estas naves como podamos para poder enfrentarnos al " + "boss final.", "Estos enemigos dispondrán solo de 1 vida, y dispondrán de unos disparos normales, " + "como los que tiene nuestra nave al principio")); personajes.add(new PersonajeBean( R.drawable.boss, "Boss", "Es el enemigo más poderoso, mucho más grande que los enemigos normales, más fuerte " + "y con ataques especiales. Deberemos derrotarlo para ganar la partida", "El boss dispondrán de 500 de vida, y podrá disparar balas de muchos tipos. Es el enemigo más difícil de derrotar")); return personajes; } }
true
39204633fbaa0dd30eb3877d09932f2ad842cef3
Java
bote100/DynamicRocket
/DynamicRocket-API/src/main/java/net/bote/rocketapi/bridge/server/GroupConfiguration.java
UTF-8
2,545
2.703125
3
[]
no_license
package net.bote.rocketapi.bridge.server; import net.bote.rocketapi.lib.Document; import java.io.File; /** * @author Elias Arndt * created on 22.10.2018 at 14:21 * * This object contains all informations of a server group. */ public class GroupConfiguration { private int slots; private int ram; private String title; private int newstart; private int globalnewstart; private boolean lobby; /** * Constructor * @param slots Slots of an server of the group * @param ram RAM per server * @param title name of the group * @param newstart how many players must be in the * group to start new server of the group? * @param globalnewstart how many players must be on * the server to start new server of the group? * @param lobby if it's a lobby server */ public GroupConfiguration(int slots, int ram, String title, int newstart, int globalnewstart, boolean lobby) { this.slots = slots; this.ram = ram; this.title = title; this.newstart = newstart; this.globalnewstart = globalnewstart; this.lobby = lobby; } public boolean isLobby() { return lobby; } public void setSlots(int slots) { this.slots = slots; } public int getRam() { return ram; } public void setRam(int ram) { this.ram = ram; } public String getName() { return title; } public void setTitle(String title) { this.title = title; } public int getNewstart() { return newstart; } public void setNewstart(int newstart) { this.newstart = newstart; } public int getGlobalnewstart() { return globalnewstart; } public void setGlobalnewstart(int globalnewstart) { this.globalnewstart = globalnewstart; } public int getSlots() { return slots; } /** * static method to get GroupConfiguration * @param name name of the servergroup * @return new GroupConfiguration */ public static GroupConfiguration getGroupConfiguration(String name) { Document doc = Document.loadDocument(new File("groups/" + name + ".json")); return new GroupConfiguration( doc.getInt("slots"), doc.getInt("ram"), doc.getString("name"), doc.getInt("groupstart"), doc.getInt("globalstart"), doc.getBoolean("isLobby")); } }
true
f21c3a61b4b1533f74aadb2204347819281b9707
Java
LovingMy/BaseUtil
/test/src/test/java/com/che/test/rxjava/asyncwork/Func.java
UTF-8
125
1.953125
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.che.test.rxjava.asyncwork; /** * 类型变换泛型接口 */ public interface Func<T, R> { R call(T t); }
true
fc7add646d4b14c30e9bde372f3963bafb64be3d
Java
podplatnikm/Ekoloske-kmetije-slovenije
/src/si/um/feri/uporabnik/Uporabnik.java
UTF-8
4,690
2.15625
2
[]
no_license
package si.um.feri.uporabnik; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.hibernate.search.annotations.*; import org.hibernate.search.annotations.Index; import si.um.feri.paket.Paket; import javax.persistence.*; import java.io.Serializable; import java.util.Calendar; import java.util.List; /** * Created by Miha on 22/05/2017. */ @Entity public class Uporabnik implements Serializable{ @Id @GeneratedValue( strategy= GenerationType.AUTO ) private long id; @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO) @Analyzer(definition = "analizatorpomeri") private String email; @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO) @Analyzer(definition = "analizatorpomeri") private String naziv; private String opis; private String telefonskaStevilka; private Calendar datumPridruzitve; //NASLOV private String naslov; private int posta; @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO) @Analyzer(definition = "analizatorpomeri") private String kraj; @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO) @Analyzer(definition = "analizatorpomeri") private String ime; @Field(index=Index.YES, analyze=Analyze.YES, store=Store.NO) @Analyzer(definition = "analizatorpomeri") private String priimek; private String idApi; private int tip; @ManyToMany (cascade = CascadeType.ALL) private List<Uporabnik> priljubljeneKmetije; @ManyToMany (cascade = CascadeType.ALL) private List<Paket> paketi; public Uporabnik() { } public Uporabnik(UporabnikBuilder uporabnikBuilder){ this.email = uporabnikBuilder.getEmail(); this.idApi = uporabnikBuilder.getIdApi(); this.ime = uporabnikBuilder.getIme(); this.kraj = uporabnikBuilder.getKraj(); this.priimek = uporabnikBuilder.getPriimek(); this.naslov = uporabnikBuilder.getNaslov(); this.naziv = uporabnikBuilder.getNaziv(); this.opis = uporabnikBuilder.getOpis(); this.posta = uporabnikBuilder.getPosta(); this.tip = uporabnikBuilder.getTip(); this.telefonskaStevilka = uporabnikBuilder.getTelefonskaStevilka(); this.datumPridruzitve = uporabnikBuilder.getDatumKreacije(); } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getTip() { return tip; } public void setTip(int tip) { this.tip = tip; } public String getIdApi() { return idApi; } public void setIdApi(String idApi) { this.idApi = idApi; } public String getNaziv() { return naziv; } public void setNaziv(String naziv) { this.naziv = naziv; } public String getOpis() { return opis; } public void setOpis(String opis) { this.opis = opis; } public String getTelefonskaStevilka() { return telefonskaStevilka; } public void setTelefonskaStevilka(String telefonskaStevilka) { this.telefonskaStevilka = telefonskaStevilka; } public String getNaslov() { return naslov; } public void setNaslov(String naslov) { this.naslov = naslov; } public int getPosta() { return posta; } public void setPosta(int posta) { this.posta = posta; } public String getKraj() { return kraj; } public void setKraj(String kraj) { this.kraj = kraj; } public String getIme() { return ime; } public void setIme(String ime) { this.ime = ime; } public String getPriimek() { return priimek; } public void setPriimek(String priimek) { this.priimek = priimek; } @Override public String toString() { Gson g = new GsonBuilder().setPrettyPrinting().create(); return g.toJson(this); } public Calendar getDatumPridruzitve() { return datumPridruzitve; } public void setDatumPridruzitve(Calendar datumPridruzitve) { this.datumPridruzitve = datumPridruzitve; } public List<Uporabnik> getPriljubljeneKmetije() { return priljubljeneKmetije; } public void setPriljubljeneKmetije(List<Uporabnik> priljubljeneKmetije) {this.priljubljeneKmetije = priljubljeneKmetije;} public List<Paket> getPaketi() {return paketi;} public void setPaketi(List<Paket> paketi) {this.paketi = paketi;} }
true
9ec8f7dca10be51ee24e6c306e55a0133368eebb
Java
AdamenkoA/Loyalty
/app/src/main/java/com/example/adamenko/loyalty/DataBase/MySQLiteHelper.java
UTF-8
13,179
2.375
2
[]
no_license
package com.example.adamenko.loyalty.DataBase; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.example.adamenko.loyalty.Content.EventContent; import com.example.adamenko.loyalty.Content.SettingsContent; import com.example.adamenko.loyalty.Content.TopicContent; import com.example.adamenko.loyalty.R; import java.util.ArrayList; import java.util.List; public class MySQLiteHelper extends SQLiteOpenHelper { private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = R.string.file_name + "DB"; private static final String TABLE_SETTINGS = "Settings"; private static final String TABLE_EVENTS = "Events"; private static final String TABLE_TOPICS = "Topics"; private static final String KEY_ID = "id"; private static final String KEY_TOPIC_ID = "topicId"; private static final String KEY_KEY = "key"; private static final String KEY_VALUE = "value"; private static final String KEY_TITLE = "title"; private static final String KEY_DESCRIPTION = "description"; private static final String KEY_SUBSCRIBE = "subscribe"; private static final String KEY_DATE = "date"; private static final String KEY_TIME = "time"; private static final String KEY_COLOR = "color"; private String CREATE_TABLE_SETTINGS = ""; private String CREATE_TABLE_EVENTS = ""; private String CREATE_TABLE_TOPICS = ""; public MySQLiteHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); CREATE_TABLE_SETTINGS = context.getResources().getString(R.string.DB_Settings); CREATE_TABLE_EVENTS = context.getResources().getString(R.string.DB_Events); CREATE_TABLE_TOPICS = context.getResources().getString(R.string.DB_Topics); } @Override public void onCreate(SQLiteDatabase db) { // SQL statement to create book table try { db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTINGS); db.execSQL(CREATE_TABLE_SETTINGS); db.execSQL("DROP TABLE IF EXISTS " + TABLE_EVENTS); db.execSQL(CREATE_TABLE_EVENTS); db.execSQL("DROP TABLE IF EXISTS " + TABLE_TOPICS); db.execSQL(CREATE_TABLE_TOPICS); } catch (Exception e) { e.printStackTrace(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older books table if existed db.execSQL("DROP TABLE IF EXISTS " + TABLE_SETTINGS); db.execSQL("DROP TABLE IF EXISTS " + TABLE_EVENTS); db.execSQL("DROP TABLE IF EXISTS " + TABLE_TOPICS); // create fresh books table this.onCreate(db); } public void addSettings(SettingsContent setting) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_KEY, setting.getKey()); values.put(KEY_VALUE, setting.getValue()); db.insert(TABLE_SETTINGS, // table null, //nullColumnHack values); // key/value -> keys = column names/ values = column values db.close(); } public void updateSettings(SettingsContent settingsContent) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_VALUE, settingsContent.getValue()); values.put(KEY_KEY, settingsContent.getKey()); int i = db.update(TABLE_SETTINGS, values, KEY_ID + " = ?", new String[]{String.valueOf(settingsContent.getId())}); db.close(); } public String getSettings(String key) { SQLiteDatabase db = this.getReadableDatabase(); String sc = ""; Cursor cursor = db.query(TABLE_SETTINGS, new String[]{KEY_VALUE}, "key = " + "\'" + String.valueOf(key) + "\'", null, null, null, null, null); if ((cursor != null ? cursor.getCount() : 0) != 0) { cursor.moveToFirst(); sc = cursor.getString(0); } return sc; } public void deleteSettings(SettingsContent settingsContent) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_SETTINGS, KEY_ID + " = ?", new String[]{String.valueOf(settingsContent.getId())}); db.close(); } public void addTopics(TopicContent topic) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_ID, topic.getId()); values.put(KEY_TITLE, topic.getTitle()); values.put(KEY_DESCRIPTION, topic.getDescription()); values.put(KEY_SUBSCRIBE, topic.getSubscribe()); values.put(KEY_COLOR, topic.getColor()); if (getId(TABLE_TOPICS, topic.getId() + "", db)) { db.insert(TABLE_TOPICS, null, values); } else db.update(TABLE_TOPICS, values, KEY_ID + " = ?", new String[]{topic.getId() + ""}); db.close(); } public int updateTopics(TopicContent topic) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_ID, topic.getId()); values.put(KEY_TITLE, topic.getTitle()); values.put(KEY_DESCRIPTION, topic.getDescription()); values.put(KEY_SUBSCRIBE, topic.getSubscribe()); values.put(KEY_COLOR, topic.getSubscribe()); int i = db.update(TABLE_TOPICS, values, KEY_ID + " = ?", new String[]{String.valueOf(topic.getId())}); db.close(); return i; } public List<TopicContent> getTopics() { // 1. get reference to readable DB SQLiteDatabase db = this.getReadableDatabase(); List<TopicContent> topics = new ArrayList<>(); // 2. build query Cursor cursor = db.query(TABLE_TOPICS, // a. table new String[]{"*"}, // b. column names null, // c. selections null, // d. selections args null, // e. group by null, // f. having null, // g. order by null); // h. limit if (cursor.moveToFirst()) { while (!cursor.isAfterLast()) { String id = cursor.getString(cursor.getColumnIndex(KEY_ID)); String title = cursor.getString(cursor.getColumnIndex(KEY_TITLE)); String description = cursor.getString(cursor.getColumnIndex(KEY_DESCRIPTION)); Boolean subscribe = cursor.getInt(cursor.getColumnIndex(KEY_SUBSCRIBE)) > 0; String color = cursor.getString(cursor.getColumnIndex(KEY_COLOR)); topics.add(new TopicContent(Integer.parseInt(id), title, description, subscribe, color)); cursor.moveToNext(); } } return topics; } public TopicContent getTopic(String topicId) { SQLiteDatabase db = this.getReadableDatabase(); String id = ""; String title = ""; String description = ""; Boolean subscribe = false; String color = ""; Cursor cursor = db.query(TABLE_TOPICS, // a. table new String[]{"*"}, // c. selections KEY_ID + "= ?", // b. column names new String[]{topicId + ""}, // d. selections args null, // e. group by null, // f. having null, // g. order by null); // h. limit if (cursor.moveToFirst()) { id = cursor.getString(cursor.getColumnIndex(KEY_ID)); title = cursor.getString(cursor.getColumnIndex(KEY_TITLE)); description = cursor.getString(cursor.getColumnIndex(KEY_DESCRIPTION)); subscribe = cursor.getInt(cursor.getColumnIndex(KEY_SUBSCRIBE)) > 0; color = cursor.getString(cursor.getColumnIndex(KEY_COLOR)); } return new TopicContent(Integer.parseInt(id), title, description, subscribe, color); } public void deleteTopic(TopicContent topic) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_TOPICS, //table name KEY_ID + " = ?", // selections new String[]{String.valueOf(topic.getId())}); //selections args // 3. close db.close(); } public void deleteAllTopic() { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_TOPICS, null, null); db.close(); } public void addEvents(EventContent event) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_ID, event.getId()); values.put(KEY_DESCRIPTION, event.getDescription()); values.put(KEY_TITLE, event.getTitle()); values.put(KEY_DATE, event.getDate()); values.put(KEY_TIME, event.getTime()); values.put(KEY_TOPIC_ID, event.getTopicId()); if (getId(TABLE_EVENTS, event.getId(), db)) { db.insert(TABLE_EVENTS, null, values); } else db.update(TABLE_EVENTS, values, KEY_ID + " = ?", new String[]{String.valueOf(event.getId())}); db.close(); } public List<EventContent> getEvents() { // 1. get reference to readable DB SQLiteDatabase db = this.getReadableDatabase(); List<EventContent> event = new ArrayList<>(); // 2. build query Cursor cursor = db.query(TABLE_EVENTS, new String[]{"*"}, null, null, null, null, null, null); if (cursor.moveToFirst()) { while (!cursor.isAfterLast()) { String id = cursor.getString(cursor.getColumnIndex(KEY_ID)); String title = cursor.getString(cursor.getColumnIndex(KEY_TITLE)); String descrpition = cursor.getString(cursor.getColumnIndex(KEY_DESCRIPTION)); String date = cursor.getString(cursor.getColumnIndex(KEY_DATE)); String time = cursor.getString(cursor.getColumnIndex(KEY_TIME)); String topic_id = cursor.getString(cursor.getColumnIndex(KEY_TOPIC_ID)); String color = cursor.getString(cursor.getColumnIndex(KEY_COLOR)); if (color==null){ color=getTopic(topic_id).getColor(); } event.add(new EventContent(id, topic_id, date, time, title, descrpition, color)); cursor.moveToNext(); } } return event; } public int updateEvents(EventContent event) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_ID, event.getId()); values.put(KEY_DESCRIPTION, event.getDescription()); values.put(KEY_TITLE, event.getTitle()); values.put(KEY_DATE, event.getDate()); values.put(KEY_TIME, event.getTitle()); values.put(KEY_TOPIC_ID, event.getTopicId()); int i = db.update(TABLE_EVENTS, values, KEY_ID + " = ?", new String[]{String.valueOf(event.getId())}); db.close(); return i; } public void deleteEvents(EventContent event) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_EVENTS, KEY_ID + " = ?", new String[]{String.valueOf(event.getId())}); db.close(); } public void deleteAllEvents() { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_EVENTS, null, null); db.close(); } private boolean getId(String table, String id, SQLiteDatabase db) { Cursor cursor = db.query(table, new String[]{KEY_ID}, KEY_ID + "= ?", new String[]{id}, null, null, null, null); return cursor.getCount() <= 0; } public boolean getSubscribe(Integer id, SQLiteDatabase db) { Boolean result = false; Cursor cursor = db.query(TABLE_TOPICS, new String[]{KEY_SUBSCRIBE}, KEY_ID + "= ?", new String[]{id + ""}, null, null, null, null); if (cursor != null) cursor.moveToFirst(); if (cursor.getCount() != 0) { result = cursor.getInt(cursor.getColumnIndex(KEY_SUBSCRIBE)) > 0; } return result; } }
true
d2b92279fd85be80868e500bc580852e1de39a7f
Java
Unfunctioned/SBML-Converter-for-ERODE
/src/main/java/sbml/conversion/species/SBMLSpeciesBuilder.java
UTF-8
748
2.046875
2
[]
no_license
package sbml.conversion.species; import it.imt.erode.crn.interfaces.ISpecies; import org.sbml.jsbml.ext.qual.QualitativeSpecies; import sbml.configurations.SBMLConfiguration; class SBMLSpeciesBuilder { private static final SBMLConfiguration CONFIG = SBMLConfiguration.getConfiguration(); public QualitativeSpecies createSpecies(ISpecies species) { QualitativeSpecies q = new QualitativeSpecies(CONFIG.getLevel(),CONFIG.getVersion()); q.setId(species.getName()); q.setName(species.getOriginalName()); q.setCompartment(CONFIG.getDefaultCompartment()); q.setMaxLevel(1); q.setInitialLevel(species.getInitialConcentration().intValue()); q.setConstant(false); return q; } }
true
2b2cbc3a0cb431e4d327c5bbe2b7bc5312dac5d1
Java
PriyankaPawar7910/Insurance-Application-on-External-Tomcat
/claimedPolicy-service/src/main/java/com/insurancepolicy/service/IClaimedPolicyService.java
UTF-8
620
1.851563
2
[]
no_license
package com.insurancepolicy.service; import java.util.List; import com.insurancepolicy.model.ClaimedPolicy; import com.insurancepolicy.model.ResponseTemplate; import com.insurancepolicy.model.User; public interface IClaimedPolicyService { List<ResponseTemplate> getAllClaimPolicies(); ClaimedPolicy addClaimPolicy(ClaimedPolicy claimPolicy); ClaimedPolicy getClaimPolicy(int id); ClaimedPolicy updateClaimPolicy(ClaimedPolicy claimPolicy); List<ClaimedPolicy> deleteClaimPolicy(int planId); List<ResponseTemplate> getClaimPolicyByUser(int userId); List<User> getPolicyHoldersByPolicy(int policyId); }
true
916dc4004b8cb9cde32a2472de4b7f61845d087f
Java
diastowo29/java-capex
/src/main/java/com/example/repository/JettyHeadTypeFormulaRepository.java
UTF-8
247
1.546875
2
[ "MIT" ]
permissive
package com.example.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.example.model.JettyHeadTypeFormula; public interface JettyHeadTypeFormulaRepository extends JpaRepository<JettyHeadTypeFormula, Long> { }
true
6a59a6effbb922f383632155b66e25ca77cdd1f1
Java
tegebe/tapestry5-liferay
/tapestry-liferay-demo/src/main/java/tapestry/liferay/portlets/components/LayoutForPreferences.java
UTF-8
498
1.859375
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package tapestry.liferay.portlets.components; import org.apache.tapestry5.SymbolConstants; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.ioc.annotations.Inject; import org.apache.tapestry5.ioc.annotations.Symbol; /** * Layout component for pages of application preferences pages */ public class LayoutForPreferences { @SuppressWarnings("unused") @Inject @Symbol(value=SymbolConstants.APPLICATION_VERSION) @Property private String applicationVersion; }
true
93e934684c57a6381166efa3f3e747f6c9ea8eee
Java
carlstaana/apollo
/src/com/apollo/training/set3/calc2/SquareRoot.java
UTF-8
384
3.0625
3
[]
no_license
package com.apollo.training.set3.calc2; import java.math.BigDecimal; public class SquareRoot extends CalculatorEngine implements Operation{ @Override public BigDecimal compute(BigDecimal currentValue, BigDecimal value) { value = BigDecimal.valueOf(StrictMath.sqrt(value.doubleValue())); // means: value = square Root of value OR value = Math.sqrt(value); return value; } }
true
58ff8054e73856516e0800bf50a5e028f4c4bd26
Java
RFBGH/javaTest
/src/main/java/com/rfb/demo/rxjavatest/bean/Action1.java
UTF-8
138
1.554688
2
[]
no_license
package com.rfb.demo.rxjavatest.bean; /** * Created by Administrator on 2018/7/23 0023. */ public interface Action1{ void call(); }
true
96e228c8262273b2be95fa0cf68391be50db1188
Java
ghl1024/dbforbix-1
/src/com/smartmarmot/dbforbix/scheduler/MultiColumnItem.java
UTF-8
2,269
2.203125
2
[ "Apache-2.0" ]
permissive
/* * This file is part of DBforBix. * * DBforBix 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. * * DBforBix 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 * DBforBix. If not, see <http://www.gnu.org/licenses/>. */ package com.smartmarmot.dbforbix.scheduler; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import com.smartmarmot.dbforbix.zabbix.ZabbixItem; public class MultiColumnItem extends AbstractMultiItem { public MultiColumnItem(String prefix, String[] items, String query) { super(prefix, items, query); } @Override public ZabbixItem[] getItemData(Connection con, String hostname, int timeout) throws SQLException { Long clock = new Long(System.currentTimeMillis() / 1000L); PreparedStatement pstmt = con.prepareStatement(query); pstmt.setQueryTimeout(timeout); ResultSet rs = pstmt.executeQuery(); String val = noData; Map<String,ZabbixItem> values = new HashMap<>(); // // fill with base items // for (String item: items) // values.put(item, new ZabbixItem(name, "", hostname)); // // // now check if we find better values while (rs.next()) { // String fetchedName = rs.getString(1); // String fetchedVal = rs.getString(2); // if (fetchedVal != null) // val = fetchedVal; // } // else { // int colNum = 1; // try { // colNum = rs.findColumn("value"); // } // catch (SQLException sqlex) { // colNum = meta.getColumnCount(); // last column // } // String fetchedVal = rs.getString(colNum); // if (fetchedVal != null) // val = fetchedVal; // } } rs.close(); pstmt.close(); if (val == null) val = ""; return new ZabbixItem[]{new ZabbixItem(hostname, name, val,clock)}; } }
true
020e57d2b28b5ee29e44bcddd935a4cf64cea55e
Java
ITchild/CanvsViewDemo1
/app/src/main/java/com/fei/canvsviewdemo/activity/buletooth/buleToothActivity.java
UTF-8
423
1.703125
2
[]
no_license
package com.fei.canvsviewdemo.activity.buletooth; import com.fei.canvsviewdemo.R; import com.fei.feilibs_1_0_0.base.ac.BaseActivity; public class buleToothActivity extends BaseActivity { @Override protected int initLayout() { return R.layout.activity_buletooth; } @Override protected boolean isBackshow() { return false; } @Override protected void initView() { } }
true
2eae18af529e930207eff910ce252f5b2fd06d9d
Java
dsaleixo/MicroRTS_Synthesis_LLD
/GAforMicroRTSSOAScaleSG/Synthesis_David/CLG_David/N.java
UTF-8
701
2.84375
3
[]
no_license
package CLG_David; import java.util.ArrayList; import java.util.List; public class N implements AlmostTerminal { String n; public N() { // TODO Auto-generated constructor stub n=null; } public N(String n) { super(); this.n = n; } public String getN() { return n; } public void setN(String n) { this.n = n; } @Override public String getValue() { return n; } @Override public String getName() { return "N"; } @Override public String translate() { return ""+n; } @Override public List<String> Rules(){ List<String> l = new ArrayList<>(); l.add("50"); l.add("1"); l.add("5"); l.add("10"); l.add("25"); return l; } }
true
e8e4daa79d10b52d1d2197aa685f510196d3f978
Java
vishwaschauhan/adobe-analytics-testing
/WSLogsAdaptor/src/adobe/analytics/ws/logs/adapt/LogBeautifier.java
UTF-8
3,408
2.734375
3
[]
no_license
package adobe.analytics.ws.logs.adapt; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; public class LogBeautifier { public static void main(String[] args) throws IOException { convertLog(); /*Files.walk(Paths.get("C:/Users/vishwsin/Desktop/work/logs")).forEach(filePath -> { if (Files.isRegularFile(filePath)) { convertLog(filePath.toString()); } }); */// convertLog(); } private static List<String> convertLog() { try (BufferedReader br = new BufferedReader( new FileReader("C:/Users/vishwsin/Desktop/work/logs/Virtual_RS_20_Requests.log"))) { String sCurrentLine; List<String> sList = new ArrayList<String>(); while ((sCurrentLine = br.readLine()) != null) { if (sCurrentLine.contains("[URL]:")) { System.out.println("------------------------------------------------------------------------------------------------"+"\n\n"); String tempURL = "url: " + sCurrentLine.split((Pattern.quote(" [URL]:")))[1].trim(); sList.add(tempURL); System.out.println(tempURL); { } } if (sCurrentLine.contains("[Post]:") || sCurrentLine.contains("[Get]:")) { String reqBody = "requestbody: "; if (sCurrentLine.contains("{")) { reqBody = reqBody.concat("{"); int openedBrackets = 1; String tempCurrentLine; while (openedBrackets != 0) { tempCurrentLine = br.readLine(); reqBody = reqBody.concat(tempCurrentLine); if (tempCurrentLine.contains("}")) --openedBrackets; if (tempCurrentLine.contains("{")) ++openedBrackets; } System.out.println(reqBody); } } if (sCurrentLine.contains("[Method]")) { String mString = "method: " + sCurrentLine.split((Pattern.quote("]:")))[1].trim(); System.out.println(mString); } if (sCurrentLine.contains("[Response")) { String resp = "response: "; /* * This works on assumption that {\n and \n} are properly * written */ if (sCurrentLine.contains("{")) { resp = resp.concat("{"); int openedBrackets = 1; String tempCurrentLine; while (openedBrackets != 0 && (tempCurrentLine = br.readLine()) != null) { resp = resp.concat(tempCurrentLine); if (tempCurrentLine.contains("}")) --openedBrackets; if (tempCurrentLine.contains("{")) ++openedBrackets; } System.out.println(resp); } else if (sCurrentLine.contains("]: [")) { resp = resp.concat("["); int openedBrackets = 1; String tempCurrentLine; while (openedBrackets != 0 && (tempCurrentLine = br.readLine()) != null) { resp = resp.concat(tempCurrentLine); if (tempCurrentLine.contains("]")) --openedBrackets; if (tempCurrentLine.contains("[")) ++openedBrackets; } System.out.println(resp); } else { String sResp = ""; try { sResp = sCurrentLine.split((Pattern.quote("]:")))[1].trim(); } catch (ArrayIndexOutOfBoundsException ex) { sResp = ""; } resp = resp.concat(sResp); System.out.println(resp); } } } } catch (IOException e) { e.printStackTrace(); } return null; } }
true
58e0f7acf44e74bce49507d053efd42328bf550f
Java
vigour-io/wrapper
/templates/android/plugincore/plugin-core/src/main/java/io/vigour/nativewrapper/plugin/core/Plugin.java
UTF-8
1,378
2.390625
2
[ "MIT" ]
permissive
package io.vigour.nativewrapper.plugin.core; import java.lang.reflect.Method; import java.util.AbstractMap; import java.util.TreeMap; /** * Created by michielvanliempt on 08/04/15. */ public class Plugin { private String name; private AbstractMap<String, PluginFunction> functions = new TreeMap<>(); private BridgeEvents eventInterface; public Plugin(String name) { this.name = name; for (Method m : getClass().getMethods()) { if (m.getDeclaringClass() == getClass() && m.getParameterTypes().length < 2) { register(new ReflectivePluginFunction(m.getName(), m, this)); } } } protected void sendEvent(String event, String data) { eventInterface.receive(event, data, name); } protected void sendError(String message) { eventInterface.receive("error", message, name); } public String getName() { return name; } public String getReadyMessage() { return ""; } public PluginFunction getFunction(String functionName) { return functions.get(functionName); } protected void register(PluginFunction function) { functions.put(function.getName(), function); } public void setEventInterface(BridgeEvents eventInterface) { this.eventInterface = eventInterface; } }
true
f9451fd1455ccb70793c47536a25d301b2bc6383
Java
vsokol/innopolis-homework
/src/main/java/store/sokolov/innopolis/homework_13/task_01/Main.java
UTF-8
1,513
3.375
3
[]
no_license
package store.sokolov.innopolis.homework_13.task_01; import java.util.LinkedList; import java.util.List; /** * ДЗ_13 * Задание 1. Необходимо создать программу, которая продемонстрирует утечку памяти в Java. При этом объекты должны * не только создаваться, но и периодически частично удаляться, чтобы GC имел возможность очищать часть памяти. * Через некоторое время программа должна завершиться с ошибкой OutOfMemoryError c пометкой Java Heap Space. * ----- * запускать с параметром VM -Xmx128m */ public class Main { public static void main(String[] args) { System.out.println("ДЗ_13. Задание 1"); genOutOfMemoryErrorJavaHeapSpace(); } private static void genOutOfMemoryErrorJavaHeapSpace() { int listSize = 1000; List<Object[]> list = new LinkedList<>(); int count = 0; while (true) { Object[] arr = generateData(listSize); if (count % 6 == 0) { list.add(arr); } count++; } } private static Object[] generateData(int length) { Object[] arr = new Object[length]; for (int i = 0; i < arr.length; i++) { arr[i] = new Object(); } return arr; } }
true
f49f1fdb9055b4c04a74a5ad65359ba0d0299fc7
Java
StormITpl/JavaExamples
/kafka/src/main/java/pl/stormit/Transaction.java
UTF-8
586
2.796875
3
[]
no_license
package pl.stormit; import java.util.Date; public final class Transaction { private final Date date; private final String from; private final String to; private final int amount; public Transaction(Date date, String from, String to, int amount) { this.date = date; this.from = from; this.to = to; this.amount = amount; } public Date getDate() { return date; } public String getFrom() { return from; } public String getTo() { return to; } public int getAmount() { return amount; } public boolean isSpecial() { return "SPECIAL".equals(from); } }
true
7a68953ab0bed1f35f7016952ece93135bd725ec
Java
jungleworks/fugu-android
/app/src/main/java/com/skeleton/mvp/data/model/searchgroupuser/Data.java
UTF-8
1,156
1.882813
2
[ "Apache-2.0" ]
permissive
package com.skeleton.mvp.data.model.searchgroupuser; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class Data { @SerializedName("users") @Expose private List<User> users = null; @SerializedName("channels") @Expose private List<Channel> channels = null; @SerializedName("open_groups") @Expose private List<OpenGroup> openGroups = null; @SerializedName("bot") @Expose private List<Bot> bot = null; public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } public List<Channel> getChannels() { return channels; } public void setChannels(List<Channel> channels) { this.channels = channels; } public List<OpenGroup> getOpenGroups() { return openGroups; } public void setOpenGroups(List<OpenGroup> openGroups) { this.openGroups = openGroups; } public List<Bot> getBot() { return bot; } public void setBot(List<Bot> bot) { this.bot = bot; } }
true
c0aac44cce6fab784ecb6af7a3928f936813f810
Java
lcc214321/LogiCommon
/logi-dsl-prase/src/main/java/com/didiglobal/logi/dsl/parse/dsl/parser/query/RangeParser.java
UTF-8
725
1.960938
2
[ "Apache-2.0" ]
permissive
package com.didiglobal.logi.dsl.parse.dsl.parser.query; import com.alibaba.fastjson.JSONObject; import com.didiglobal.logi.dsl.parse.dsl.ast.common.KeyWord; import com.didiglobal.logi.dsl.parse.dsl.ast.common.multi.NodeMap; import com.didiglobal.logi.dsl.parse.dsl.ast.query.Range; import com.didiglobal.logi.dsl.parse.dsl.parser.DslParser; import com.didiglobal.logi.dsl.parse.dsl.parser.ParserType; public class RangeParser extends DslParser { public RangeParser(ParserType type) { super(type); } @Override public KeyWord parse(String name, Object obj) throws Exception { Range node = new Range(name); NodeMap.toField4Value((JSONObject) obj, node.m); return node; } }
true
8e5efa8bc23da72cf81065123b3a70e69e123054
Java
bouzuya/jig
/jig-core/src/main/java/org/dddjava/jig/presentation/view/ViewResolver.java
UTF-8
5,169
2.078125
2
[ "Apache-2.0" ]
permissive
package org.dddjava.jig.presentation.view; import org.dddjava.jig.domain.model.jigdocument.documentformat.JigDocument; import org.dddjava.jig.domain.model.jigdocument.implementation.BusinessRuleRelationDiagram; import org.dddjava.jig.domain.model.jigdocument.implementation.CategoryUsageDiagram; import org.dddjava.jig.domain.model.jigdocument.implementation.ServiceMethodCallHierarchyDiagram; import org.dddjava.jig.domain.model.jigdocument.specification.ArchitectureDiagram; import org.dddjava.jig.domain.model.jigdocument.specification.Categories; import org.dddjava.jig.domain.model.jigdocument.specification.CompositeUsecaseDiagram; import org.dddjava.jig.domain.model.jigdocument.specification.PackageRelationDiagram; import org.dddjava.jig.domain.model.jigdocument.stationery.DiagramSource; import org.dddjava.jig.domain.model.jigdocument.stationery.JigDocumentContext; import org.dddjava.jig.domain.model.jigmodel.lowmodel.declaration.package_.PackageDepth; import org.dddjava.jig.domain.model.jigmodel.lowmodel.declaration.package_.PackageIdentifierFormatter; import org.dddjava.jig.domain.model.jigmodel.services.MethodNodeLabelStyle; import org.dddjava.jig.presentation.view.graphviz.DiagramFormat; import org.dddjava.jig.presentation.view.graphviz.DiagramSourceEditor; import org.dddjava.jig.presentation.view.graphviz.graphvizj.GraphvizjView; import java.util.List; import static java.util.stream.Collectors.toList; public class ViewResolver { PackageIdentifierFormatter packageIdentifierFormatter; MethodNodeLabelStyle methodNodeLabelStyle; DiagramFormat diagramFormat; JigDocumentContext jigDocumentContext; public ViewResolver(PackageIdentifierFormatter packageIdentifierFormatter, MethodNodeLabelStyle methodNodeLabelStyle, DiagramFormat diagramFormat, JigDocumentContext jigDocumentContext) { this.jigDocumentContext = jigDocumentContext; this.packageIdentifierFormatter = packageIdentifierFormatter; this.methodNodeLabelStyle = methodNodeLabelStyle; this.diagramFormat = diagramFormat; } public JigView<PackageRelationDiagram> dependencyWriter() { return newGraphvizjView(model -> { List<PackageDepth> depths = model.maxDepth().surfaceList(); List<DiagramSource> diagramSources = depths.stream() .map(model::applyDepth) .map(packageNetwork1 -> packageNetwork1.dependencyDotText(jigDocumentContext, packageIdentifierFormatter)) .filter(diagramSource -> !diagramSource.noValue()) .collect(toList()); return DiagramSource.createDiagramSource(diagramSources); }); } public JigView<ServiceMethodCallHierarchyDiagram> serviceMethodCallHierarchy() { return newGraphvizjView(model -> model.methodCallDotText(jigDocumentContext)); } public JigView<CategoryUsageDiagram> enumUsage() { return newGraphvizjView(model -> model.diagramSource(jigDocumentContext)); } public JigView<CompositeUsecaseDiagram> compositeUsecaseDiagram() { return newGraphvizjView(model -> model.diagramSource(jigDocumentContext)); } private <T> JigView<T> newGraphvizjView(DiagramSourceEditor<T> diagram) { return new GraphvizjView<>(diagram, diagramFormat); } public JigView<BusinessRuleRelationDiagram> businessRuleRelationWriter() { return newGraphvizjView(model -> model.relationDotText(jigDocumentContext, packageIdentifierFormatter)); } public JigView<Categories> categories() { return newGraphvizjView(model -> model.valuesDotText(jigDocumentContext)); } public JigView<ArchitectureDiagram> architecture() { return newGraphvizjView(model -> model.dotText(jigDocumentContext)); } public JigView<?> toDiagramView(JigDocument jigDocument) { switch (jigDocument) { case ServiceMethodCallHierarchyDiagram: return serviceMethodCallHierarchy(); case PackageRelationDiagram: return dependencyWriter(); case BusinessRuleRelationDiagram: return businessRuleRelationWriter(); case OverconcentrationBusinessRuleDiagram: return new GraphvizjView<BusinessRuleRelationDiagram>( model -> model.overconcentrationRelationDotText(jigDocumentContext), diagramFormat); case CoreBusinessRuleRelationDiagram: return new GraphvizjView<BusinessRuleRelationDiagram>( model -> model.coreRelationDotText(jigDocumentContext, packageIdentifierFormatter), diagramFormat); case CategoryUsageDiagram: return enumUsage(); case CategoryDiagram: return categories(); case ArchitectureDiagram: return architecture(); case CompositeUsecaseDiagram: return compositeUsecaseDiagram(); } throw new IllegalArgumentException("Diagram以外が指定された?: " + jigDocument); } }
true
7900e64defd4d8af4498024735c34053d4677000
Java
drowinternet/mage
/Mage/src/main/java/mage/abilities/common/SimpleTriggeredAbility.java
UTF-8
1,840
2.484375
2
[ "MIT" ]
permissive
package mage.abilities.common; import mage.constants.Zone; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.effects.Effect; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.events.GameEvent.EventType; /** * * @author BetaSteward_at_googlemail.com */ public class SimpleTriggeredAbility extends TriggeredAbilityImpl { private EventType eventType; private boolean onlyController; private String prefix; public SimpleTriggeredAbility(Zone zone, EventType eventType, Effect effect, String prefix) { this(zone, eventType, effect, prefix, false); } public SimpleTriggeredAbility(Zone zone, EventType eventType, Effect effect, String prefix, boolean onlyController) { this(zone, eventType, effect, prefix, onlyController, false); } public SimpleTriggeredAbility(Zone zone, EventType eventType, Effect effect, String prefix, boolean onlyController, boolean optional) { super(zone, effect, optional); this.eventType = eventType; this.onlyController = onlyController; this.prefix = prefix; } public SimpleTriggeredAbility(final SimpleTriggeredAbility ability) { super(ability); this.eventType = ability.eventType; this.onlyController = ability.onlyController; this.prefix = ability.prefix; } @Override public boolean checkEventType(GameEvent event, Game game) { return event.getType() == eventType; } @Override public boolean checkTrigger(GameEvent event, Game game) { return !onlyController || event.getPlayerId().equals(this.controllerId); } @Override public SimpleTriggeredAbility copy() { return new SimpleTriggeredAbility(this); } @Override public String getRule() { return prefix + super.getRule(); } }
true
4f7005feaa25cbd8e0e4a0dd5e12e1f1a4e20a53
Java
evernat/vertigo
/vertigo-dynamo-plugin-elasticsearch_5_6/src/main/java/io/vertigo/dynamo/plugins/search/elasticsearch_5_6/embedded/ESEmbeddedSearchServicesPlugin.java
UTF-8
5,490
1.84375
2
[ "Apache-2.0" ]
permissive
/** * vertigo - simple java starter * * Copyright (C) 2013-2019, Vertigo.io, KleeGroup, direction.technique@kleegroup.com (http://www.kleegroup.com) * KleeGroup, Centre d'affaire la Boursidiere - BP 159 - 92357 Le Plessis Robinson Cedex - France * * 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 io.vertigo.dynamo.plugins.search.elasticsearch_5_6.embedded; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import java.util.Optional; import javax.inject.Inject; import org.elasticsearch.client.Client; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.reindex.ReindexPlugin; import org.elasticsearch.node.InternalSettingsPreparer; import org.elasticsearch.node.Node; import org.elasticsearch.node.NodeValidationException; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.transport.Netty4Plugin; import io.vertigo.commons.codec.CodecManager; import io.vertigo.core.param.ParamValue; import io.vertigo.core.resource.ResourceManager; import io.vertigo.dynamo.plugins.search.elasticsearch_5_6.AbstractESSearchServicesPlugin; import io.vertigo.lang.Assertion; import io.vertigo.lang.WrappedException; //Vérifier /** * Gestion de la connexion au serveur ElasticSearch en mode embarqué. * * @author pchretien, npiedeloup */ public final class ESEmbeddedSearchServicesPlugin extends AbstractESSearchServicesPlugin { /** url du serveur elasticSearch. */ private final URL elasticSearchHomeURL; private Node node; private final Integer httpPort; private final Integer transportPort; /** * Constructor. * @param elasticSearchHome URL du serveur SOLR * @param envIndex Nom de l'index de l'environment * @param envIndexIsPrefix Si Nom de l'index de l'environment est un prefix * @param rowsPerQuery Nombre d'élément retourné par query * @param codecManager Manager des codecs * @param resourceManager Manager d'accès aux ressources * @param configFile Fichier de configuration des indexs */ @Inject public ESEmbeddedSearchServicesPlugin( @ParamValue("home") final String elasticSearchHome, @ParamValue("envIndex") final String envIndex, @ParamValue("envIndexIsPrefix") final Optional<Boolean> envIndexIsPrefix, @ParamValue("rowsPerQuery") final int rowsPerQuery, @ParamValue("config.file") final String configFile, @ParamValue("http.port") final Optional<Integer> httpPortOpt, @ParamValue("transport.tcp.port") final Optional<Integer> transportPortOpt, final CodecManager codecManager, final ResourceManager resourceManager) { super(envIndex, envIndexIsPrefix.orElse(false), rowsPerQuery, configFile, codecManager, resourceManager); Assertion.checkArgNotEmpty(elasticSearchHome); //----- elasticSearchHomeURL = resourceManager.resolve(elasticSearchHome); httpPort = httpPortOpt.orElse(9200); transportPort = transportPortOpt.orElse(9300); } /** {@inheritDoc} */ @Override protected Client createClient() { node = createNode(elasticSearchHomeURL); try { node.start(); } catch (final NodeValidationException e) { throw WrappedException.wrap(e, "Error at ElasticSearch node start"); } return node.client(); } /** {@inheritDoc} */ @Override protected void closeClient() { try { node.close(); } catch (final IOException e) { throw WrappedException.wrap(e, "Error at ElasticSearch node stop"); } } private Node createNode(final URL esHomeURL) { Assertion.checkNotNull(esHomeURL); //----- final File home; try { home = new File(URLDecoder.decode(esHomeURL.getFile(), StandardCharsets.UTF_8.name())); } catch (final UnsupportedEncodingException e) { throw WrappedException.wrap(e, "Error de parametrage du ElasticSearchHome " + esHomeURL); } Assertion.checkArgument(home.exists() && home.isDirectory(), "Le ElasticSearchHome : {0} n''existe pas, ou n''est pas un répertoire.", home.getAbsolutePath()); Assertion.checkArgument(home.canWrite(), "L''application n''a pas les droits d''écriture sur le ElasticSearchHome : {0}", home.getAbsolutePath()); return new MyNode(buildNodeSettings(home.getAbsolutePath()), Arrays.asList(Netty4Plugin.class, ReindexPlugin.class)); } private static class MyNode extends Node { public MyNode(final Settings preparedSettings, final Collection<Class<? extends Plugin>> classpathPlugins) { super(InternalSettingsPreparer.prepareEnvironment(preparedSettings, null), classpathPlugins); } } private Settings buildNodeSettings(final String homePath) { //Build settings return Settings.builder() .put("node.name", "es-embedded-node-" + System.currentTimeMillis()) .put("transport.type", "netty4") .put("http.type", "netty4") .put("http.enabled", "true") .put("http.port", httpPort) .put("transport.tcp.port", transportPort) .put("path.home", homePath) .build(); } }
true
334cc16b71a97b26a232d125ad22f5a0b2aa701d
Java
BelidePruthvi/AU_Assignments
/kafka/kafka_Assignment/src/main/java/com/practice/kafkastreams/producer/NumberProducer.java
UTF-8
794
2.125
2
[]
no_license
package com.practice.kafkastreams.producer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import java.util.Random; @Component @EnableScheduling public class NumberProducer { @Value("topic1") private String topicName; @Autowired private KafkaTemplate<String,Long> kafkaTemplate; Random rand=new Random(); // private Long counter = 0L; @Scheduled(fixedRate = 2000) public void produce() { kafkaTemplate.send(topicName, rand.nextLong()); } }
true
cc0ff03757ad715c0938c8ec89d091de2c930e8b
Java
dddddttttt/androidsourcecodes
/坦克大战/src/yzy/Tank/GameView.java
GB18030
10,315
2.359375
2
[]
no_license
package yzy.Tank; import java.util.ArrayList; import java.util.HashMap; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PaintFlagsDrawFilter; import android.media.AudioManager; import android.media.SoundPool; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceHolder.Callback; import android.view.SurfaceView; /** * Ϸ */ public class GameView extends SurfaceView implements Callback, Runnable { private SurfaceHolder sh; private Canvas canvas; MainActivity activity;//activity private Bitmap gdbj;// private Bitmap[] gdbjs = new Bitmap[ConstantUtil.pictureCount];//װָԺͼƬ float backGroundIX = 0;//ͼx int i = 0;//ͼ BackGroundThread backGroundThread;//߳ private Bitmap control;//ưť SoundPool soundPool;// HashMap<Integer, Integer> soundPoolMap; KeyThread keyThread;//̼߳ int action = 0;//̵״̬ MoveThread moveThread;//ƶ߳ ExplodeThread explodeThread;//ը֡߳ int status = 1;//Ϸ״̬1ʾϷ,2ʾϷʧܼҷɻû private boolean isdraw = true;//Ƿֹͣ Tank tank = new Tank(140, 389,ConstantUtil.life, this); ArrayList<Bullet> goodBollets = new ArrayList<Bullet>();//ҷ̹˷ӵ ArrayList<Bullet> badBollets = new ArrayList<Bullet>();//з̹˷ӵ ArrayList<EnemyTank> enemyTanks;//з̹ Bitmap enemyTank1;//̹1 Bitmap enemyTank2;//̹2 Bitmap enemyTank3;//̹3 Bitmap enemyTank4;//зɵ Bitmap enemyTank5; ArrayList<Life> lifes;//Ѫ Bitmap life;//ѪͼƬ ArrayList<Explode> explodeList = new ArrayList<Explode>();//ըЧ1 int[] explodesID = new int[]{//ը֡ R.drawable.baozha1,R.drawable.baozha2,R.drawable.baozha3, R.drawable.baozha4,R.drawable.baozha5,R.drawable.baozha6, R.drawable.baozha7,R.drawable.baozha8,R.drawable.baozha9, }; Bitmap[] explodes = new Bitmap[explodesID.length];//ը1 ArrayList<Explode> explodeList2 = new ArrayList<Explode>();//ըЧ2 int[] explodesID2 = new int[]{//ը2֡ R.drawable.bz1,R.drawable.bz2, R.drawable.bz3,R.drawable.bz4,R.drawable.bz5, }; Bitmap[] explodes2 = new Bitmap[explodesID2.length];//ը2 public GameView(MainActivity activity) { super(activity); this.activity = activity;//activity gdbj = BitmapFactory.decodeResource(this.getResources(), R.drawable.gdbj);//ͼƬ for(int i=0; i<gdbjs.length; i++){//гСͼƬ gdbjs[i] = Bitmap.createBitmap(gdbj, ConstantUtil.pictureWidth*i, 0, ConstantUtil.pictureWidth, 480); } gdbj=null;//ͷŵ󱳾ͼ control= BitmapFactory.decodeResource(this.getResources(), R.drawable.control);//ƼͼƬ initSounds();//ʼ this.backGroundThread = new BackGroundThread(this);//ʼ߳ this.keyThread = new KeyThread(this);//ʼ̼ this.moveThread = new MoveThread(this);//ʼƶ߳ this.explodeThread = new ExplodeThread(this);//ʼը߳ enemyTanks = Maps.getFirst();//ȡһصĵ̹ lifes = Maps.getFirstLife();//ȡһصĵѪ enemyTank1 = BitmapFactory.decodeResource(getResources(), R.drawable.tk1);//̹1ͼƬ enemyTank2 = BitmapFactory.decodeResource(getResources(), R.drawable.tk2);//̹2ͼƬ enemyTank3 = BitmapFactory.decodeResource(getResources(), R.drawable.tk3);//̹3ͼƬ enemyTank4 = BitmapFactory.decodeResource(getResources(), R.drawable.feidie);//зɵͼƬ enemyTank5 = BitmapFactory.decodeResource(getResources(), R.drawable.boss);//boss for(int i=0; i<explodes.length; i++){//ʼը1ͼƬ explodes[i] = BitmapFactory.decodeResource(getResources(), explodesID[i]); } for(int i=0; i<explodes2.length; i++){//ʼը2ͼƬ explodes2[i] = BitmapFactory.decodeResource(getResources(), explodesID2[i]); } for(EnemyTank ep : enemyTanks){//Ϊ̹ʼͼƬ if(ep.type == 1){ ep.bitmap = enemyTank1; } else if(ep.type == 2){ ep.bitmap = enemyTank2; } else if(ep.type == 3){ ep.bitmap = enemyTank3; } else if(ep.type == 4){ ep.bitmap = enemyTank4; } else if(ep.type == 5){ ep.bitmap = enemyTank5; } } life = BitmapFactory.decodeResource(getResources(), R.drawable.xuekuai);//ѪͼƬ for(Life l : lifes){//ΪѪʼͼƬ l.bitmap = life; } this.setFocusable(true);// õǰViewӵпƽ sh = this.getHolder();// View൱ڵ SurfaceHolderң sh.addCallback(this); } public void initSounds(){//ʼ soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100); soundPoolMap = new HashMap<Integer, Integer>(); soundPoolMap.put(1, soundPool.load(getContext(), R.raw.tk3, 1)); soundPoolMap.put(2, soundPool.load(getContext(), R.raw.zidanfashe, 1)); soundPoolMap.put(3, soundPool.load(getContext(), R.raw.baozha, 1)); soundPoolMap.put(4, soundPool.load(getContext(), R.raw.daodanyinxiao, 1)); soundPoolMap.put(5, soundPool.load(getContext(), R.raw.chixue, 1)); } public void playSound(int sound, int loop) { AudioManager mgr = (AudioManager)getContext().getSystemService(Context.AUDIO_SERVICE); float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC); float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC); float volume = streamVolumeCurrent / streamVolumeMax; soundPool.play(soundPoolMap.get(sound), volume, volume, 1, loop, 1f); } public void drawView() { //xģ󻭵ĻḲǰ滭 float backGroundIX=this.backGroundIX; int i=this.i; try { if (sh != null) { canvas = sh.lockCanvas();// õ canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG));// //i౳ if(backGroundIX>0){ float n=(backGroundIX/ConstantUtil.pictureWidth)+((backGroundIX%ConstantUtil.pictureWidth==0)?0:1);//iмͼ for(int j=1;j<=n;j++){ canvas.drawBitmap(gdbjs[(i-j+ConstantUtil.pictureCount)%ConstantUtil.pictureCount], backGroundIX-ConstantUtil.pictureWidth*j, 0, null); } } //i canvas.drawBitmap(gdbjs[i], backGroundIX, 0, null); //iҲ౳ if(backGroundIX<854-ConstantUtil.pictureWidth){ float k=854-(backGroundIX+ConstantUtil.pictureWidth); float n=(k/ConstantUtil.pictureWidth)+((k%ConstantUtil.pictureWidth==0)?0:1);//iмͼ for(int j=1;j<=n;j++){ canvas.drawBitmap(gdbjs[(i+j)%ConstantUtil.pictureCount], backGroundIX+ConstantUtil.pictureWidth*j, 0, null ); } } canvas.drawBitmap(control, 42, 138, null);//Ƽ tank.drawView(canvas);//̹ try{//Ƶ̹ for(EnemyTank ep:enemyTanks){ if(ep.status == true){ ep.draw(canvas); } } }catch(Exception e){ } try{//ҷӵ for(Bullet b:goodBollets){ b.draw(canvas); } }catch(Exception e){ } try{//Ƶзӵ for(Bullet b:badBollets){ b.draw(canvas); } } catch(Exception e){ } try{//Ʊը for(Explode e : explodeList){ e.draw(canvas); } } catch(Exception e){} try{//Ѫ for(Life l : lifes){ if(l.status == true){ l.draw(canvas); } } } catch(Exception e){} } } catch (Exception e) { e.printStackTrace(); } finally { if (canvas != null) { sh.unlockCanvasAndPost(canvas);// Ӵ ͸ң } } } public void surfaceCreated(SurfaceHolder holder) { new Thread(this).start();//GameView߳ this.backGroundThread.setFlag(true); this.backGroundThread.start();//߳ this.keyThread.setFlag(true); keyThread.start();//̼߳ this.moveThread.setFlag(true); moveThread.start();//ӵѾƶƶ߳ this.explodeThread.setFlag(true); explodeThread.start();//ը߳ } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } public void surfaceDestroyed(SurfaceHolder holder) { boolean retry = true; isdraw = false; this.backGroundThread.setFlag(false);//ֹͣ߳ this.keyThread.setFlag(false);//ֹ̼ͣ this.moveThread.setFlag(false);//ֹͣӵѾƶƶ߳ this.explodeThread.setFlag(false);//ֹͣը߳ while (retry) { try { keyThread.join(); backGroundThread.join(); moveThread.join(); explodeThread.join(); retry = false; } catch (InterruptedException e) {//ϵѭֱˢ֡߳̽ } } } @Override public void run() { while (isdraw) { drawView(); } } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if ((event.getX() >= 100 & event.getX() <= 170)& (event.getY() >= 125 & event.getY() <= 201)) {// action = 1; }else if ((event.getX() >= 100 & event.getX() <= 170)& (event.getY() >= 275 & event.getY() <= 349)) {// action = 2; }else if ((event.getX() >= 0 & event.getX() <= 100)& (event.getY() >= 201 & event.getY() <= 275)) {// action = 3; }else if ((event.getX() >= 171 & event.getX() <= 241)& (event.getY() >= 201 & event.getY() <= 275)) {// action = 4; }else{ action = 6;//ڿ Ļ ӵ } } if (event.getAction() == MotionEvent.ACTION_UP) { action = 5; } return true; } }
true
4a63decc925d8a6cbcd2338c0bd37d69e963d6c9
Java
fedosovmu/BullsAndCows
/src/com/company/SecretNumber.java
UTF-8
870
3.421875
3
[]
no_license
package com.company; import java.util.Formatter; public class SecretNumber { public int Value; public int[] Digits; SecretNumber (int[] digits) { Digits = new int[4]; Digits[0] = Math.abs(digits[0] % 10); Digits[1] = Math.abs(digits[1] % 10); Digits[2] = Math.abs(digits[2] % 10); Digits[3] = Math.abs(digits[3] % 10); Value = Digits[0] * 1000 + Digits[1] * 100 + Digits[2] * 10 + Digits[3]; } SecretNumber (int value) { Value = Math.abs(value % 10000); Digits = new int[4]; Digits[3] = Value % 10; Digits[2] = (Value / 10) % 10; Digits[1] = (Value / 100) % 10; Digits[0] = Value / 1000; } @Override public String toString() { Formatter f = new Formatter(); f.format("%04d", Value); return f.toString(); } }
true
ae567d779adc39ce399858d1868c0a0aedf6fda9
Java
jhnam/hvcc_sap_dalian
/src/com/hvcc/sap/beijing/ActualToSap.java
UTF-8
3,919
2.234375
2
[]
no_license
/** * */ package com.hvcc.sap.beijing; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Logger; import com.hvcc.sap.MesSearcher; import com.hvcc.sap.MesUpdater; import com.hvcc.sap.RfcInvoker; import com.hvcc.sap.util.Utils; /** * Actual Interface MES To SAP * * @author Shortstop */ public class ActualToSap { private static final Logger LOGGER = Logger.getLogger(ActualToSap.class.getName()); public static final String RFC_FUNC_NAME = "ZPPG_EA_ACT_PROD"; /** * call rfc * * @return * @throws Exception */ public Map<String, Object> callRfc(Map<String, Object> inputParams) throws Exception { List<String> outputParams = new ArrayList<String>(); outputParams.add("EV_RESULT"); outputParams.add("EV_MSG"); outputParams.add("EV_IFSEQ"); LOGGER.info("RFC [" + RFC_FUNC_NAME + "] Call!"); Map<String, Object> output = new RfcInvoker().callFunction(RFC_FUNC_NAME, "IS_ACT", inputParams, outputParams); return output; } /** * Select from MES Actual Table * * @throws Exception */ public List<Map<String, Object>> selectActuals() throws Exception { String sql = "SELECT * FROM (SELECT MES_ID, IFSEQ, WERKS, ARBPL, EQUNR, LOGRP, VAART, MATNR, CHARG, KUNNR, BUDAT, PDDAT, ERFMG, SERIAL_NO, LOT_NUMBER FROM INF_SAP_ACTUAL WHERE IFRESULT = 'N' ORDER BY MES_ISTDT ASC) WHERE ROWNUM <= 100"; return new MesSearcher().search(sql); } /** * Update status flag MES Scrap table * * @param mesId * @param status * @param msg * @return * @throws Exception */ public boolean updateStatus(String mesId, String status, String msg) throws Exception { String preparedSql = "UPDATE INF_SAP_ACTUAL SET IFRESULT = ?, IFFMSG = ? WHERE MES_ID = ?"; List parameters = new ArrayList(); List param = new ArrayList(); param.add(status); param.add(msg); param.add(mesId); parameters.add(param); int result = new MesUpdater().update(preparedSql, parameters); return result > 0; } /** * 실행 * * @throws Exception */ public void execute() { List<Map<String, Object>> actuals = null; try { actuals = this.selectActuals(); } catch (Throwable th) { LOGGER.severe(th.getMessage()); return; } if(actuals != null && !actuals.isEmpty()) { int actualCount = actuals.size(); for(int i = 0 ; i < actualCount ; i++) { Map<String, Object> inputParam = actuals.get(i); String mesId = (String)inputParam.remove("MES_ID"); Map<String, Object> output = this.executeRecord(mesId, inputParam); if(output != null) { String ifseq = (String)output.get("EV_IFSEQ"); String evResult = (String)output.get("EV_RESULT"); if(evResult != null && evResult.equalsIgnoreCase("S")) { LOGGER.info("Actual IFSEQ : " + ifseq); } else { String evMsg = (String)output.get("EV_MSG"); LOGGER.info("Actual Error Message : " + evMsg); if(evMsg.length() > 250) evMsg = evMsg.substring(0, 250); try { this.updateStatus(mesId, evResult, evMsg); } catch (Throwable th) { LOGGER.severe("Failed to update status, Error : " + th.getMessage()); } } } } } else { LOGGER.info("No actual data to interface!"); } } private Map<String, Object> executeRecord(String mesId, Map<String, Object> inputParam) { Utils.mapToStr(inputParam); Map<String, Object> output = null; try { output = this.callRfc(inputParam); this.updateStatus(mesId, "Y", null); } catch (Throwable th) { String msg = "Error - MES_ID : " + mesId + ", MSG : " + th.getMessage(); LOGGER.severe(msg); if(msg.length() > 250) msg = msg.substring(0, 250); try { this.updateStatus(mesId, "F", msg); } catch (Throwable e) { LOGGER.severe("Failed to update status, Error : " + e.getMessage()); } } return output; } }
true
5a005fa9dbc2b2c76796a13fcc800c98a973b95d
Java
moskalap/Sejmometr
/src/QueryInterpreter.java
UTF-8
5,543
2.859375
3
[]
no_license
import org.json.JSONException; import java.io.IOException; /** * Created by przemek on 21.12.16. * * klasa, która zwraca stringa z danymi, których oczekuje requesteddData. */ public class QueryInterpreter implements IQueryInterpreter { private RequestedData requestedData; private DataDownloader dataDownloader; private Parliament parliament; public QueryInterpreter(RequestedData rd){ this.requestedData=rd; } public String interpret(RequestedData requestedData) throws IOException, JSONException { this.requestedData=requestedData; dataDownloader.setParliament(parliament); if(requestedData.wantsPolitican){ return new StringBuilder().append("Poseł "). append(requestedData.politic). append(": \nSuma wydatków wynosi\n"). append(dataDownloader.sumofExpenses(requestedData.politicanid)). append("zł\nW tym \n"). append(dataDownloader.downloadExpense(requestedData.politicanid, requestedData.expenseID)). append("zł na\n").append(dataDownloader.getExpenseName(requestedData.expenseID)).toString(); } if(requestedData.wantsParty){ StringBuilder out= new StringBuilder(); if(requestedData.wantsAverage) out.append("\nSuma wydatków partii "). append(requestedData.party). append(" wynosi:\n"). append(dataDownloader.downloadSumOfParty(requestedData.party, parliament)). append("zł\n"). append("Średnia wartość wydatków posła partii "). append(requestedData.party). append(" wynosi:\n"). append(dataDownloader.downloadAvgOfParty(requestedData.party, parliament)). append("zł\n"); if(requestedData.wantsListofTravellersTo_) { out.append("\nPosłowie z partii "). append(requestedData.party). append("\nktórzy podrózowali do \n"). append(requestedData.country+"\n"); for(Politican politican:dataDownloader.downloadListofTravellersto_(requestedData.country, requestedData.party)) { out.append(politican.getName()); out.append("\n"); } } if(requestedData.wantsTheLongestTravel){ out.append("\nCzłonek partii "). append(requestedData.party). append("\nktóry najdłużej przebywał za granicą to\n"). append(dataDownloader.downloadTheLongTravel(requestedData.party)); } if(requestedData.wantsTheMostExpensiveTravel){ out.append("\nCzłonek partii "). append(requestedData.party). append("\nktóry odbył najdroższą podróż to\n"). append(dataDownloader.downloadTheExpensiverTraveller(requestedData.party)); } if(requestedData.wantsTheGreatestTraveller){ out.append("\nCzłonek partii "). append(requestedData.party). append("\nktóry najwięcej podróżował to\n"). append(dataDownloader.downloadTheGreatestTrveller(requestedData.party)); } return out.toString(); } if(requestedData.wantsAll){ StringBuilder out= new StringBuilder(); if(requestedData.wantsAverage) out.append("Suma wydatków wszystkich posłów wynosi "). append(dataDownloader.downloadSumOfParty("-a", parliament)). append(" zł \nŚrednia wydatków wszyskich posłów wynosi"). append(dataDownloader.downloadAvgOfParty("-a",parliament)). append(" zł\n\n\n\n"); if(requestedData.wantsListofTravellersTo_) { out.append("\nPosłowie, ktorzy podróżowali do \n"). append(requestedData.country); for(Politican politican:dataDownloader.downloadListofTravellersto_(requestedData.country, "-a")) { out.append(politican.getName()); out.append("\n"); } } if(requestedData.wantsTheLongestTravel){ out.append("\nPoseł który najdłużej przebywał za granicą "). append(dataDownloader.downloadTheLongTravel("-a")); } if(requestedData.wantsTheMostExpensiveTravel){ out.append("\nPoseł który odbył najdroższą podróż "). append(dataDownloader.downloadTheExpensiverTraveller("-a")); } if(requestedData.wantsTheGreatestTraveller){ out.append("\nPoseł który najwięcej podróżował "). append(dataDownloader.downloadTheGreatestTrveller("-a")); } return out.toString(); } return "error"; } public void setParliament(Parliament parliament) { this.parliament = parliament; } public void setDownloader(DataDownloader downloader){ this.dataDownloader=downloader; } }
true
d38e4efb4c6d4763aa486002fc822e6914392163
Java
himz/interview
/src/test/java/leetcode/_171Test.java
UTF-8
568
2.390625
2
[]
no_license
package leetcode; import leetcode.string._171_ExcelSheetNumber; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import java.util.List; import static org.junit.Assert.assertEquals; @Ignore public class _171Test { private static _171_ExcelSheetNumber solution1;// @BeforeClass public static void setup() { solution1 = new _171_ExcelSheetNumber(); } @Test public void test1() { int arr[] = {1,2,3}; int result = solution1.titleToNumber("AB"); System.out.println(result); } }
true
356ada78072dd5165146fa2dee774d3565eb71e4
Java
wwb382899012/ops
/ops-entity/src/main/java/com/jyblife/logic/wl/ops/entity/OilPriceAdjustMsg.java
UTF-8
2,880
2.140625
2
[]
no_license
package com.jyblife.logic.wl.ops.entity; import com.jyblife.logic.wl.ops.common.annotation.Id; import com.jyblife.logic.wl.ops.common.annotation.Table; import java.util.Date; @Table("t_oil_price_adjust_msg") public class OilPriceAdjustMsg { /** * */ @Id private Integer id; /** * 油价调整的内容 */ private String content; /** * 关联t_oil_price表字段price_id */ private Integer priceId; /** * 油企id */ private Integer companyId; /** * 油站id */ private Integer stationId; /** * 生效时间 */ private Date effectTime; /** * 创建时间 */ private Date createTime; /** * * @return id */ public Integer getId() { return id; } /** * * @param id */ public void setId(Integer id) { this.id = id; } /** * 油价调整的内容 * @return content 油价调整的内容 */ public String getContent() { return content; } /** * 油价调整的内容 * @param content 油价调整的内容 */ public void setContent(String content) { this.content = content == null ? null : content.trim(); } /** * 关联t_oil_price表字段price_id * @return price_id 关联t_oil_price表字段price_id */ public Integer getPriceId() { return priceId; } /** * 关联t_oil_price表字段price_id * @param priceId 关联t_oil_price表字段price_id */ public void setPriceId(Integer priceId) { this.priceId = priceId; } /** * 油企id * @return company_id 油企id */ public Integer getCompanyId() { return companyId; } /** * 油企id * @param companyId 油企id */ public void setCompanyId(Integer companyId) { this.companyId = companyId; } /** * 油站id * @return station_id 油站id */ public Integer getStationId() { return stationId; } /** * 油站id * @param stationId 油站id */ public void setStationId(Integer stationId) { this.stationId = stationId; } /** * 生效时间 * @return effect_time 生效时间 */ public Date getEffectTime() { return effectTime; } /** * 生效时间 * @param effectTime 生效时间 */ public void setEffectTime(Date effectTime) { this.effectTime = effectTime; } /** * 创建时间 * @return create_time 创建时间 */ public Date getCreateTime() { return createTime; } /** * 创建时间 * @param createTime 创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } }
true
31fb3306b43845c838f8d2b423cae84e95eaa648
Java
RowanWang/model
/DesignPattern/src/com/creationalpattern/factorymethod/AppleGardener.java
UTF-8
220
2.390625
2
[]
no_license
package com.creationalpattern.factorymethod; /** * Created by szk on 2019/11/12. */ public class AppleGardener implements FruitGardener { @Override public Fruit Factory() { return new Apple(); } }
true
83a24aae07a81fcc15d2b48297d5a3d1261775e6
Java
RasmusMuikku96/vending
/src/main/java/com/rasmus/app/vending/mod/Drink.java
UTF-8
575
2.828125
3
[]
no_license
package com.rasmus.app.vending.mod; public class Drink extends Products{ private String volume; public Drink(String name, int price, String volume) { super(name, price); this.volume = volume; } public String getVolume() { return volume; } @Override void purchase(int money, String name) { // TODO Auto-generated method stub } @Override public String examine() { return this.getName() + " " + getPrice() + " " + getVolume(); } @Override public String use() { return "You drank " + this.getName(); } }
true
69cff949dc5b399f012422721809f3a2c2480f0d
Java
sonalpnaik/1320OnlineTest
/elevator/src/Elevetor_door.java
UTF-8
369
2.859375
3
[]
no_license
public class Elevetor_door { boolean door_open; public Elevetor_door() { super(); door_open=false; } public boolean isDoor_open() { return door_open; } public void setDoor_open(boolean door_open) { this.door_open = door_open; if(isDoor_open()) System.out.println("door is open"); else System.out.println("door closed"); } }
true
a7afbbc34f3daf8c54891dcb90522fd05943262f
Java
pavankhanal/E9pay-webservices
/src/main/java/com/e9pay/e9pay/api/entity/MenuFirstCategory.java
UTF-8
864
1.945313
2
[]
no_license
package com.e9pay.e9pay.api.entity; import java.util.List; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import lombok.Data; import com.e9pay.e9pay.api.core.BaseEntity; /** * @author Vivek Adhikari * @since 4/29/2017 */ @Entity @Table(name = "menu_first_category") @Data @SequenceGenerator(name = "hb_seq", sequenceName = "seq_menu_first_category") public class MenuFirstCategory extends BaseEntity { @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "menu_item_id") private MenuItem item; @OneToMany(fetch = FetchType.LAZY) @JoinColumn(name = "menu_second_category_id") private List<MenuSecondCategory> secondCategories; }
true
ff51733fc9342704d803462746403eaaf76f1701
Java
BGCX261/zju-svn-to-git
/trunk/base/src/main/java/com/jsict/base/form/BaseForm.java
UTF-8
474
1.78125
2
[]
no_license
/** * $Id: PJBaseForm.java,v 1.3 2006/02/14 08:51:16 helj Exp $ */ package com.jsict.base.form; import org.apache.struts.action.ActionForm; /** * * @author qipf * */ public abstract class BaseForm extends ActionForm { protected String actionType = null; public String getActionType() { return actionType; } public void setActionType(String actionType) { this.actionType = actionType; } }
true
b0a3d82a74a24c4fd98a252632b6d3fe16655625
Java
songxingguo/CampusBikesForSophomores
/campusParking/src/main/java/com/cp/dao/NoticeMapper.java
UTF-8
1,341
1.84375
2
[]
no_license
package com.cp.dao; import com.cp.model.Notice; public interface NoticeMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table notice * * @mbggenerated */ int deleteByPrimaryKey(String id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table notice * * @mbggenerated */ int insert(Notice record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table notice * * @mbggenerated */ int insertSelective(Notice record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table notice * * @mbggenerated */ Notice selectByPrimaryKey(String id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table notice * * @mbggenerated */ int updateByPrimaryKeySelective(Notice record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table notice * * @mbggenerated */ int updateByPrimaryKey(Notice record); }
true
5d1d0a6dea9596d5c45f9ea9e2a5062e37fa4c4a
Java
codingBitsKolkata/auth-server
/src/main/java/com/orastays/authserver/dao/UserVsLanguageDAO.java
UTF-8
412
1.742188
2
[]
no_license
/** * @author Abhideep */ package com.orastays.authserver.dao; import org.springframework.stereotype.Repository; import com.orastays.authserver.entity.UserVsLanguageEntity; @Repository public class UserVsLanguageDAO extends GenericDAO<UserVsLanguageEntity, Long> { private static final long serialVersionUID = 8218607289499611724L; public UserVsLanguageDAO() { super(UserVsLanguageEntity.class); } }
true
3553351b4bc5b4a08e52b0d1460d100972da2cf2
Java
Telefonica/avro-random-generator
/app/src/main/java/io/confluent/avro/random/generator/geojson/crs/CRS.java
UTF-8
904
2.640625
3
[ "Apache-2.0" ]
permissive
package io.confluent.avro.random.generator.geojson.crs; import java.util.Random; public abstract class CRS { protected double leftBound; protected double rightBound; protected double bottomBound; protected double upperBound; protected void setBounds( double leftBound, double rightBound, double bottomBound, double upperBound ) { this.leftBound = leftBound; this.rightBound = rightBound; this.bottomBound = bottomBound; this.upperBound = upperBound; } public double randomLatitude() { Random r = new Random(); return bottomBound + (upperBound - bottomBound) * r.nextDouble(); } public double randomLongitude() { Random r = new Random(); return leftBound + (rightBound - leftBound) * r.nextDouble(); } public abstract String toString(); }
true
75813b53851ca92d12d120063270ef1c357e0d3a
Java
masan67/WebViewBridge
/app/src/main/java/com/marioapps/webviewbridge/WebAppInterface.java
UTF-8
430
2.1875
2
[]
no_license
package com.marioapps.webviewbridge; import android.webkit.JavascriptInterface; import android.widget.Toast; import android.content.Context; public class WebAppInterface { private Context context; public WebAppInterface(Context context){ this.context=context; } @JavascriptInterface public void showToast(String message){ Toast.makeText(context,message,Toast.LENGTH_LONG).show(); } }
true