hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
9240ceb6924001d5e056f606c42ac5bfd59af64f
412
java
Java
springboot/transaction/src/main/java/wiki/laona/transaction/TransactionApplication.java
HuaiAnGG/Go
1d3522cb399641f1e5b9cd876c893a8d087ca161
[ "MIT" ]
null
null
null
springboot/transaction/src/main/java/wiki/laona/transaction/TransactionApplication.java
HuaiAnGG/Go
1d3522cb399641f1e5b9cd876c893a8d087ca161
[ "MIT" ]
1
2022-01-22T08:10:48.000Z
2022-01-22T08:16:14.000Z
springboot/transaction/src/main/java/wiki/laona/transaction/TransactionApplication.java
HuaiAnGG/Go
1d3522cb399641f1e5b9cd876c893a8d087ca161
[ "MIT" ]
null
null
null
25.75
68
0.813107
1,001,673
package wiki.laona.transaction; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableAsync; @EnableAsync @SpringBootApplication public class TransactionApplication { public static void main(String[] args) { SpringApplication.run(TransactionApplication.class, args); } }
9240cedfef2ba87ffee69365117efc2d1de8936f
329
java
Java
app/src/main/java/wang/imallen/blog/servicemanager/CheckPearImpl.java
wxun7619/iQiYi
0d7f14a503a637bf24d9e2bc8c6f439d387b0298
[ "BSD-3-Clause" ]
2,175
2018-04-20T08:25:05.000Z
2022-03-23T02:11:17.000Z
app/src/main/java/wang/imallen/blog/servicemanager/CheckPearImpl.java
kylin17/Andromeda
2616510bbf9d7a04cb79be9ef02063d0851ed1ea
[ "BSD-3-Clause" ]
22
2018-06-04T07:39:15.000Z
2021-09-27T06:11:46.000Z
app/src/main/java/wang/imallen/blog/servicemanager/CheckPearImpl.java
kylin17/Andromeda
2616510bbf9d7a04cb79be9ef02063d0851ed1ea
[ "BSD-3-Clause" ]
267
2018-04-20T08:25:30.000Z
2022-02-16T08:16:40.000Z
18.277778
50
0.653495
1,001,674
package wang.imallen.blog.servicemanager; /** * Created by wangallen on 2018/2/12. */ public class CheckPearImpl implements ICheckPear { @Override public int getCalories(int pearNum) { return pearNum * 50; } @Override public String getPearDesc(int pearType) { return "Big pear!"; } }
9240d14c2c5c0496611f9613df6c93f5ad3fcfb4
3,550
java
Java
impl/web/common-web/src/test/java/be/atbash/ee/security/octopus/ratelimit/RateLimitFilterTest.java
atbashEE/atbash-octopus
122cd96f414fbb10a3dc850083b7f48907e6addc
[ "Apache-2.0" ]
4
2017-12-27T20:22:09.000Z
2021-05-29T23:20:40.000Z
impl/web/common-web/src/test/java/be/atbash/ee/security/octopus/ratelimit/RateLimitFilterTest.java
atbashEE/atbash-octopus
122cd96f414fbb10a3dc850083b7f48907e6addc
[ "Apache-2.0" ]
null
null
null
impl/web/common-web/src/test/java/be/atbash/ee/security/octopus/ratelimit/RateLimitFilterTest.java
atbashEE/atbash-octopus
122cd96f414fbb10a3dc850083b7f48907e6addc
[ "Apache-2.0" ]
null
null
null
33.17757
119
0.742535
1,001,675
/* * Copyright 2014-2020 Rudy De Busscher (https://www.atbash.be) * * 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 be.atbash.ee.security.octopus.ratelimit; import be.atbash.ee.security.octopus.WebConstants; import be.atbash.ee.security.octopus.config.exception.ConfigurationException; import be.atbash.util.TestReflectionUtils; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import javax.servlet.ServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.*; /** * */ @ExtendWith(MockitoExtension.class) public class RateLimitFilterTest { private static final String SOMEPATH = "/somepath"; @Mock private ServletRequest requestMock; @Mock private HttpServletResponse responseMock; @Mock private FixedBucket fixedBucketMock; @Mock private PrintWriter printWriterMock; private RateLimitFilter filter; @BeforeEach public void setup() { filter = new RateLimitFilter(); filter.initInstance(); } @Test public void processPathConfig() throws NoSuchFieldException, IllegalAccessException { filter.processPathConfig(SOMEPATH, "1/1s"); Map<String, FixedBucket> rateLimiters = TestReflectionUtils.getValueOf(filter, "rateLimiters"); assertThat(rateLimiters).hasSize(1); assertThat(rateLimiters).containsKey(SOMEPATH); assertThat(rateLimiters.get(SOMEPATH)).isNotNull(); } @Test public void processPathConfig_invalidConfig() { Assertions.assertThrows(ConfigurationException.class, () -> filter.processPathConfig(SOMEPATH, "1/1s, 10/1m")); } @Test public void onPreHandle() throws Exception { Map<String, FixedBucket> rateLimiters = TestReflectionUtils.getValueOf(filter, "rateLimiters"); rateLimiters.put(SOMEPATH, fixedBucketMock); when(requestMock.getAttribute(WebConstants.OCTOPUS_CHAIN_NAME)).thenReturn(SOMEPATH); when(fixedBucketMock.getToken(anyString())).thenReturn(TokenInstance.USABLE); filter.onPreHandle(requestMock, responseMock); verifyNoMoreInteractions(responseMock); } @Test public void onPreHandle_rateExceeded() throws Exception { Map<String, FixedBucket> rateLimiters = TestReflectionUtils.getValueOf(filter, "rateLimiters"); rateLimiters.put(SOMEPATH, fixedBucketMock); when(requestMock.getAttribute(WebConstants.OCTOPUS_CHAIN_NAME)).thenReturn(SOMEPATH); when(responseMock.getWriter()).thenReturn(printWriterMock); when(fixedBucketMock.getToken(anyString())).thenReturn(TokenInstance.UNUSABLE); filter.onPreHandle(requestMock, responseMock); verify(responseMock).setStatus(429); } }
9240d1570dbafb7841cbcda4851d1318dd1c1d7f
757
java
Java
presto-verifier/src/main/java/io/prestosql/verifier/TypesDoNotMatchException.java
rzeyde-varada/prestodb
3a3d33271e98d315940d06dc7fbe38d6a4912f51
[ "Apache-2.0" ]
476
2020-06-30T14:24:39.000Z
2022-03-29T13:13:33.000Z
presto-verifier/src/main/java/io/prestosql/verifier/TypesDoNotMatchException.java
rzeyde-varada/prestodb
3a3d33271e98d315940d06dc7fbe38d6a4912f51
[ "Apache-2.0" ]
316
2020-06-30T11:44:52.000Z
2022-03-30T11:08:04.000Z
presto-verifier/src/main/java/io/prestosql/verifier/TypesDoNotMatchException.java
rzeyde-varada/prestodb
3a3d33271e98d315940d06dc7fbe38d6a4912f51
[ "Apache-2.0" ]
326
2020-06-30T11:40:14.000Z
2022-03-31T07:55:03.000Z
31.541667
75
0.733157
1,001,676
/* * 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.prestosql.verifier; public class TypesDoNotMatchException extends RuntimeException { public TypesDoNotMatchException(String message) { super(message); } }
9240d185eabfff561ccda2e49edc4f29044f2a82
5,433
java
Java
jingnan_web/src/main/java/com/jn/web/goods/service/impl/CartServiceImpl.java
zhoushaoping2021/jingnan_parent_base
e552953afc679f206c1beab4140eb55f4c45eeeb
[ "Apache-2.0" ]
null
null
null
jingnan_web/src/main/java/com/jn/web/goods/service/impl/CartServiceImpl.java
zhoushaoping2021/jingnan_parent_base
e552953afc679f206c1beab4140eb55f4c45eeeb
[ "Apache-2.0" ]
null
null
null
jingnan_web/src/main/java/com/jn/web/goods/service/impl/CartServiceImpl.java
zhoushaoping2021/jingnan_parent_base
e552953afc679f206c1beab4140eb55f4c45eeeb
[ "Apache-2.0" ]
null
null
null
30.522472
113
0.608688
1,001,677
package com.jn.web.goods.service.impl; import com.jn.entity.Constants; import com.jn.pojo.OrderItem; import com.jn.pojo.Sku; import com.jn.pojo.Spu; import com.jn.util.IdWorker; import com.jn.web.goods.service.CartService; import com.jn.web.goods.service.SkuService; import com.jn.web.goods.service.SpuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @Author muYan * @Version 1.0 * @Since 2021-02-01 */ @Service public class CartServiceImpl implements CartService { @Autowired RedisTemplate redisTemplate; @Autowired SpuService spuService; @Autowired SkuService skuService; @Autowired IdWorker idWorker; @Override public Map<String, Object> list(String userName) { //1. 根据当前登录用户的用户名, 到redis中获取购物车集合数据返回 List<OrderItem> orderItemList = redisTemplate.boundHashOps(Constants.REDIS_CART + userName).values(); //2. 计算所有商品总价格, 总购买数量 //总购买数量 Integer totalCount = 0; //总购买商品的价格 Integer totalPrice = 0; if (orderItemList != null) { for (OrderItem orderItem : orderItemList) { //计算总购买数量 totalCount += orderItem.getNum(); //计算总购买价格 totalPrice += orderItem.getMoney(); } } //2. 封装购物车列表页面需要的数据返回 Map<String, Object> resultMap = new HashMap<>(); //购物车中的购物项集合数据 resultMap.put("orderItemList", orderItemList); //总购买数量 resultMap.put("totalNum", totalCount); //总购买价格 resultMap.put("totalPrice", totalPrice); return resultMap; } @Override public void addAndUpdate(String userName, String skuId, Integer num) { //1. 根据用户名到redis中获取购物车信息 OrderItem orderItem = (OrderItem) redisTemplate.boundHashOps(Constants.REDIS_CART + userName).get(skuId); //2. 判断redis中的购物车是否为空 if (orderItem != null) { //3. 如果redis中的购物车不为空, 追加购物项 //购买数量追加 = 原来购物项的购买数量 + 现在要购买的数量 orderItem.setNum(orderItem.getNum() + num); //本方法支持购买数量增减调整, 判断最终的购买数量, 是否大于0件 if (orderItem.getNum() <= 0) { //如果购买数量<=0件, 从购物车中删除这个购物项 redisTemplate.boundHashOps(Constants.REDIS_CART + userName).delete(skuId); //返回 return ; } //总价格 = 购买数量 * 单价 orderItem.setMoney(orderItem.getNum() * orderItem.getPrice()); //支付价格 = 购买数量 * 单价 orderItem.setPayMoney(orderItem.getNum() * orderItem.getPrice()); } else { //4. 如果redis中的购物车为空, 新建购物车, 然后将购物项放入其中 orderItem = createOrderItem(skuId, num); } //5. 将最新的购物车, 从新放到redis中的, 覆盖redis中之前的购物车数据 redisTemplate.boundHashOps(Constants.REDIS_CART + userName).put(skuId, orderItem); } @Override public void del(String userName, String skuId) { redisTemplate.boundHashOps(Constants.REDIS_CART + userName).delete(skuId); } @Override public void updateChecked(String userName, String skuId, Boolean checked) { //1. 获取购物项实体对象 OrderItem orderItem = (OrderItem)redisTemplate.boundHashOps(Constants.REDIS_CART + userName).get(skuId); if (orderItem != null) { //2.更改购物项中的是否勾选属性值 orderItem.setChecked(checked); //3. 将购物项从新放回到redis中 redisTemplate.boundHashOps(Constants.REDIS_CART + userName).put(skuId, orderItem); } } /** * 创建购物项对象 * @param skuId 库存id * @param num 购买数量 * @return */ private OrderItem createOrderItem(String skuId, Integer num) { //1. 判断传入的购买数量不能为空 if (num <= 0) { throw new RuntimeException("购买数量最少是1件"); } //2. 根据skuid, 获取sku对象 Sku sku = skuService.findOneByskuId(skuId); if (sku == null) { throw new RuntimeException("skuId错误, 无效的skuId, 数据库中找不到对应的库存sku数据!"); } //3. 根据spuId, 获取spu对象 Spu spu = spuService.findById(sku.getSpuId()); if (spu == null) { throw new RuntimeException("skuId错误, 无效的skuId, 数据库中找不到对应的spu商品数据!"); } //4. 创建购物项对象(订单详情对象) OrderItem orderItem = new OrderItem(); //订单详情(购物项)主键id orderItem.setId(String.valueOf(idWorker.nextId())); //购买数量 orderItem.setNum(num); //商品id orderItem.setSpuId(spu.getId()); //库存id orderItem.setSkuId(skuId); //单价 orderItem.setPrice(sku.getPrice()); //库存名称 orderItem.setName(sku.getName()); //总价钱 orderItem.setMoney(orderItem.getNum() * orderItem.getPrice()); //支付价钱 orderItem.setPayMoney(orderItem.getNum() * orderItem.getPrice()); //运费 orderItem.setPostFee(0); //商品示例图片 orderItem.setImage(sku.getImage()); //一级分类 orderItem.setCategoryId1(spu.getCategory1Id()); //二级分类 orderItem.setCategoryId2(spu.getCategory2Id()); //三级分类 orderItem.setCategoryId3(spu.getCategory3Id()); //商品重量 orderItem.setWeight(sku.getWeight()); //购物车列表页面中, 复选框是否选中状态 orderItem.setChecked(true); return orderItem; } }
9240d1ea530023436b5bfb3333d48482e31371ac
6,283
java
Java
Animator/src/main/java/au/gov/ga/worldwind/animator/application/KeyFrameClipboard.java
ga-m3dv/ga-worldwind-suite
13f26992f3d2a6ff66d0383a0aa86a07edf91a0f
[ "Apache-2.0" ]
10
2015-03-10T18:09:41.000Z
2016-06-30T15:17:08.000Z
Animator/src/main/java/au/gov/ga/worldwind/animator/application/KeyFrameClipboard.java
GeoscienceAustralia/ga-worldwind-suite
13f26992f3d2a6ff66d0383a0aa86a07edf91a0f
[ "Apache-2.0" ]
1
2015-07-15T06:31:21.000Z
2015-07-15T06:31:21.000Z
Animator/src/main/java/au/gov/ga/worldwind/animator/application/KeyFrameClipboard.java
GeoscienceAustralia/ga-worldwind-suite
13f26992f3d2a6ff66d0383a0aa86a07edf91a0f
[ "Apache-2.0" ]
5
2019-01-11T22:47:50.000Z
2021-09-27T01:18:34.000Z
29.516432
141
0.728646
1,001,678
/******************************************************************************* * Copyright 2012 Geoscience Australia * * 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 au.gov.ga.worldwind.animator.application; import static au.gov.ga.worldwind.animator.util.message.AnimationMessageConstants.getCopyKeyFrameLabelKey; import static au.gov.ga.worldwind.animator.util.message.AnimationMessageConstants.getCutKeyFrameLabelKey; import static au.gov.ga.worldwind.animator.util.message.AnimationMessageConstants.getPasteKeyFrameLabelKey; import static au.gov.ga.worldwind.common.util.message.MessageSourceAccessor.getMessage; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.Action; import javax.swing.KeyStroke; import au.gov.ga.worldwind.animator.animation.Animation; import au.gov.ga.worldwind.animator.animation.KeyFrame; import au.gov.ga.worldwind.animator.animation.KeyFrameImpl; import au.gov.ga.worldwind.animator.animation.event.AnimationEvent; import au.gov.ga.worldwind.animator.animation.event.AnimationEventListener; import au.gov.ga.worldwind.animator.ui.frameslider.ChangeFrameListener; import au.gov.ga.worldwind.animator.ui.frameslider.CurrentFrameChangeListener; import au.gov.ga.worldwind.animator.util.Icons; import au.gov.ga.worldwind.common.ui.BasicAction; import au.gov.ga.worldwind.common.util.Validate; /** * A clipboard that holds a keyframe and can perform cut-copy-paste operations * * @author James Navin ([email protected]) */ public class KeyFrameClipboard implements CurrentFrameChangeListener, ChangeFrameListener, AnimationEventListener, ChangeOfAnimationListener { /** The key frame currently in the clipboard */ private KeyFrame clipboardKeyFrame; private Animation animation; private BasicAction copyAction; private BasicAction cutAction; private BasicAction pasteAction; public KeyFrameClipboard(Animation animation) { Validate.notNull(animation, "An animation is required"); this.animation = animation; initialiseActions(); updateActionEnabledStatus(); } private void initialiseActions() { copyAction = new BasicAction(getMessage(getCopyKeyFrameLabelKey()), Icons.copy.getIcon()); copyAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.CTRL_MASK)); copyAction.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { copySelectedKeyFrame(); } }); cutAction = new BasicAction(getMessage(getCutKeyFrameLabelKey()), Icons.cut.getIcon()); cutAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK)); cutAction.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { cutSelectedKeyFrame(); } }); pasteAction = new BasicAction(getMessage(getPasteKeyFrameLabelKey()), Icons.paste.getIcon()); pasteAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK)); pasteAction.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { pasteSelectedKeyFrame(); } }); } public boolean isKeyFrameInClipboard() { return clipboardKeyFrame != null; } public KeyFrame getKeyFrameInClipboard() { return clipboardKeyFrame; } public void copySelectedKeyFrame() { KeyFrame selectedKeyFrame = getSelectedKeyFrame(); if (selectedKeyFrame != null) { clipboardKeyFrame = selectedKeyFrame.clone(); updateActionEnabledStatus(); } } public void cutSelectedKeyFrame() { KeyFrame selectedKeyFrame = getSelectedKeyFrame(); if (selectedKeyFrame != null) { clipboardKeyFrame = selectedKeyFrame.clone(); animation.removeKeyFrame(selectedKeyFrame); updateActionEnabledStatus(); } } public void pasteSelectedKeyFrame() { if (!isKeyFrameInClipboard()) { return; } animation.insertKeyFrame(createKeyFrameForCurrentFrame(), true); updateActionEnabledStatus(); } public void clearClipboard() { clipboardKeyFrame = null; pasteAction.setEnabled(false); } public void updateAnimation(Animation newAnimation) { Validate.notNull(newAnimation, "An animation is required"); this.animation = newAnimation; clearClipboard(); } private KeyFrame createKeyFrameForCurrentFrame() { return new KeyFrameImpl(getCurrentFrame(), clipboardKeyFrame.getParameterValues()); } private KeyFrame getSelectedKeyFrame() { return animation.getKeyFrame(getCurrentFrame()); } private int getCurrentFrame() { return animation.getCurrentFrame(); } public BasicAction getCopyAction() { return copyAction; } public BasicAction getCutAction() { return cutAction; } public BasicAction getPasteAction() { return pasteAction; } @Override public void currentFrameChanged(int newFrame) { updateActionEnabledStatus(); } @Override public void frameChanged(int index, int oldFrame, int newFrame) { updateActionEnabledStatus(); } @Override public void receiveAnimationEvent(AnimationEvent event) { if (event.getRootCause().getValue() instanceof KeyFrame) { updateActionEnabledStatus(); } } private void updateActionEnabledStatus() { boolean hasKeyAtFrame = getSelectedKeyFrame() != null; cutAction.setEnabled(hasKeyAtFrame); copyAction.setEnabled(hasKeyAtFrame); pasteAction.setEnabled(isKeyFrameInClipboard()); } }
9240d29b873ded4aeea296fa90d8e8924ca95b57
14,097
java
Java
src/com/cladonia/xngreditor/TextPrinter.java
HiltonRoscoe/exchangerxml
6da3871f1094633bd98c95fd3f404cfbf805fe43
[ "ClArtistic" ]
6
2021-01-31T21:22:32.000Z
2021-07-13T04:52:24.000Z
src/com/cladonia/xngreditor/TextPrinter.java
HiltonRoscoe/exchangerxml
6da3871f1094633bd98c95fd3f404cfbf805fe43
[ "ClArtistic" ]
8
2021-01-08T20:49:50.000Z
2021-06-27T23:14:03.000Z
src/com/cladonia/xngreditor/TextPrinter.java
HiltonRoscoe/exchangerxml
6da3871f1094633bd98c95fd3f404cfbf805fe43
[ "ClArtistic" ]
null
null
null
25.218247
136
0.623821
1,001,679
/* * $Id: TextPrinter.java,v 1.1 2004/03/25 18:52:46 edankert Exp $ * * Copyright (C) 2002, Cladonia Ltd. All rights reserved. * * This software is the proprietary information of Cladonia Ltd. * Use is subject to license terms. */ package com.cladonia.xngreditor; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.font.FontRenderContext; import java.awt.print.Book; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.util.Vector; import javax.swing.text.BadLocationException; import javax.swing.text.Element; import javax.swing.text.PlainDocument; import javax.swing.text.Segment; /** * A simple text printer class. * * @version $Revision: 1.1 $, $Date: 2004/03/25 18:52:46 $ * @author Dogsbay */ public class TextPrinter { private static TextPrinter printer = null; private boolean printLineNumbers = false; private boolean wrapText = false; private boolean printHeader = false; private Font font = null; // the page font (default) private PageFormat pageFormat = null; private Book book = null; private String title = null; private String[] text = null; private int pages = 0; private int wrapOffset = 0; private int tabSize = 4; /** * returns the one text-printer object */ public static TextPrinter getPrinter() { if ( printer == null) { printer = new TextPrinter(); } return printer; } /** * Constructor, sets the initial values. */ private TextPrinter() { pageFormat = new PageFormat(); font = new Font("Courier", Font.PLAIN, 10); } /** * Prints a document! * * @param document the document to print. */ public void print( PlainDocument document) throws PrinterException { print( document, "", 4); } /** * Prints a document! * * @param document the document to print. * @param title the document title. * @param softabs wether to have soft-tabs. * @param tabsize the size of the tabs. */ public void print( PlainDocument document, String title, int tabSize) throws PrinterException { Element root = document.getDefaultRootElement(); String lines[] = new String[ root.getElementCount()]; Segment segment = new Segment(); // Get each line element, get its text and put it in the string array for (int i = 0; i < lines.length; i++) { Element line = (Element) root.getElement(i); try { document.getText( line.getStartOffset(), line.getEndOffset() - line.getStartOffset(), segment); lines[i] = segment.toString(); } catch (BadLocationException ble) {} } print( lines, title, tabSize); } /** * Prints an array of Strings! * * @param text the array of strings. */ public void print( String[] text) throws PrinterException { print( text, "", 4); } /** * Prints an array of Strings! * * @param text the array of strings. * @param title the document title. * @param tabsize the size of the tabs. */ public void print( String[] text, String title, int tabSize) throws PrinterException { this.tabSize = tabSize; this.title = title; this.text = text; this.book = new Book(); printTextArray(); } /** * Setup the printer! */ public void setup() { PrinterJob job = PrinterJob.getPrinterJob(); pageFormat = job.pageDialog( pageFormat); pageFormat = job.validatePage( pageFormat); } // Print the text... private void printTextArray() throws PrinterException { PageFormat format = pageFormat; Font pageFont = font; PrinterJob job = PrinterJob.getPrinterJob(); pageFormat = job.validatePage( pageFormat); text = removeEOLChar(); if ( printLineNumbers) { text = addLineNumbers(); } if ( wrapText == true) { text = wrapText(); } book = pageinateText(); job.setPageable( book); if ( job.printDialog()) { job.print(); } } // Remove end of line characters private String[] removeEOLChar() { String temp1 = null; String temp2 = null; String temp3 = null; int lineCount = text.length; String[] newText = new String[ lineCount]; int offset = 0; for (int i = 0; i < lineCount; i++) { if ( text[i].length() == 1) { newText[i] = " "; } else { temp1 = text[i].substring( text[i].length() - 2, text[i].length() - 1); temp2 = text[i].substring( text[i].length() - 1, text[i].length()); if ( temp1.compareTo("\r") == 0 || temp1.compareTo("\n") == 0) { offset = 2; } else if ( temp2.compareTo("\r") == 0 || temp2.compareTo("\n") == 0) { offset = 1; } else { offset = 0; } temp3 = text[i].substring( 0, text[i].length() - offset); StringBuffer temp4 = new StringBuffer(); int length = temp3.length(); for (int j = 0; j < length; j++) { if ( "\t".equals( temp3.substring(j, j + 1)) == true) { int numSpaces = temp4.length() % tabSize; if ( numSpaces == 0) { numSpaces = tabSize; } for ( int x = 0; x < numSpaces; x++) { temp4.append(" "); } } else { temp4.append( temp3.substring(j, j + 1)); } } newText[i] = temp4.toString(); } } return newText; } /** * Adds line numbers to the beginning of each line. */ private String[] addLineNumbers() { int numLines = text.length; int totalNumSpaces = 0; String temp = null; String[] newText = new String[numLines]; // Get the total number of digits in last line number // So that spacing and alignment can be done properly. Integer lines = new Integer(numLines); temp = lines.toString(); totalNumSpaces = temp.length(); // Set the wrap offset so that we can start wrapped lines in the proper place. wrapOffset = totalNumSpaces + 3; for ( int i = 0; i < numLines; i++) { StringBuffer num = new StringBuffer(); num.append(i + 1); int numLen = num.length(); StringBuffer lineNum = new StringBuffer(); for (int j = 0; j < (totalNumSpaces - numLen); j++) { lineNum.append(' '); } lineNum.append(num.toString()); newText[i] = lineNum.toString() + ". " + text[i]; } return newText; } /** * Creates a new array of lines that all fit the width of the page. */ private String[] wrapText() { String currentLine = null; String tempString = null; Vector temp = new Vector(); int lineCount = text.length; int newLineCount = 0; StringBuffer wrapSpaces = new StringBuffer(""); int i = 0; PageFormat pgfmt = pageFormat; Font pageFont = font; double pageWidth = pgfmt.getImageableWidth(); for (i = 0; i < wrapOffset; i++) { wrapSpaces.append(' '); } for (i = 0; i < lineCount; i++) { currentLine = text[i]; while (pageFont.getStringBounds(currentLine, new FontRenderContext(pageFont.getTransform(), false, false)).getWidth() > pageWidth) { int numChars = (int)(currentLine.length() * pageWidth / pageFont.getStringBounds(currentLine, new FontRenderContext(pageFont.getTransform(), false, false)).getWidth()); temp.add(currentLine.substring(0, numChars)); currentLine = wrapSpaces.toString() + currentLine.substring(numChars, currentLine.length()); } temp.add(currentLine); } newLineCount = temp.size(); String [] newText = new String[newLineCount]; for (int j = 0; j < newLineCount; j++) { newText[j] = (String) temp.get(j); } return newText; } /** * The pagination method, Paginate the text onto Printable page objects */ private Book pageinateText() { Book book = new Book(); int linesPerPage = 0; // lines on one page int currentLine = 0; // line I am currently reading int pageNum = 0; // page # PageFormat format = pageFormat; Font pageFont = font; int height = (int) format.getImageableHeight(); // height of a page int pages = 0; // number of pages linesPerPage = height / (pageFont.getSize() + 2); // number of lines on a page pages = ((int) text.length / linesPerPage); // set number of pages String[] pageText; // one page of text String readString; // a temporary string to read from master string convertUnprintables(); // method to keep out errors if ( printHeader == true) { linesPerPage = linesPerPage - 2; } while (pageNum <= pages) { pageText = new String[linesPerPage]; // create a new page for (int x = 0; x < linesPerPage; x++) { try { readString = text[ currentLine]; // read the string } catch (ArrayIndexOutOfBoundsException e) { readString = " "; } pageText[x] = readString; // add to the page currentLine++; } pageNum++; book.append( new Page( pageText, pageNum), format); } return book; // return the completed book } /** * Converts unprintable things to a space. stops some errors. */ private void convertUnprintables() { String tempString; int i = text.length; while (i > 0) { i--; tempString = text[i]; if (tempString == null || "".equals(tempString)) { text[i] = " "; } } } // methods to set the print properties. /** * Enable/Disable printing of line numbers. * * @param enable enable the printing of line numbers. */ public void setPrintLineNumber( boolean enable) { printLineNumbers = enable; } /** * Find out if printing of line numbers has been enabled. * * @return true when the printing of linenumbers has been enabled. */ public boolean isPrintLineNumber() { return printLineNumbers; } /** * Enable/Disable wrapping of text. * * @param enable enable the wrapping of text. */ public void setWrapText( boolean enable) { wrapText = enable; } /** * Find out if wrapping of text has been enabled. * * @return true when the wrapping of text has been enabled. */ public boolean isWrapText() { return wrapText; } /** * Enable/Disable printing of the header. * * @param enable enable the printing of the header. */ public void setPrintHeader( boolean enable) { printHeader = enable; } /** * Find out if printing of the header has been enabled. * * @return true when the printing of the header has been enabled. */ public boolean isPrintHeader() { return printHeader; } /** * Set the printing font. * * @param font the printing font. */ public void setFont( Font font) { this.font = font; } /** * Get the printing font. * * @return the printing font. */ public Font getFont() { return font; } /** * An inner class that defines one page of text based * on data about the PageFormat etc. from the book defined * in the parent class */ class Page implements Printable { private String[] pageText; // the text for the page private int pageNumber = 0; Page(String[] text, int pageNum) { this.pageText = text; // set the page's text this.pageNumber = pageNum; // set page number. } /** * Defines the Printable print method, for printing a Page */ public int print( Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { int pos; int posOffset = 1; double pageWidth = pageFormat.getImageableWidth(); Font pageFont = font; if ( printHeader == true) { // StringBuffer header = new StringBuffer(); StringBuffer pageNumText = new StringBuffer(); int i = 0; int headerPos = 0; int numSpaces = 0; // Calendar date = Calendar.getInstance(); // header.append(date.get(Calendar.DAY_OF_MONTH)); // header.append('/'); // header.append(date.get(Calendar.MONTH) + 1); // header.append('/'); // header.append(date.get(Calendar.YEAR)); // header.append( title); pageNumText.append("Page "); pageNumText.append( pageNumber); double margin = (pageFormat.getWidth() - pageFormat.getImageableWidth()) / 2; graphics.setFont( font); graphics.setColor( Color.black); pos = (int) pageFormat.getImageableY() + (font.getSize() + 2); graphics.drawString( title, (int) pageFormat.getImageableX(), pos); // draw the title // xPos = (int)((pageFormat.getWidth() / 2) - (graphics.getFontMetrics().stringWidth( title) / 2)); // graphics.drawString( title, xPos, pos); int xPos = (int)(pageFormat.getWidth() - margin - graphics.getFontMetrics().stringWidth( pageNumText.toString())); graphics.drawString(pageNumText.toString(), xPos, pos); posOffset = 3; } graphics.setFont(pageFont); // Set the font graphics.setColor(Color.black); // set color for (int x = 0; x < (pageText.length); x++) { pos = (int) pageFormat.getImageableY() + (pageFont.getSize() + 2) * (x + posOffset); graphics.drawString(this.pageText[x], (int) pageFormat.getImageableX(), pos); // draw a line of text } return Printable.PAGE_EXISTS; // print the page } } /** * An inner class that defines one section of printable text. * This allows the flexability to assign different fonts to * individual words or phrases (i.e. for headers/footers or * Syntax highlighting (pretty print). */ class PrintableText { private Font font; private boolean newLine = true; private String text; PrintableText(){ } PrintableText( String text, Font font, boolean newLine) { this.text = text; this.font = font; this.newLine = newLine; } String getText() { return text; } void setText( String text) { this.text = text; } Font getFont() { return font; } void setFont( Font font) { this.font = font; } boolean isNewLine() { return newLine; } void setNewLine( boolean newLine) { this.newLine = newLine; } } }
9240d2b64e5aa46f0d3fe448efd85977b7c25840
4,203
java
Java
core/rio/api/src/main/java/org/eclipse/rdf4j/rio/RDFParseException.java
yanaspaula/rdf4j
e75f8940c48caf9847dd775fd6a67866dc9b9dcd
[ "BSD-3-Clause" ]
312
2016-01-14T20:04:24.000Z
2022-03-30T22:21:41.000Z
core/rio/api/src/main/java/org/eclipse/rdf4j/rio/RDFParseException.java
yanaspaula/rdf4j
e75f8940c48caf9847dd775fd6a67866dc9b9dcd
[ "BSD-3-Clause" ]
2,611
2016-01-18T22:32:22.000Z
2022-03-31T17:38:43.000Z
core/rio/api/src/main/java/org/eclipse/rdf4j/rio/RDFParseException.java
yanaspaula/rdf4j
e75f8940c48caf9847dd775fd6a67866dc9b9dcd
[ "BSD-3-Clause" ]
186
2016-01-14T21:18:37.000Z
2022-03-22T12:32:33.000Z
28.398649
119
0.662384
1,001,680
/******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.rio; import org.eclipse.rdf4j.RDF4JException; /** * A parse exception that can be thrown by a parser when it encounters an error from which it cannot or doesn't want to * recover. */ public class RDFParseException extends RDF4JException { /*-----------* * Constants * *-----------*/ private static final long serialVersionUID = -4686126837948873012L; private final long lineNo; private final long columnNo; /*--------------* * Constructors * *--------------*/ /** * Creates a new ParseException. * * @param msg An error message. */ public RDFParseException(String msg) { this(msg, -1, -1); } /** * Creates a new ParseException. * * @param msg An error message. * @param lineNo A line number associated with the message. * @param columnNo A column number associated with the message. */ public RDFParseException(String msg, long lineNo, long columnNo) { super(msg + getLocationString(lineNo, columnNo)); this.lineNo = lineNo; this.columnNo = columnNo; } /** * Creates a new ParseException wrapping another exception. The ParseException will inherit its message from the * supplied source exception. * * @param t The source exception. */ public RDFParseException(Throwable t) { this(t, -1, -1); } /** * Creates a new ParseException wrapping another exception. The ParseException will inherit its message from the * supplied source exception. * * @param msg An error message. * @param t The source exception. */ public RDFParseException(String msg, Throwable t) { this(msg, t, -1, -1); } /** * Creates a new ParseException wrapping another exception. The ParseException will inherit its message from the * supplied source exception. * * @param t The source exception. * @param lineNo A line number associated with the message. * @param columnNo A column number associated with the message. */ public RDFParseException(Throwable t, long lineNo, long columnNo) { super(t.getMessage() + getLocationString(lineNo, columnNo), t); this.lineNo = lineNo; this.columnNo = columnNo; } /** * Creates a new ParseException wrapping another exception. The ParseException will inherit its message from the * supplied source exception. * * @param t The source exception. * @param lineNo A line number associated with the message. * @param columnNo A column number associated with the message. */ public RDFParseException(String msg, Throwable t, long lineNo, long columnNo) { super(msg + getLocationString(lineNo, columnNo), t); this.lineNo = lineNo; this.columnNo = columnNo; } /*---------* * Methods * *---------*/ /** * Gets the line number associated with this parse exception. * * @return A line number, or -1 if no line number is available or applicable. */ public long getLineNumber() { return lineNo; } /** * Gets the column number associated with this parse exception. * * @return A column number, or -1 if no column number is available or applicable. */ public long getColumnNumber() { return columnNo; } /** * Creates a string to that shows the specified line and column number. Negative line numbers are interpreted as * unknowns. Example output: "[line 12, column 34]". If the specified line number is negative, this method returns * an empty string. */ public static String getLocationString(long lineNo, long columnNo) { if (lineNo < 0) { return ""; } StringBuilder sb = new StringBuilder(16); sb.append(" [line "); sb.append(lineNo); if (columnNo >= 0) { sb.append(", column "); sb.append(columnNo); } sb.append("]"); return sb.toString(); } }
9240d4906a1717c22c46415dd4fd91980762ec71
8,738
java
Java
component/src/main/java/io/siddhi/extension/execution/time/ExtractDayOfWeekFunctionExtension.java
wso2-extensions/siddhi-time
11a5539c091cc80b995800a3ad76eaf48978af19
[ "Apache-2.0" ]
1
2018-10-12T07:04:42.000Z
2018-10-12T07:04:42.000Z
component/src/main/java/io/siddhi/extension/execution/time/ExtractDayOfWeekFunctionExtension.java
wso2-extensions/siddhi-time
11a5539c091cc80b995800a3ad76eaf48978af19
[ "Apache-2.0" ]
6
2017-08-29T07:19:51.000Z
2018-07-11T16:34:41.000Z
component/src/main/java/io/siddhi/extension/execution/time/ExtractDayOfWeekFunctionExtension.java
wso2-extensions/siddhi-time
11a5539c091cc80b995800a3ad76eaf48978af19
[ "Apache-2.0" ]
24
2016-11-18T11:38:31.000Z
2019-05-06T07:20:31.000Z
42.62439
120
0.611353
1,001,681
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. 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 io.siddhi.extension.execution.time; import io.siddhi.annotation.Example; import io.siddhi.annotation.Extension; import io.siddhi.annotation.Parameter; import io.siddhi.annotation.ParameterOverload; import io.siddhi.annotation.ReturnAttribute; import io.siddhi.annotation.util.DataType; import io.siddhi.core.config.SiddhiQueryContext; import io.siddhi.core.exception.SiddhiAppRuntimeException; import io.siddhi.core.executor.ExpressionExecutor; import io.siddhi.core.executor.function.FunctionExecutor; import io.siddhi.core.util.config.ConfigReader; import io.siddhi.core.util.snapshot.state.State; import io.siddhi.core.util.snapshot.state.StateFactory; import io.siddhi.extension.execution.time.util.TimeExtensionConstants; import io.siddhi.query.api.definition.Attribute; import io.siddhi.query.api.exception.SiddhiAppValidationException; import org.apache.commons.lang3.time.FastDateFormat; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * dayOfWeek(dateValue,dateFormat) * Returns day on which a given date falls. * dateValue - value of date. eg: "2014-11-11 13:23:44.657", "2014-11-11" * dateFormat - Date format of the provided date value. eg: yyyy-MM-dd HH:mm:ss.SSS * Accept Type(s) for dayOfWeek(dateValue,dateFormat): * dateValue : STRING * dateFormat : STRING * Return Type(s): STRING * <p> * In the case of using only the datevalue as the parameter, user has to follow * the following specific format for the date * yyyy-MM-dd time */ /** * Class representing the Time dayOfWeek implementation. */ @Extension( name = "dayOfWeek", namespace = "time", description = "Extracts the day on which a given date falls.", parameters = { @Parameter(name = "date.value", description = "The value of the date. " + "For example, `2014-11-11 13:23:44.657`, `2014-11-11`, `13:23:44.657`.", type = {DataType.STRING}, dynamic = true), @Parameter(name = "date.format", description = "The format of the date value provided. " + "For example, `yyyy/MM/dd HH:mm:ss.SSS`.", type = {DataType.STRING}, dynamic = true, optional = true, defaultValue = "`yyyy-MM-dd HH:mm:ss.SSS`"), }, parameterOverloads = { @ParameterOverload(parameterNames = {"date.value", "date.format"}), @ParameterOverload(parameterNames = {"date.value"}) }, returnAttributes = @ReturnAttribute( description = "Returns the day of the week corresponding to the date value given. " + "The values can be one of `Monday`, `Tuesday`, `Wednesday`, `Thursday`, `Friday`, " + "`Saturday`, or `Sunday`.", type = {DataType.STRING}), examples = { @Example( syntax = "time:date('2014/12/11 13:23:44', 'yyyy/MM/dd HH:mm:ss')", description = "Extracts the date and returns `Thursday`." ), @Example( syntax = "time:date('2014-11-11 13:23:44.345')", description = "Extracts the date and returns `Tuesday`." ), } ) public class ExtractDayOfWeekFunctionExtension extends FunctionExecutor { private static final long serialVersionUID = 1L; private Attribute.Type returnType = Attribute.Type.STRING; @Override protected StateFactory init(ExpressionExecutor[] attributeExpressionExecutors, ConfigReader configReader, SiddhiQueryContext siddhiQueryContext) { if (attributeExpressionExecutors.length > 2) { throw new SiddhiAppValidationException("Invalid no of arguments passed to time:dayOfWeek(dateValue," + "dateFormat) function, " + "required 2, but found " + attributeExpressionExecutors.length); } if (attributeExpressionExecutors[0].getReturnType() != Attribute.Type.STRING) { throw new SiddhiAppValidationException("Invalid parameter type found for the first argument of " + "time:dayOfWeek(dateValue,dateFormat) function, " + "required " + Attribute.Type.STRING + " but found " + attributeExpressionExecutors[0] .getReturnType().toString()); } //User can omit sending the dateFormat thus using a default CEP Time format if (attributeExpressionExecutors.length > 0) { if (attributeExpressionExecutors.length > 1 && attributeExpressionExecutors[1].getReturnType() != Attribute.Type.STRING) { throw new SiddhiAppValidationException("Invalid parameter type found for the second argument of " + "time:dayOfWeek(dateValue,dateFormat) function, " + "required " + Attribute.Type.STRING + " but found " + attributeExpressionExecutors[1] .getReturnType().toString()); } } return null; } @Override protected Object execute(Object[] data, State state) { String userFormat; if (data[0] == null) { return null; } if (data.length > 1) { if (data[1] == null) { return null; } else { userFormat = (String) data[1]; } } else { userFormat = TimeExtensionConstants.EXTENSION_TIME_DEFAULT_DATE_FORMAT; } String source = null; FastDateFormat userSpecificFormat; Date userSpecifiedDate; try { source = (String) data[0]; userSpecificFormat = FastDateFormat.getInstance(userFormat); userSpecifiedDate = userSpecificFormat.parse(source); return getDayOfWeek(userSpecifiedDate); } catch (ParseException e) { String errorMsg = "Provided format " + userFormat + " does not match with the timestamp " + source + e .getMessage(); throw new SiddhiAppRuntimeException(errorMsg, e); } catch (ClassCastException e) { String errorMsg = "Provided Data type cannot be cast to desired format. " + e.getMessage(); throw new SiddhiAppRuntimeException(errorMsg, e); } } @Override protected Object execute(Object data, State state) { String userFormat; if (data == null) { return null; } userFormat = TimeExtensionConstants.EXTENSION_TIME_DEFAULT_DATE_FORMAT; String source; try { source = (String) data; String inputData[] = source.split(" "); DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); try { Date date = format.parse(inputData[0]); return getDayOfWeek(date); } catch (ParseException e) { String errorMsg = "Provided format " + userFormat + " does not match with the timestamp " + source + e .getMessage(); throw new SiddhiAppRuntimeException(errorMsg, e); } } catch (ClassCastException e) { String errorMsg = "Provided Data type cannot be cast to desired format. " + e.getMessage(); throw new SiddhiAppRuntimeException(errorMsg, e); } } @Override public Attribute.Type getReturnType() { return returnType; } //private methods private String getDayOfWeek(Date date) { DateFormat dateFormatDayOfWeek = new SimpleDateFormat(TimeExtensionConstants.EXTENSION_TIME_SIMPLE_DATE_FORMAT); return dateFormatDayOfWeek.format(date); } }
9240d5bc88f955f36a3e9208f565f6a1945a7dcd
1,700
java
Java
book-spring-5-recipes/ch12/recipe_12_1_vi/src/main/java/com/apress/springrecipes/nosql/Main.java
zou-zhicheng/awesome-java
99eaaf93525ffe48598b28c9eb342ddde8de4492
[ "Apache-2.0" ]
1
2021-09-29T07:24:56.000Z
2021-09-29T07:24:56.000Z
book-spring-5-recipes/ch12/recipe_12_1_vi/src/main/java/com/apress/springrecipes/nosql/Main.java
zou-zhicheng/awesome-java
99eaaf93525ffe48598b28c9eb342ddde8de4492
[ "Apache-2.0" ]
null
null
null
book-spring-5-recipes/ch12/recipe_12_1_vi/src/main/java/com/apress/springrecipes/nosql/Main.java
zou-zhicheng/awesome-java
99eaaf93525ffe48598b28c9eb342ddde8de4492
[ "Apache-2.0" ]
1
2021-09-17T15:05:17.000Z
2021-09-17T15:05:17.000Z
38.636364
110
0.648235
1,001,682
package com.apress.springrecipes.nosql; import java.util.concurrent.CountDownLatch; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import com.apress.springrecipes.nosql.config.MongoConfiguration; import reactor.core.publisher.Flux; /** * Created by marten on 22-09-14. */ public class Main { public static void main(String[] args) throws Exception { ApplicationContext ctx = new AnnotationConfigApplicationContext(MongoConfiguration.class); VehicleRepository repository = ctx.getBean(VehicleRepository.class); CountDownLatch countDownLatch = new CountDownLatch(1); repository.count().doOnSuccess(cnt -> System.out.println("Number of Vehicles: " + cnt)) .thenMany( repository.saveAll( Flux.just( new Vehicle("TEM0001", "RED", 4, 4), new Vehicle("TEM0002", "RED", 4, 4)))) .last() .then(repository.count()).doOnSuccess(cnt -> System.out.println("Number of Vehicles: " + cnt)) .then(repository.findByVehicleNo("TEM0001")).doOnSuccess(System.out::println) .then(repository.deleteAll()) .doOnSuccess(x -> countDownLatch.countDown()) .doOnError(t -> countDownLatch.countDown()) .then(repository.count()).subscribe(cnt -> System.out.println("Number of Vehicles: " + cnt)); countDownLatch.await(); ((AbstractApplicationContext) ctx).close(); } }
9240d5cbc933a826251fea637b04029e7bfaa91f
770
java
Java
server/src/main/java/com/pinche/infrastructure/repository/AddressRepository.java
WenRou-Pan/pin
2c7bf6a8215688f10ac24b6455980251c650c087
[ "MIT" ]
null
null
null
server/src/main/java/com/pinche/infrastructure/repository/AddressRepository.java
WenRou-Pan/pin
2c7bf6a8215688f10ac24b6455980251c650c087
[ "MIT" ]
null
null
null
server/src/main/java/com/pinche/infrastructure/repository/AddressRepository.java
WenRou-Pan/pin
2c7bf6a8215688f10ac24b6455980251c650c087
[ "MIT" ]
null
null
null
17.111111
56
0.577922
1,001,683
package com.pinche.infrastructure.repository; import com.pinche.domain.address.AddressDO; import com.pinche.domain.address.Dot; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; /** * @author Parmaze * @date 2021/12/16 */ @Mapper public interface AddressRepository { /** * 增加地址 * * @param addressDO * @return */ int insert(@Param("addressDO") AddressDO addressDO); /** * 查询地址 * * @param dot * @return */ AddressDO find(@Param("dot") Dot dot); /** * 增加地址 * * @param id */ void addPoint(@Param("id") Integer id); /** * 查询地址 * * @param id * @return */ AddressDO findById(@Param("id") Integer id); }
9240d5f2d2b105eb0406c534251c98076ffe2c21
1,299
java
Java
src/Estudiante.java
SamuelColmenares/estructura-datos-multilistas
97e86b3473b0b709a73d60c0650df55bf84f0d71
[ "MIT" ]
null
null
null
src/Estudiante.java
SamuelColmenares/estructura-datos-multilistas
97e86b3473b0b709a73d60c0650df55bf84f0d71
[ "MIT" ]
null
null
null
src/Estudiante.java
SamuelColmenares/estructura-datos-multilistas
97e86b3473b0b709a73d60c0650df55bf84f0d71
[ "MIT" ]
null
null
null
21.65
67
0.625866
1,001,684
/** * Estudiante clase de nodo hijo. */ public class Estudiante { private String nombre; private String carnet; private int semestre; private Estudiante sigEstudiante; /** * Constructor de Estudiante con llenado de propiedades. * @param nombre Nombre del estudiante. * @param carnet Carnet del estudiante. * @param semestre Semestre del estudiante. */ public Estudiante(String nombre, String carnet, int semestre) { this.nombre = nombre; this.carnet=carnet; this.semestre=semestre; this.sigEstudiante=null; } public Estudiante() { this.sigEstudiante=null; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getCarnet() { return carnet; } public void setCarnet(String carnet) { this.carnet = carnet; } public int getSemestre() { return semestre; } public void setSemestre(int semestre) { this.semestre = semestre; } public Estudiante getSigEstudiante() { return sigEstudiante; } public void setSigEstudiante(Estudiante nuevoEstudiante) { this.sigEstudiante = nuevoEstudiante; } }
9240d62a17705eb3eb9114f3506c58a1dcd4bc2d
385
java
Java
src/test/java/team/easytravel/model/userprefs/UserPrefsTest.java
zenatrick/main
817a106dd169abd9a05af0385c08695ace5b3b29
[ "MIT" ]
2
2020-02-11T01:42:42.000Z
2020-02-19T06:53:23.000Z
src/test/java/team/easytravel/model/userprefs/UserPrefsTest.java
zenatrick/main
817a106dd169abd9a05af0385c08695ace5b3b29
[ "MIT" ]
201
2020-02-12T10:13:17.000Z
2020-04-20T02:18:56.000Z
src/test/java/team/easytravel/model/userprefs/UserPrefsTest.java
zenatrick/main
817a106dd169abd9a05af0385c08695ace5b3b29
[ "MIT" ]
16
2020-02-10T16:36:18.000Z
2020-11-05T16:34:10.000Z
25.666667
93
0.753247
1,001,685
package team.easytravel.model.userprefs; import org.junit.jupiter.api.Test; import team.easytravel.testutil.Assert; public class UserPrefsTest { @Test public void setGuiSettings_nullGuiSettings_throwsNullPointerException() { UserPrefs userPref = new UserPrefs(); Assert.assertThrows(NullPointerException.class, () -> userPref.setGuiSettings(null)); } }
9240d6645d95ca5211c59dc66251dd47e5e65e5c
11,300
java
Java
src/main/java/com/buisonje/AutoProxyMojo.java
volkertb/autoproxy-maven-plugin
118a4d86229f401e0bb1dacd8ed42dd18f54faf7
[ "Apache-2.0" ]
7
2016-06-02T12:57:31.000Z
2020-04-16T14:07:38.000Z
src/main/java/com/buisonje/AutoProxyMojo.java
volkertb/autoproxy-maven-plugin
118a4d86229f401e0bb1dacd8ed42dd18f54faf7
[ "Apache-2.0" ]
4
2015-03-19T14:50:55.000Z
2017-02-11T15:48:32.000Z
src/main/java/com/buisonje/AutoProxyMojo.java
volkertb/autoproxy-maven-plugin
118a4d86229f401e0bb1dacd8ed42dd18f54faf7
[ "Apache-2.0" ]
4
2015-06-15T16:39:32.000Z
2021-12-23T19:31:26.000Z
40.647482
142
0.636814
1,001,686
/* * Copyright 2014 Volkert de Buisonj&eacute; * * 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. * * NOTE: proxy-vole has a different license. See the license.txt file bundled * with the proxy-vole dependency in the bundled-repo folder. */ package com.buisonje; /* * Copyright 2001-2005 The Apache Software Foundation. * * 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. */ import java.net.InetSocketAddress; import java.net.Proxy; import java.net.Proxy.Type; import java.net.ProxySelector; import java.net.SocketAddress; import java.net.URI; import java.net.URISyntaxException; import java.util.Date; import java.util.List; import java.util.Map; import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.logging.Log; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.settings.Settings; import org.apache.maven.settings.TrackableBase; import com.github.markusbernhardt.proxy.ProxySearch; import com.github.markusbernhardt.proxy.util.Logger; /** * Goal which automatically detects and configures the current system proxy * server. * * @author Volkert de Buisonj&eacute; * */ @Mojo(name = "detectProxy", defaultPhase = LifecyclePhase.VALIDATE, aggregator = false) public class AutoProxyMojo extends AbstractMojo { private static final String BASIC_HTTP_URL_TO_TRY = "http://www.ams-ix.net"; private static final String PROXY_DETECTION_TIME_KEY = Date.class.getName(); private static final String PROXY_SELECTOR_KEY = ProxySelector.class .getName(); /** * The Maven Settings. */ @Parameter(defaultValue = "${settings}", readonly = false) private Settings settings; @Parameter(defaultValue = "${session}", readonly = true) private MavenSession session; Map<String, Object> sessionMap = null; @Override public void execute() throws MojoExecutionException { final Log mojoLog = getLog(); ProxySelector myProxySelector = null; if (isProxyDetectionAlreadyAttempted()) { mojoLog.info("Proxy server detection already attempted in this session. Reapplying result(s)..."); myProxySelector = (ProxySelector) session.getSystemProperties() .get(PROXY_SELECTOR_KEY); } else { showMavenProxySettings(mojoLog); // showCurrentSystemWideProxiesInfo(mojoLog); mojoLog.info("Autodetecting system proxy server(s)..."); myProxySelector = autodetectProxySettings(mojoLog); session.getSystemProperties().put(PROXY_DETECTION_TIME_KEY, new Date()); } if (myProxySelector == null) { mojoLog.warn("Could not detect proxy server(s) automatically. Falling back to the initial settings..."); } else { session.getSystemProperties().put(PROXY_SELECTOR_KEY, myProxySelector); /* * NOTE: It seems that Maven either ignores the system-wide * (default) {@link ProxySelector} entirely, or doesn't update it * with the initial proxy settings until it actually starts * downloading something. Either way, replacing the default {@link * ProxySelector} might therefore be pointless here. But it * shouldn't hurt, either. */ ProxySelector.setDefault(myProxySelector); mojoLog.info("Detected available proxy server(s) for HTTP connections:"); List<Proxy> detectedAvailableProxies = getAvailableProxies(myProxySelector); showAvailableProxies(mojoLog, detectedAvailableProxies); Proxy firstDetectedAvailableProxy = detectedAvailableProxies.get(0); mojoLog.info(String .format("Overriding Maven proxy settings with the first detected available proxy (%s)...", firstDetectedAvailableProxy.address().toString())); overrideMavenProxySettings(firstDetectedAvailableProxy, mojoLog); } } private boolean isProxyDetectionAlreadyAttempted() { return session.getSystemProperties().get(PROXY_DETECTION_TIME_KEY) != null; } /** * Override the Maven proxy settings with the first available (actual) * Proxy. * * @param overridingProxy * The {@link Proxy} to use instead of whatever is configured in * the initial Maven settings (settings.xml). */ private void overrideMavenProxySettings(Proxy overridingProxy, Log mojoLog) { org.apache.maven.settings.Proxy mavenProxy = settings.getActiveProxy(); if (mavenProxy == null) { /* * Create a new Maven proxy setting instance that will end up * containing the detected overriding proxy server configuration. */ mavenProxy = new org.apache.maven.settings.Proxy(); } if (mavenProxy.getSourceLevel() == null) { /* * User level should be enough for overriding the proxy for the * Maven goals/commands currently being executed. */ mavenProxy.setSourceLevel(TrackableBase.USER_LEVEL); } if (Proxy.NO_PROXY.equals(overridingProxy)) { mojoLog.info("The detected proxy configuration is a direct connection. Overriding active proxy configured in Maven settings..."); /* * There can be only one active proxy in the Maven settings at a * time, so if the currently active one is set to inactive, that * should imply a direct connection. */ mavenProxy.setActive(false); } else { final String nonProxyHosts = mavenProxy.getNonProxyHosts(); if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) { mojoLog.info("Non-proxy hosts appear to have been specified in settings.xml. Leaving those untouched."); } mavenProxy.setActive(true); mavenProxy.setProtocol(overridingProxy.type().name().toLowerCase()); SocketAddress overridingProxyAddress = overridingProxy.address(); if (overridingProxyAddress instanceof InetSocketAddress) { InetSocketAddress overridingInetSocketAddress = (InetSocketAddress) overridingProxyAddress; mavenProxy.setHost(overridingInetSocketAddress.getHostName()); mavenProxy.setPort(overridingInetSocketAddress.getPort()); } else { /* * Unlikely that the {@link SocketAddress} of the detected * {@link java.net.Proxy} would be anything other than its * subclass {@link InetSocketAddress}, but just in case, handle * it somehow: */ mavenProxy.setHost(overridingProxyAddress.toString()); mavenProxy.setPort(0); } } } /** * @param mojoLog * @return */ private ProxySelector autodetectProxySettings(final Log mojoLog) { // Let proxy-vole log to the Maven plugin logger. Logger.setBackend(new MojoLogBackEnd(mojoLog)); // Let Proxy Vole try to detect the system proxy settings automatically. ProxySearch proxySearch = ProxySearch.getDefaultProxySearch(); // Set the default proxy server as determined by Proxy Vole: ProxySelector myProxySelector = proxySearch.getProxySelector(); return myProxySelector; } /** * @param proxySelector * @return */ private List<Proxy> getAvailableProxies(ProxySelector proxySelector) { return proxySelector.select(getBasicHttpURIForProxySelection()); } /** * @param mojoLog * @param availableProxies */ private void showAvailableProxies(final Log mojoLog, List<Proxy> availableProxies) { for (int i = 0; i < availableProxies.size(); i++) { final Proxy proxy = availableProxies.get(i); mojoLog.info(String.format("Available proxy %d:", i + 1)); mojoLog.info(" * Proxy type: " + proxy.type().name()); String proxyAddress = proxy.type() == Type.DIRECT ? "n/a (Direct connection)" : proxy.address().toString(); mojoLog.info(" * Proxy address: " + proxyAddress); } } private void showMavenProxySettings(final Log mojoLog) { final org.apache.maven.settings.Proxy manuallyConfiguredActiveMavenProxy = settings .getActiveProxy(); if (manuallyConfiguredActiveMavenProxy != null) { mojoLog.info("Manually configured active proxy found in settings.xml. Details:"); mojoLog.info(" * Hostname: " + manuallyConfiguredActiveMavenProxy.getHost()); mojoLog.info(" * Port : " + manuallyConfiguredActiveMavenProxy.getPort()); mojoLog.info(" * Protocol: " + manuallyConfiguredActiveMavenProxy.getProtocol()); } else { mojoLog.info("No currently active proxy found in settings.xml."); } } private boolean isDirectConnection(List<Proxy> availableProxies) { return (availableProxies.size() == 1 && availableProxies.get(0).type() == Type.DIRECT); } private static final URI getBasicHttpURIForProxySelection() { URI validHttpUri; try { validHttpUri = new URI(BASIC_HTTP_URL_TO_TRY); } catch (URISyntaxException e) { throw new IllegalStateException("The String " + BASIC_HTTP_URL_TO_TRY + " is not considered a valid URI."); } return validHttpUri; } }
9240d684da755073ae8703d00eb1bc3aaf433acc
1,690
java
Java
src/main/java/fr/inra/maiage/bibliome/util/biotopes2012/AlvisAEAnnotation.java
Bibliome/bibliome-java-utils
f9b16d905f4e2c8c3758b9e8b8756900651ce0d4
[ "Apache-2.0" ]
1
2017-01-02T15:56:55.000Z
2017-01-02T15:56:55.000Z
src/main/java/fr/inra/maiage/bibliome/util/biotopes2012/AlvisAEAnnotation.java
Bibliome/bibliome-java-utils
f9b16d905f4e2c8c3758b9e8b8756900651ce0d4
[ "Apache-2.0" ]
29
2017-01-26T12:57:39.000Z
2022-01-13T09:26:53.000Z
src/main/java/fr/inra/maiage/bibliome/util/biotopes2012/AlvisAEAnnotation.java
Bibliome/bibliome-java-utils
f9b16d905f4e2c8c3758b9e8b8756900651ce0d4
[ "Apache-2.0" ]
1
2017-07-27T10:34:55.000Z
2017-07-27T10:34:55.000Z
28.166667
90
0.763905
1,001,687
/* Copyright 2016, 2017 Institut National de la Recherche Agronomique 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 fr.inra.maiage.bibliome.util.biotopes2012; import org.json.simple.JSONObject; public abstract class AlvisAEAnnotation { private final AlvisAEAnnotationSet annotationSet; private final String id; private final String type; private final AlvisAEProperties properties = new AlvisAEProperties(); protected AlvisAEAnnotation(AlvisAEAnnotationSet annotationSet, String id, String type) { super(); this.annotationSet = annotationSet; this.id = id; this.type = type; } protected AlvisAEAnnotation(AlvisAEAnnotationSet annotationSet, JSONObject json) { super(); this.annotationSet = annotationSet; this.id = (String) json.get("id"); this.type = (String) json.get("type"); this.properties.loadJSON((JSONObject) json.get("properties")); } public String getId() { return id; } public String getType() { return type; } public AlvisAEAnnotationSet getAnnotationSet() { return annotationSet; } public abstract <R,P> R accept(AlvisAEAnnotationVisitor<R,P> visitor, P param); public AlvisAEProperties getProperties() { return properties; } }
9240d6d4a57ed83ca2cc612709c05be50641a848
391
java
Java
7. Advanced-Loops-Exercises/src/p_09SumDigits.java
Tihomircho/Java-Practice
72989b80e856157d764e0fefe5e342ae544eb426
[ "MIT" ]
null
null
null
7. Advanced-Loops-Exercises/src/p_09SumDigits.java
Tihomircho/Java-Practice
72989b80e856157d764e0fefe5e342ae544eb426
[ "MIT" ]
null
null
null
7. Advanced-Loops-Exercises/src/p_09SumDigits.java
Tihomircho/Java-Practice
72989b80e856157d764e0fefe5e342ae544eb426
[ "MIT" ]
null
null
null
23
54
0.547315
1,001,688
import java.util.Scanner; public class p_09SumDigits { public static void main(String[] args) { Scanner console = new Scanner(System.in); int num= Integer.parseInt(console.nextLine()); int sum = 0; do { int lastDigit= num %10; sum+=lastDigit; num/=10; }while (num>0); System.out.println(sum); } }
9240d9307eb58f784508792d76cead857ec6379f
884
java
Java
src/main/java/com/bianlitransf/biz/service/IExchangeBillService.java
largeTree/bianlitransf
870a30a3b75bf9e875d8b2f02df561e7a0f2e728
[ "Apache-2.0" ]
null
null
null
src/main/java/com/bianlitransf/biz/service/IExchangeBillService.java
largeTree/bianlitransf
870a30a3b75bf9e875d8b2f02df561e7a0f2e728
[ "Apache-2.0" ]
null
null
null
src/main/java/com/bianlitransf/biz/service/IExchangeBillService.java
largeTree/bianlitransf
870a30a3b75bf9e875d8b2f02df561e7a0f2e728
[ "Apache-2.0" ]
3
2019-02-17T13:56:39.000Z
2019-03-12T16:09:34.000Z
19.644444
105
0.719457
1,001,689
package com.bianlitransf.biz.service; import java.math.BigDecimal; import java.util.Map; import com.bianlitransf.biz.dao.ExchangeBillDao; import com.bianlitransf.biz.entity.ExchangeBill; import com.qiuxs.cuteframework.core.persistent.database.service.ifc.IDataPropertyService; public interface IExchangeBillService extends IDataPropertyService<Long, ExchangeBill, ExchangeBillDao> { /** * 保存兑换单 * @author qiuxs * * @param params * @param exchangeBill * * 创建时间:2018年8月29日 下午8:14:58 */ public void saveBill(Map<String, String> params, ExchangeBill exchangeBill); /** * 汇总当前用户的兑换单 * @author qiuxs * * @return * * 创建时间:2018年9月3日 下午8:50:49 */ public Map<String, Object> summaryExgBills(); /** * 合计已兑换积分 * @author qiuxs * * @param ownerId * @return * * 创建时间:2018年9月6日 下午10:27:21 */ public BigDecimal summaryScore(Long ownerId); }
9240da72aca167ed5eddebdcad1ef38a01b26ce0
1,535
java
Java
src/main/java/com/couchbase/client/dcp/message/DataType.java
couchbase/java-dcp-client
692da2ea4175f796a1011050aeadf37a93705e8a
[ "Apache-2.0" ]
29
2017-08-15T08:54:27.000Z
2021-09-03T16:10:57.000Z
src/main/java/com/couchbase/client/dcp/message/DataType.java
couchbase/java-dcp-client
692da2ea4175f796a1011050aeadf37a93705e8a
[ "Apache-2.0" ]
6
2017-12-18T16:51:57.000Z
2021-04-26T20:17:08.000Z
src/main/java/com/couchbase/client/dcp/message/DataType.java
couchbase/java-dcp-client
692da2ea4175f796a1011050aeadf37a93705e8a
[ "Apache-2.0" ]
10
2017-12-18T16:11:15.000Z
2022-02-24T11:24:18.000Z
26.016949
89
0.709446
1,001,690
/* * Copyright 2020 Couchbase, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.couchbase.client.dcp.message; import java.util.Arrays; import java.util.EnumSet; import java.util.List; import static java.util.Collections.unmodifiableList; /** * https://github.com/couchbase/kv_engine/blob/master/docs/BinaryProtocol.md#data-types */ public enum DataType { JSON(0x01), SNAPPY(0x02), XATTR(0x04); private final int bitmask; private static final List<DataType> values = unmodifiableList(Arrays.asList(values())); DataType(int bitmask) { this.bitmask = bitmask; } public int bitmask() { return bitmask; } public static EnumSet<DataType> parse(int bitfield) { EnumSet<DataType> result = EnumSet.noneOf(DataType.class); for (DataType type : values) { if (contains(bitfield, type)) { result.add(type); } } return result; } public static boolean contains(int bitfield, DataType type) { return (bitfield & type.bitmask()) != 0; } }
9240daa0c425fc4d158957c6cbf5ed03fc1e4278
6,049
java
Java
uhc-custom-craft/src/main/java/gg/eris/uhc/customcraft/command/StatsCommand.java
erisgg/uhc
149fe0ba601dfc2eed1b7371208e2637d08c04cd
[ "MIT" ]
null
null
null
uhc-custom-craft/src/main/java/gg/eris/uhc/customcraft/command/StatsCommand.java
erisgg/uhc
149fe0ba601dfc2eed1b7371208e2637d08c04cd
[ "MIT" ]
null
null
null
uhc-custom-craft/src/main/java/gg/eris/uhc/customcraft/command/StatsCommand.java
erisgg/uhc
149fe0ba601dfc2eed1b7371208e2637d08c04cd
[ "MIT" ]
null
null
null
34.565714
99
0.575632
1,001,691
package gg.eris.uhc.customcraft.command; import com.fasterxml.jackson.databind.JsonNode; import gg.eris.commons.bukkit.command.Command.Builder; import gg.eris.commons.bukkit.command.CommandManager; import gg.eris.commons.bukkit.command.CommandProvider; import gg.eris.commons.bukkit.command.argument.StringArgument; import gg.eris.commons.bukkit.player.ErisPlayerManager; import gg.eris.commons.bukkit.text.CenteredChatData; import gg.eris.commons.bukkit.text.TextController; import gg.eris.commons.bukkit.text.TextType; import gg.eris.commons.bukkit.util.CC; import gg.eris.commons.core.util.Text; import gg.eris.uhc.core.UhcPlugin; import gg.eris.uhc.customcraft.CustomCraftUhcIdentifiers; import gg.eris.uhc.customcraft.game.player.CustomCraftUhcPlayer; import java.util.UUID; import lombok.RequiredArgsConstructor; import org.apache.commons.lang3.StringUtils; import org.bukkit.Bukkit; @RequiredArgsConstructor public final class StatsCommand implements CommandProvider { public static final String STRIKE = CC.GOLD.bold().strikethrough() + StringUtils.repeat("-", 45) + CC.RESET; private final UhcPlugin plugin; private final ErisPlayerManager erisPlayerManager; @Override public Builder getCommand(CommandManager manager) { return manager.newCommandBuilder( "stats", "shows stats", "stats [player]", CustomCraftUhcIdentifiers.STATS_PERMISSION, "statsf" ).noArgsHandler(context -> { CustomCraftUhcPlayer player = this.erisPlayerManager.getPlayer(context.getSenderAsPlayer()); int kills = player.getKills(); int deaths = player.getDeaths(); int wins = player.getWins(); int gamesPlayed = player.getGamesPlayed(); int coins = player.getCoins(); double kd; if (kills == 0) { kd = 0; } else { kd = kills / Math.max(1.0, deaths); } double winLoss = wins / Math.max(1.0, gamesPlayed); player.getHandle().sendMessage(getMessage( player.getName(), kills, deaths, wins, gamesPlayed, coins, kd, winLoss) ); }, true).withSubCommand() .asPlayerOnly() .argument(StringArgument.of("target")) .handler(context -> { String target = context.getArgument("target"); TextController.send( context.getSenderAsPlayer(), TextType.INFORMATION, "Looking up stats for <h>{0}</h>.", target ); Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> { UUID uuid = this.erisPlayerManager.getOfflineDataManager().getUuid(target); if (uuid == null) { TextController.send( context.getSenderAsPlayer(), TextType.ERROR, "Could not find player <h>{0}</h>.", target ); return; } // TODO: Have a custom craft data class and move all data into there, so can serialize // into a node without an ErisPlayer reference JsonNode node = this.erisPlayerManager.getOfflineDataManager().getRaw(uuid); String name = node.get("name").asText(); int coins = 0; int gamesPlayed = 0; int wins = 0; int kills = 0; int deaths = 0; if (node.has("games")) { JsonNode games = node.get("games"); if (games.has(CustomCraftUhcIdentifiers.JSON_KEY)) { JsonNode customCraft = games.get(CustomCraftUhcIdentifiers.JSON_KEY); if (customCraft.has("coins")) { coins = customCraft.get("coins").asInt(); } if (customCraft.has("games_played")) { gamesPlayed = customCraft.get("games_played").asInt(); } if (customCraft.has("wins")) { wins = customCraft.get("wins").asInt(); } if (customCraft.has("kills")) { kills = customCraft.get("kills").asInt(); } if (customCraft.has("deaths")) { deaths = customCraft.get("deaths").asInt(); } } } double kd; if (kills == 0) { kd = 0; } else { kd = kills / Math.max(1.0, deaths); } double winLoss = wins / Math.max(1.0, gamesPlayed); String message = getMessage( name, kills, deaths, wins, gamesPlayed, coins, kd, winLoss ); Bukkit.getScheduler() .runTask(this.plugin, () -> context.getCommandSender().sendMessage(message)); }); }).finished(); } private String getMessage(String name, int kills, int deaths, int wins, int gamesPlayed, int coins, double kd, double winLoss) { return STRIKE + "\n" + CenteredChatData.getCentredMessage("&e&l" + name + "'s Stats") + "\n" + CC.RESET + CenteredChatData.getCentredMessage("&6Kills: &e" + Text.formatInt(kills)) + "\n" + CC.RESET + CenteredChatData.getCentredMessage("&6Deaths: &e" + Text.formatInt(deaths)) + "\n" + CC.RESET + CenteredChatData.getCentredMessage("&6K/D Ratio: &e" + Text.formatDouble(kd)) + "\n" + CC.RESET + CenteredChatData.getCentredMessage("&6Games Played: &e" + Text.formatInt(gamesPlayed)) + "\n" + CC.RESET + CenteredChatData.getCentredMessage("&6Wins: &e" + Text.formatInt(wins)) + "\n" + CC.RESET + CenteredChatData.getCentredMessage("&6Win/Loss Ratio: &e" + Text.formatDouble(winLoss)) + "\n" + CC.RESET + CenteredChatData.getCentredMessage("&6Coins: &e" + Text.formatInt(coins)) + CC.RESET + "\n" + STRIKE; } }
9240dae547702455d713cdd9b4cc98519a1daf0e
3,362
java
Java
YiLian/src/main/java/com/yilian/mall/entity/MerchInfo.java
LJW123/YiLianMall
ea335a66cb4fd6417aa264a959847b094c90fb04
[ "MIT" ]
null
null
null
YiLian/src/main/java/com/yilian/mall/entity/MerchInfo.java
LJW123/YiLianMall
ea335a66cb4fd6417aa264a959847b094c90fb04
[ "MIT" ]
null
null
null
YiLian/src/main/java/com/yilian/mall/entity/MerchInfo.java
LJW123/YiLianMall
ea335a66cb4fd6417aa264a959847b094c90fb04
[ "MIT" ]
null
null
null
14.745614
50
0.667757
1,001,692
package com.yilian.mall.entity; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; public class MerchInfo { /** * 商家唯一id */ @SerializedName("merchant_id") public String merchantId; @SerializedName("merchant_type") public int merchantType; /** * 商家名字标题 */ @SerializedName("merchant_name") public String merchantName; /** * 商家评分10-50之间,代表1-5颗星 */ @SerializedName("graded") public String graded; // /** * 省 */ @SerializedName("merchant_province") public String merchantProvince; /** * 市 */ @SerializedName("merchant_city") public String merchantCity; /** * 县 */ @SerializedName("merchant_county") public String merchantCounty; //县 /** * 商家地址 */ @SerializedName("merchant_address") public String merchantAddress; /** * 商家地理位置经度 */ @SerializedName("merchant_longitude") public String merchantLongitude; /** * 商家地理位置纬度 */ @SerializedName("merchant_latitude") public String merchantLatitude; /** * 商家所属的二级行业 */ @SerializedName("merchant_industry") public String merchantIndustry; /** * 商家所属的顶级行业 */ @SerializedName("merchant_industry_parent") public String merchantIndustryParent; /** * 经营范围 */ @SerializedName("merchant_scope") public String merchantScope; /** * 特色简介 */ @SerializedName("merchant_desp") public String merchantDesp; /** * 营业时间 */ @SerializedName("merchant_worktime") public String merchantWorktime; /** * 注册时间 */ @SerializedName("merchant_regtime") public String merchantRegtime; /** * 商家环境图片 */ public ArrayList<FilialeCodeImage> images; /** * 商家送奖券比例,取值范围10-100,代表百分比 */ @SerializedName("merchant_percent") public String merchantPercent; /** * 商家固定电话号码 */ @SerializedName("merchant_tel") public String merchantTel; /** * 兑换中心分店唯一ID */ @SerializedName("shop_index") public String shopIndex; /** * 兑换中心唯一ID */ @SerializedName("shop_filiale_id") public String shopFilialeId; /** * 兑换中心门店标题 */ @SerializedName("shop_name") public String shopName; /** * 省 */ @SerializedName("shop_province") public String shopProvince; /** * 市 */ @SerializedName("shop_city") public String shopCity; /** * 县 */ @SerializedName("shop_county") public String shopCounty; /** * 兑换中心门店地址 */ @SerializedName("shop_address") public String shopAddress; /** * 兑换中心门店地理位置经度 */ @SerializedName("shop_longitude") public String shopLongitude; /** * 兑换中心门店地理位置纬度 */ @SerializedName("shop_latitude") public String shopLatitude; /** * 联系电话 */ @SerializedName("shop_tel") public String shopTel; /** * 兑换中心门店简介 */ @SerializedName("shop_desp") public String shopDesp; /** * //0分店,1总店 */ @SerializedName("shop_type") public String shopType; //0分店,1总店 /** * 营业时间 */ @SerializedName("shop_worktime") public String shopWorktime; /** * 是否支持乐币支付,0表示不支持,大于0表示支持 */ @SerializedName("merchant_lebi_percent") public int merchantLebiPercent; /** * 点赞数量 */ @SerializedName("praise_count") public String praiseCount; /** * 累计消费人次 */ @SerializedName("deal_count") public String dealCount; /** * 累计赠送数量 */ @SerializedName("send_lefen_count") public String sendLefenCount; /** * 人气 */ @SerializedName("renqi") public String renqi; }
9240db02193a3b5ce29668919937ecbdb41468d5
16,199
java
Java
cs-amazon/src/main/java/io/cloudslang/content/amazon/entities/constants/Inputs.java
tethryus/cs-actions
8c8796d6381d8378c3ce528f308dac0808a5f0ce
[ "Apache-2.0" ]
null
null
null
cs-amazon/src/main/java/io/cloudslang/content/amazon/entities/constants/Inputs.java
tethryus/cs-actions
8c8796d6381d8378c3ce528f308dac0808a5f0ce
[ "Apache-2.0" ]
null
null
null
cs-amazon/src/main/java/io/cloudslang/content/amazon/entities/constants/Inputs.java
tethryus/cs-actions
8c8796d6381d8378c3ce528f308dac0808a5f0ce
[ "Apache-2.0" ]
null
null
null
62.786822
126
0.732514
1,001,693
/******************************************************************************* * (c) Copyright 2017 Hewlett-Packard Development Company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 * *******************************************************************************/ package io.cloudslang.content.amazon.entities.constants; /** * Created by Mihai Tusa. * 2/17/2016. */ public class Inputs { private Inputs() { // prevent instantiation } public static class CommonInputs { public static final String CREDENTIAL = "credential"; public static final String DELIMITER = "delimiter"; public static final String ENDPOINT = "endpoint"; public static final String HEADERS = "headers"; public static final String IDENTITY = "identity"; public static final String PROXY_HOST = "proxyHost"; public static final String PROXY_PASSWORD = "proxyPassword"; public static final String PROXY_PORT = "proxyPort"; public static final String PROXY_USERNAME = "proxyUsername"; public static final String PREFIX = "prefix"; public static final String QUERY_PARAMS = "queryParams"; public static final String VERSION = "version"; } public static class CustomInputs { public static final String ALLOCATION_ID = "allocationId"; public static final String AMAZON_API = "amazonApi"; public static final String ARCHITECTURE = "architecture"; public static final String ASSOCIATION_ID = "associationId"; public static final String ATTACHMENT_ID = "attachmentId"; public static final String AVAILABILITY_ZONE = "availabilityZone"; public static final String BLOCK_DEVICE_MAPPING_SNAPSHOT_ID = "blockDeviceMappingSnapshotId"; public static final String BLOCK_MAPPING_DEVICE_NAME = "blockMappingDeviceName"; public static final String DATE = "date"; public static final String DELETE_ON_TERMINATION = "deleteOnTermination"; public static final String DOMAIN = "domain"; public static final String HOST_ID = "hostId"; public static final String HTTP_VERB = "httpVerb"; public static final String HYPERVISOR = "hypervisor"; public static final String IDENTITY_ID = "identityId"; public static final String IMAGE_ID = "imageId"; public static final String INSTANCE_ID = "instanceId"; public static final String INSTANCE_TYPE = "instanceType"; public static final String KEY_FILTERS_STRING = "keyFiltersString"; public static final String KERNEL_ID = "kernelId"; public static final String KEY_TAGS_STRING = "keyTagsString"; public static final String KMS_KEY_ID = "kmsKeyId"; public static final String OWNER_ALIAS = " ownerAlias "; public static final String OWNER_ID = "ownerId"; public static final String PAYLOAD_HASH = "payloadHash"; public static final String PLATFORM = "platform"; public static final String PRODUCT_CODE = "productCode"; public static final String PRODUCT_CODE_TYPE = "productCodeType"; public static final String RAMDISK_ID = "ramdiskId"; public static final String REGIONS_STRING = "regionsString"; public static final String RESOURCE_IDS_STRING = "resourceIdsString"; public static final String ROOT_DEVICE_NAME = "rootDeviceName"; public static final String ROOT_DEVICE_TYPE = "rootDeviceType"; public static final String STATE_REASON_CODE = "stateReasonCode"; public static final String STATE_REASON_MESSAGE = "stateReasonMessage"; public static final String SUBNET_ID = "subnetId"; public static final String URI = "uri"; public static final String VALUE_FILTERS_STRING = "valueFiltersString"; public static final String VALUE_TAGS_STRING = "valueTagsString"; public static final String VIRTUALIZATION_TYPE = "virtualizationType"; public static final String VOLUME_ID = "volumeId"; public static final String VOLUME_SIZE = "volumeSize"; public static final String VOLUME_TYPE = "volumeType"; public static final String VPC_ID = "vpcId"; public static final String ZONE_NAMES_STRING = "zoneNamesString"; } public static class ElasticIpInputs { public static final String ALLOW_REASSOCIATION = "allowReassociation"; public static final String PUBLIC_IP = "publicIp"; public static final String PRIVATE_IP_ADDRESS = "privateIpAddress"; public static final String PRIVATE_IP_ADDRESSES_STRING = "privateIpAddressesString"; } public static class EbsInputs { public static final String EBS_OPTIMIZED = "ebsOptimized"; public static final String BLOCK_DEVICE_MAPPING_DEVICE_NAMES_STRING = "blockDeviceMappingDeviceNamesString"; public static final String BLOCK_DEVICE_MAPPING_VIRTUAL_NAMES_STRING = "blockDeviceMappingVirtualNamesString"; public static final String DELETE_ON_TERMINATIONS_STRING = "deleteOnTerminationsString"; public static final String ENCRYPTED_STRING = "encryptedString"; public static final String NO_DEVICES_STRING = "noDevicesString"; public static final String IOPS_STRING = "iopsString"; public static final String SNAPSHOT_IDS_STRING = "snapshotIdsString"; public static final String VOLUME_IDS_STRING = "volumeIdsString"; public static final String VOLUME_SIZES_STRING = "volumeSizesString"; public static final String VOLUME_TYPES_STRING = "volumeTypesString"; } public static class IamInputs { public static final String IAM_INSTANCE_PROFILE_ARN = "iamInstanceProfileArn"; public static final String IAM_INSTANCE_PROFILE_NAME = "iamInstanceProfileName"; public static final String KEY_PAIR_NAME = "keyPairName"; public static final String SECURITY_GROUP_IDS_STRING = "securityGroupIdsString"; public static final String SECURITY_GROUP_NAMES_STRING = "networkInterfaceGroupNamesString"; public static final String SECURITY_TOKEN = "securityToken"; } public static class ImageInputs { public static final String IDS_STRING = "idsString"; public static final String IMAGE_DESCRIPTION = "description"; public static final String IS_PUBLIC = "isPublic"; public static final String MANIFEST_LOCATION = "manifestLocation"; public static final String NAME = "name"; public static final String NO_REBOOT = "noReboot"; public static final String OWNERS_STRING = "ownersString"; public static final String STATE = "state"; public static final String TYPE = "type"; public static final String USER_GROUPS_STRING = "userGroupsString"; public static final String USER_IDS_STRING = "userIdsString"; } public static class InstanceInputs { public static final String AFFINITY = "affinity"; public static final String ATTRIBUTE = "attribute"; public static final String ATTRIBUTE_VALUE = "attributeValue"; public static final String CLIENT_TOKEN = "clientToken"; public static final String ENA_SUPPORT = "enaSupport"; public static final String FILTER_NAMES_STRING = "filterNamesString"; public static final String FILTER_VALUES_STRING = "filterValuesString"; public static final String FORCE_STOP = "forceStop"; public static final String INSTANCE_IDS_STRING = "instanceIdsString"; public static final String LOWER_CASE_INSTANCE_INITIATED_SHUTDOWN_BEHAVIOR = "instanceInitiatedShutdownBehavior"; public static final String LOWER_CASE_DISABLE_API_TERMINATION = "disableApiTermination"; public static final String LOWER_CASE_KERNEL = "kernel"; public static final String LOWER_CASE_RAMDISK = "ramdisk"; public static final String LOWER_CASE_USER_DATA = "userData"; public static final String MAX_COUNT = "maxCount"; public static final String MAX_RESULTS = "maxResults"; public static final String MIN_COUNT = "minCount"; public static final String MONITORING = "monitoring"; public static final String NEXT_TOKEN = "nextToken"; public static final String PLACEMENT_GROUP_NAME = "placementGroupName"; public static final String SOURCE_DESTINATION_CHECK = "sourceDestinationCheck"; public static final String SRIOV_NET_SUPPORT = "sriovNetSupport"; public static final String TENANCY = "tenancy"; } public static class LoadBalancerInputs { public static final String ARNS_STRING = "arnsString"; public static final String LOAD_BALANCER_ARN = "loadBalancerArn"; public static final String LOAD_BALANCER_NAME = "loadBalancerName"; public static final String MARKER = "marker"; public static final String MEMBER_NAMES_STRING = "memberNamesString"; public static final String PAGE_SIZE = "pageSize"; public static final String SCHEME = "schema"; } public static class NetworkInputs { public static final String AMAZON_PROVIDED_IPV6_CIDR_BLOCK = "amazonProvidedIpv6CidrBlock"; public static final String CIDR_BLOCK = "cidrBlock"; public static final String DEVICE_INDEX = "deviceIndex"; public static final String FORCE_DETACH = "forceDetach"; public static final String NETWORK_INTERFACE_DELETE_ON_TERMINATION = "networkInterfaceDeleteOnTermination"; public static final String NETWORK_INTERFACE_DESCRIPTION = "networkInterfaceDescription"; public static final String NETWORK_INTERFACE_DEVICE_INDEX = "networkInterfaceDeviceIndex"; public static final String NETWORK_INTERFACE_ID = "networkInterfaceId"; public static final String NETWORK_INTERFACE_ASSOCIATE_PUBLIC_IP_ADDRESS = "networkInterfaceAssociatePublicIpAddress"; public static final String SECONDARY_PRIVATE_IP_ADDRESS_COUNT = "secondaryPrivateIpAddressCount"; public static final String SUBNET_IDS_STRING = "subnetIdsString"; public static final String FILTER_ADDRESSES_PRIVATE_IP_ADDRESS = "filterAddressesPrivateIpAddress"; public static final String FILTER_ADDRESSES_PRIMARY = "filterAddressesPrimary"; public static final String FILTER_ADDRESSES_ASSOCIATION_PUBLIC_IP = "filterAddressesAssociationPublicIp"; public static final String FILTER_ADDRESSES_ASSOCIATION_OWNER_ID = "filterAddressesAssociationOwnerId"; public static final String FILTER_ASSOCIATION_ASSOCIATION_ID = "filterAssociationAssociationId"; public static final String FILTER_ASSOCIATION_ALLOCATION_ID = "filterAssociationAllocationId"; public static final String FILTER_ASSOCIATION_IP_OWNER_ID = "filterAssociationIpOwnerId"; public static final String FILTER_ASSOCIATION_PUBLIC_IP = "filterAssociationPublicIp"; public static final String FILTER_ASSOCIATION_PUBLIC_DNS_NAME = "filterAssociationPublicDnsName"; public static final String FILTER_ATTACHMENT_ATTACHMENT_ID = "filterAttachmentAttachmentId"; public static final String FILTER_ATTACHMENT_ATTACH_TIME = "filterAttachmentAttachTime"; public static final String FILTER_ATTACHMENT_DELETE_ON_TERMINATION = "filterAttachmentDeleteOnTermination"; public static final String FILTER_ATTACHMENT_DEVICE_INDEX = "filterAttachmentDeviceIndex"; public static final String FILTER_ATTACHMENT_INSTANCE_ID = "filterAttachmentInstanceId"; public static final String FILTER_ATTACHMENT_INSTANCE_OWNER_ID = "filterAttachmentInstanceOwnerId"; public static final String FILTER_ATTACHMENT_NAT_GATEWAY_ID = "filterAttachmentNatGatewayId"; public static final String FILTER_ATTACHMENT_STATUS = "filterAttachmentStatus"; public static final String FILTER_AVAILABILITY_ZONE = "filterAvailabilityZone"; public static final String FILTER_DESCRIPTION = "filterDescription"; public static final String FILTER_GROUP_ID = "filterGroupId"; public static final String FILTER_GROUP_NAME = "filterGroupName"; public static final String FILTER_IPV6_ADDRESSES_IPV6_ADDRESS = "filterIpv6AddressesIpv6Address"; public static final String FILTER_MAC_ADDRESS = "filterMacAddress"; public static final String FILTER_NETWORK_INTERFACE_ID = "filterNetworkInterfaceId"; public static final String FILTER_OWNER_ID = "filterOwnerId"; public static final String FILTER_PRIVATE_IP_ADDRESS = "filterPrivateIpAddress"; public static final String FILTER_PRIVATE_DNS_NAME = "filterPrivateDnsName"; public static final String FILTER_REQUESTER_ID = "filterRequesterId"; public static final String FILTER_REQUESTER_MANAGED = "filterRequesterManaged"; public static final String FILTER_SOURCE_DEST_CHECK = "filterSourceDestCheck"; public static final String FILTER_STATUS = "filterStatus"; public static final String FILTER_SUBNET_ID = "filterSubnetId"; public static final String FILTER_TAG = "filterTag"; public static final String FILTER_TAG_KEY = "filterTagKey"; public static final String FILTER_TAG_VALUE = "filterTagValue"; public static final String FILTER_VPC_ID = "filterVpcId"; } public static class StorageInputs { public static final String BUCKET_NAME = "bucketName"; public static final String CONTINUATION_TOKEN = "continuationToken"; public static final String ENCODING_TYPE = "encodingType"; public static final String FETCH_OWNER = "fetchOwner"; public static final String MAX_KEYS = "maxKeys"; public static final String PREFIX = "prefix"; public static final String START_AFTER = "startAfter"; } public static class VolumeInputs { public static final String DEVICE_NAME = "deviceName"; public static final String ENCRYPTED = "encrypted"; public static final String FORCE = "force"; public static final String IOPS = "iops"; public static final String SIZE = "size"; public static final String SNAPSHOT_DESCRIPTION = "snapshotDescription"; public static final String SNAPSHOT_ID = "snapshotId"; public static final String VOLUME_IDS_STRING = "volumeIdsString"; public static final String FILTER_ATTACHMENT_ATTACH_TIME = "filterAttachmentAttachTime"; public static final String FILTER_ATTACHMENT_DELETE_ON_TERMINATION = "filterAttachmentDeleteOnTermination"; public static final String FILTER_ATTACHMENT_DEVICE = "filterAttachmentDevice"; public static final String FILTER_ATTACHMENT_INSTANCE_ID = "filterAttachmentInstanceId"; public static final String FILTER_ATTACHMENT_STATUS = "filterAttachmentStatus"; public static final String FILTER_AVAILABILITY_ZONE = "filterAvailabilityZone"; public static final String FILTER_CREATE_TIME = "filterCreateTime"; public static final String FILTER_ENCRYPTED = "filterEncrypted"; public static final String FILTER_SIZE = "filterSize"; public static final String FILTER_SNAPSHOT_ID = "filterSnapshotId"; public static final String FILTER_STATUS = "filterStatus"; public static final String FILTER_TAG = "filterTag"; public static final String FILTER_TAG_KEY = "filterTagKey"; public static final String FILTER_TAG_VALUE = "filterTagValue"; public static final String FILTER_VOLUME_ID = "filterVolumeId"; public static final String FILTER_VOLUME_TYPE = "filterVolumeType"; } public static class TagsInputs { public static final String FILTER_KEY = "filterKey"; public static final String FILTER_RESOURCE_ID = "filterResourceId"; public static final String FILTER_RESOURCE_TYPE = "filterResourceType"; public static final String FILTER_VALUE = "filterValue"; } }
9240dbd785de120c6726d95e8f55c9757cd6cf7f
774
java
Java
litho-core/src/main/java/com/facebook/litho/HookInitializer.java
conca/litho
26061bae949dbae11f3a9c4a5282356b843b0609
[ "Apache-2.0" ]
7,886
2017-04-18T19:27:19.000Z
2022-03-29T13:18:19.000Z
litho-core/src/main/java/com/facebook/litho/HookInitializer.java
conca/litho
26061bae949dbae11f3a9c4a5282356b843b0609
[ "Apache-2.0" ]
667
2017-04-18T20:43:18.000Z
2022-03-28T15:21:43.000Z
litho-core/src/main/java/com/facebook/litho/HookInitializer.java
conca/litho
26061bae949dbae11f3a9c4a5282356b843b0609
[ "Apache-2.0" ]
824
2017-04-18T19:56:51.000Z
2022-03-25T07:17:34.000Z
32.25
75
0.731266
1,001,694
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.litho; /** Interface for a block of code that will initialize a hook value. */ public interface HookInitializer<T> { T init(); }
9240dbf0f5db2c64799e23837c99bffe36d528f5
490
java
Java
sql/core/target/java/org/apache/spark/sql/execution/ui/SparkListenerSQLExecutionEnd$.java
Y-sir/spark-cn
06a0459999131ee14864a69a15746c900e815a14
[ "BSD-2-Clause", "Apache-2.0", "CC0-1.0", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
sql/core/target/java/org/apache/spark/sql/execution/ui/SparkListenerSQLExecutionEnd$.java
Y-sir/spark-cn
06a0459999131ee14864a69a15746c900e815a14
[ "BSD-2-Clause", "Apache-2.0", "CC0-1.0", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
sql/core/target/java/org/apache/spark/sql/execution/ui/SparkListenerSQLExecutionEnd$.java
Y-sir/spark-cn
06a0459999131ee14864a69a15746c900e815a14
[ "BSD-2-Clause", "Apache-2.0", "CC0-1.0", "MIT", "MIT-0", "ECL-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
54.444444
215
0.791837
1,001,695
package org.apache.spark.sql.execution.ui; public class SparkListenerSQLExecutionEnd$ extends scala.runtime.AbstractFunction2<java.lang.Object, java.lang.Object, org.apache.spark.sql.execution.ui.SparkListenerSQLExecutionEnd> implements scala.Serializable { /** * Static reference to the singleton instance of this Scala object. */ public static final SparkListenerSQLExecutionEnd$ MODULE$ = null; public SparkListenerSQLExecutionEnd$ () { throw new RuntimeException(); } }
9240dda89b04cdb98badfd75df0a6fd511505eae
1,369
java
Java
org/apache/xmlgraphics/image/loader/impl/ImageLoaderRaw.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
1
2022-02-24T01:32:41.000Z
2022-02-24T01:32:41.000Z
org/apache/xmlgraphics/image/loader/impl/ImageLoaderRaw.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
null
null
null
org/apache/xmlgraphics/image/loader/impl/ImageLoaderRaw.java
JaneMandy/CS
4a95148cbeb3804b9c50da003d1a7cb12254cb58
[ "Apache-2.0" ]
null
null
null
38.027778
118
0.7626
1,001,696
package org.apache.xmlgraphics.image.loader.impl; import java.io.IOException; import java.util.Map; import javax.xml.transform.Source; import org.apache.xmlgraphics.image.loader.Image; import org.apache.xmlgraphics.image.loader.ImageException; import org.apache.xmlgraphics.image.loader.ImageFlavor; import org.apache.xmlgraphics.image.loader.ImageInfo; import org.apache.xmlgraphics.image.loader.ImageSessionContext; import org.apache.xmlgraphics.image.loader.util.ImageUtil; public class ImageLoaderRaw extends AbstractImageLoader { private String mime; private ImageFlavor targetFlavor; public ImageLoaderRaw(ImageFlavor targetFlavor) { this.targetFlavor = targetFlavor; this.mime = ImageLoaderFactoryRaw.getMimeForRawFlavor(targetFlavor); } public ImageFlavor getTargetFlavor() { return this.targetFlavor; } public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!this.mime.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from a image with MIME type: " + this.mime); } else { Source src = session.needSource(info.getOriginalURI()); ImageRawStream rawImage = new ImageRawStream(info, this.getTargetFlavor(), ImageUtil.needInputStream(src)); return rawImage; } } }
9240df046b05ab5030f7dfc20ad27ac1565f5ca3
2,510
java
Java
common/src/main/java/com/shcem/logback/LogbackConfigLoader.java
judypol/jshcem
18e1bc2c6b77504714aa1afe14df9a53efae6337
[ "MIT" ]
null
null
null
common/src/main/java/com/shcem/logback/LogbackConfigLoader.java
judypol/jshcem
18e1bc2c6b77504714aa1afe14df9a53efae6337
[ "MIT" ]
null
null
null
common/src/main/java/com/shcem/logback/LogbackConfigLoader.java
judypol/jshcem
18e1bc2c6b77504714aa1afe14df9a53efae6337
[ "MIT" ]
null
null
null
35.857143
118
0.630677
1,001,697
/* ======================================== * System Name  :化交线上平台 * SubSystem Name :化交站点核心工具集 * File Name: Constants * ---------------------------------------- * Create Date/Change History * ---------------------------------------- * 2017/9/5  lizhihua Create * * * ---------------------------------------- * Copyright (c) SCEM . All rights reserved. */ package com.shcem.logback; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import com.shcem.common.YamlConfiguration; import com.shcem.utils.FileUtils; import com.shcem.utils.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.LoggerContext; import org.springframework.util.ResourceUtils; import java.io.File; import java.io.IOException; /** * logback 读取外部系统的xml配置 * @author lizhihua * @version 1.0 */ public class LogbackConfigLoader { private static Logger logger=LoggerFactory.getLogger(LogbackConfigLoader.class); public static void load () throws IOException, JoranException { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(lc); lc.reset(); /** * 优先读yaml文件的logback配置,如果不存在则读ClassPath路径下的配置。 * */ String externalConfigFileLocation= YamlConfiguration.instance().getString("logback"); if(StringUtils.isEmpty(externalConfigFileLocation)){ //如果没有配置,则直接返回 File logbackFile=ResourceUtils.getFile("classpath:/logback.xml"); configurator.doConfigure(logbackFile); return; } logger.info("logback xml is "+externalConfigFileLocation); File externalConfigFile = new File(externalConfigFileLocation); if(!externalConfigFile.exists()){ throw new IOException("Logback External Config File is not exists in "+externalConfigFileLocation); }else{ if(!externalConfigFile.isFile()){ throw new IOException("Logback External Config File Parameter exists, but does not reference a file"); }else{ if(!externalConfigFile.canRead()){ throw new IOException("Logback External Config File exists and is a file, but cannot be read."); }else{ configurator.doConfigure(externalConfigFileLocation); } } } } }
9240df49c216660e920d097620d08a23b387d28b
7,550
java
Java
app/src/main/java/com/mercy/alpacalive/EventListing.java
ecyzhi/RTSP_Webcasting
106b8de5a07813adb8d77adc597efedc7a99a02f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/mercy/alpacalive/EventListing.java
ecyzhi/RTSP_Webcasting
106b8de5a07813adb8d77adc597efedc7a99a02f
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/mercy/alpacalive/EventListing.java
ecyzhi/RTSP_Webcasting
106b8de5a07813adb8d77adc597efedc7a99a02f
[ "Apache-2.0" ]
null
null
null
38.131313
126
0.609801
1,001,698
package com.mercy.alpacalive; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import com.google.android.material.floatingactionbutton.FloatingActionButton; import com.mercy.alpacalive.adapter.EventList; import com.mercy.alpacalive.adapter.EventListAdapter; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class EventListing extends AppCompatActivity { private SharedPreferences sharedPref; public static final String TAG = "com.mercy.alpacalive"; private String sharedPrefFile = "com.mercy.alpacalive"; private static String GET_URL; private ProgressDialog pd; RequestQueue queue; ListView listEvent; List<EventList> dbeventlist; EventListAdapter adapter; private Button btnRefresh; private SwipeRefreshLayout sr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_event_listing); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); sharedPref = getSharedPreferences(sharedPrefFile,MODE_PRIVATE); String serverIP = sharedPref.getString("SERVER_IP",""); GET_URL = "http://" + serverIP + ":8080/alpacalive/SelectEvent.php"; sr = findViewById(R.id.swiperefresh); sr.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { loadEventList(getApplicationContext(), GET_URL); adapter.notifyDataSetChanged(); if (sr.isRefreshing()) { sr.setRefreshing(false); } } }); listEvent = findViewById(R.id.list_event); btnRefresh = findViewById(R.id.btnRefresh); btnRefresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loadEventList(getApplicationContext(), GET_URL); adapter.notifyDataSetChanged(); } }); pd = new ProgressDialog(this); dbeventlist = new ArrayList<>(); FloatingActionButton fab = findViewById(R.id.fab); if (!isConnected()) { Toast.makeText(getApplicationContext(), "No network", Toast.LENGTH_LONG).show(); } loadEventList(getApplicationContext(), GET_URL); listEvent.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Object object = parent.getItemAtPosition(position); EventList itemAtPosition = (EventList) object; // String clicked = itemAtPosition.getEventName(); // Toast.makeText(getApplicationContext(),clicked, Toast.LENGTH_SHORT).show(); //click go to room list Intent intent = new Intent(EventListing.this, LiveListing.class); intent.putExtra("EVENT_ID", itemAtPosition.getEventID()); intent.putExtra("EVENT_NAME", itemAtPosition.getEventName()); startActivity(intent); } }); } public void addEvent(View view){ Intent intent = new Intent(this, AddEvent.class); startActivity(intent); } private boolean isConnected(){ ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); } private void loadEventList(Context context, String url) { // Instantiate the RequestQueue queue = Volley.newRequestQueue(context); if (!pd.isShowing()) pd.setMessage("Sync with server..."); pd.show(); JsonArrayRequest jsonObjectRequest = new JsonArrayRequest( url, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { try { dbeventlist.clear(); for (int i = 0; i < response.length(); i++) { JSONObject eventListingResponse = (JSONObject) response.get(i); String eventID = eventListingResponse.getString("eventID"); String eventName = eventListingResponse.getString("eventName"); String location = eventListingResponse.getString("eventLocation"); String start = eventListingResponse.getString("eventStartDate"); String end = eventListingResponse.getString("eventEndDate"); String details = eventListingResponse.getString("eventDetails"); int roomCount = eventListingResponse.getInt("roomCount"); dbeventlist.add(new EventList(eventID,eventName,location,start,end,details,roomCount)); } loadEvent(); if (pd.isShowing()) pd.dismiss(); } catch (Exception e) { Toast.makeText(getApplicationContext(), "Error:" + e.getMessage(), Toast.LENGTH_LONG).show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Toast.makeText(getApplicationContext(), "Error" + volleyError.getMessage(), Toast.LENGTH_LONG).show(); if (pd.isShowing()) pd.dismiss(); } }); // Set the tag on the request. jsonObjectRequest.setTag(TAG); // Add the request to the RequestQueue. queue.add(jsonObjectRequest); } private void loadEvent() { adapter = new EventListAdapter(this, R.layout.eventlisting_item, dbeventlist); listEvent.setAdapter(adapter); if(dbeventlist != null){ int size = dbeventlist.size(); if(size > 0) Toast.makeText(getApplicationContext(), "No. of record : " + size + ".", Toast.LENGTH_SHORT).show(); else Toast.makeText(getApplicationContext(), "No record found.", Toast.LENGTH_SHORT).show(); } } @Override protected void onResume() { super.onResume(); } }
9240dfc48dda7c3561695df0f482f945c3414e4d
452
java
Java
src/brackets/SocketTesting.java
captianjroot/EquationBrackets
fe1fe42c9d8f603ab431e5cbb858b3e6f6408a86
[ "MIT" ]
null
null
null
src/brackets/SocketTesting.java
captianjroot/EquationBrackets
fe1fe42c9d8f603ab431e5cbb858b3e6f6408a86
[ "MIT" ]
null
null
null
src/brackets/SocketTesting.java
captianjroot/EquationBrackets
fe1fe42c9d8f603ab431e5cbb858b3e6f6408a86
[ "MIT" ]
null
null
null
18.08
45
0.663717
1,001,699
package brackets; import SupportPackage.ArgsProcessor; public class SocketTesting { public static void main(String[] args) { Tunnel sock=new Tunnel("localhost", 4243); sock.connect(); ArgsProcessor ap = new ArgsProcessor(args); boolean done=false; while(!done) { String msg=ap.nextString("Next"); sock.send(msg); System.out.println(sock.rec()); if(msg.equals("9Z9")) { sock.disconnect(); done=true; } } } }
9240dfea59488a7f7efda4093ee35dd5de703fa0
12,894
java
Java
ethereum/statetransition/src/main/java/tech/pegasys/artemis/statetransition/StateProcessor.java
zscole/artemis
7803ce1846b1f51a440ce079fc0525a64f55c327
[ "Apache-2.0" ]
null
null
null
ethereum/statetransition/src/main/java/tech/pegasys/artemis/statetransition/StateProcessor.java
zscole/artemis
7803ce1846b1f51a440ce079fc0525a64f55c327
[ "Apache-2.0" ]
null
null
null
ethereum/statetransition/src/main/java/tech/pegasys/artemis/statetransition/StateProcessor.java
zscole/artemis
7803ce1846b1f51a440ce079fc0525a64f55c327
[ "Apache-2.0" ]
null
null
null
43.857143
118
0.705987
1,001,700
/* * Copyright 2019 ConsenSys AG. * * 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 tech.pegasys.artemis.statetransition; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.common.primitives.UnsignedLong; import java.util.Date; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; import net.consensys.cava.bytes.Bytes32; import org.apache.logging.log4j.Level; import tech.pegasys.artemis.data.RawRecord; import tech.pegasys.artemis.datastructures.Constants; import tech.pegasys.artemis.datastructures.blocks.BeaconBlock; import tech.pegasys.artemis.datastructures.state.BeaconState; import tech.pegasys.artemis.datastructures.util.BeaconStateUtil; import tech.pegasys.artemis.datastructures.util.DataStructureUtil; import tech.pegasys.artemis.pow.api.DepositEvent; import tech.pegasys.artemis.pow.api.Eth2GenesisEvent; import tech.pegasys.artemis.storage.ChainStorage; import tech.pegasys.artemis.storage.ChainStorageClient; import tech.pegasys.artemis.util.alogger.ALogger; import tech.pegasys.artemis.util.hashtree.HashTreeUtil; /** Class to manage the state tree and initiate state transitions */ public class StateProcessor { private BeaconState headState; // state chosen by lmd ghost to build and attest on private BeaconBlock headBlock; // block chosen by lmd ghost to build and attest on private Bytes32 finalizedStateRoot; // most recent finalized state root private Bytes32 finalizedBlockRoot; // most recent finalized block root private Bytes32 justifiedStateRoot; // most recent justified state root private Bytes32 justifiedBlockRoot; // most recent justified block root private UnsignedLong nodeTime; private UnsignedLong nodeSlot; private UnsignedLong nodeIndex = UnsignedLong.ZERO; private final EventBus eventBus; private StateTransition stateTransition; private ChainStorageClient store; private static final ALogger LOG = new ALogger(StateProcessor.class.getName()); public StateProcessor(EventBus eventBus) { this.eventBus = eventBus; this.stateTransition = new StateTransition(true); this.eventBus.register(this); this.store = ChainStorage.Create(ChainStorageClient.class, eventBus); } public StateProcessor(EventBus eventBus, boolean printEnabled) { this.eventBus = eventBus; this.stateTransition = new StateTransition(); this.eventBus.register(this); this.store = ChainStorage.Create(ChainStorageClient.class, eventBus); } @Subscribe public void onEth2GenesisEvent(Eth2GenesisEvent event) { LOG.log( Level.INFO, "******* Eth2Genesis Event detected ******* : " + ((tech.pegasys.artemis.pow.event.Eth2Genesis) event).getDeposit_root().toString()); this.nodeSlot = UnsignedLong.valueOf(Constants.GENESIS_SLOT); this.nodeTime = UnsignedLong.valueOf(Constants.GENESIS_SLOT) .times(UnsignedLong.valueOf(Constants.SLOT_DURATION)); LOG.log(Level.INFO, "node slot: " + nodeSlot.longValue()); LOG.log(Level.INFO, "node time: " + nodeTime.longValue()); try { BeaconState initial_state = DataStructureUtil.createInitialBeaconState(); Bytes32 initial_state_root = HashTreeUtil.hash_tree_root(initial_state.toBytes()); BeaconBlock genesis_block = BeaconBlock.createGenesis(initial_state_root); Bytes32 genesis_block_root = HashTreeUtil.hash_tree_root(genesis_block.toBytes()); LOG.log(Level.INFO, "initial state root is " + initial_state_root.toHexString()); this.store.addState(initial_state_root, initial_state); this.store.addProcessedBlock(genesis_block_root, genesis_block); this.headBlock = genesis_block; this.justifiedStateRoot = initial_state_root; this.justifiedBlockRoot = genesis_block_root; this.finalizedStateRoot = initial_state_root; this.finalizedBlockRoot = genesis_block_root; this.eventBus.post(true); } catch (IllegalStateException e) { LOG.log(Level.FATAL, e.toString()); } } @Subscribe public void onDepositEvent(DepositEvent event) { LOG.log( Level.INFO, "Deposit Event detected: " + ((tech.pegasys.artemis.pow.event.Deposit) event).getDeposit_root().toString()); } @Subscribe public void onNewSlot(Date date) throws StateTransitionException { this.nodeSlot = this.nodeSlot.plus(UnsignedLong.ONE); this.nodeTime = this.nodeTime.plus(UnsignedLong.valueOf(Constants.SLOT_DURATION)); LOG.log(Level.INFO, "******* Slot Event Detected *******"); LOG.log(Level.INFO, "node time: " + nodeTime.longValue()); LOG.log(Level.INFO, "node slot: " + nodeSlot.longValue()); // Get all the unprocessed blocks that are for slots <= nodeSlot List<Optional<BeaconBlock>> unprocessedBlocks = this.store.getUnprocessedBlocksUntilSlot(nodeSlot); // Use each block to build on all possible forks unprocessedBlocks.forEach((block) -> processFork(block)); // Update the block that is subjectively the head of the chain using lmd_ghost updateHeadBlockUsingLMDGhost(); // Get head block's state, and initialize a newHeadState variable to run state transition on BeaconState headBlockState = store.getState(headBlock.getState_root()).get(); BeaconState newHeadState = BeaconState.deepCopy(headBlockState); // Hash headBlock to obtain previousBlockRoot that will be used // as previous_block_root in all state transitions Bytes32 previousBlockRoot = HashTreeUtil.hash_tree_root(headBlock.toBytes()); // Run state transition with no blocks from the newHeadState.slot to node.slot boolean firstLoop = true; while (newHeadState.getSlot().compareTo(nodeSlot) < 0) { if (firstLoop) { LOG.log( Level.INFO, "Transitioning state from slot: " + newHeadState.getSlot() + " to slot: " + nodeSlot); firstLoop = false; } stateTransition.initiate(newHeadState, null, previousBlockRoot); } this.headState = newHeadState; // TODO: This is not appropriate for StateProcessor. This index field should be implemented in // the data adapter. // TODO: move all this data provider logic to a new method this.nodeIndex = this.nodeIndex.plus(UnsignedLong.ONE); BeaconState justifiedState = store.getState(justifiedStateRoot).get(); BeaconBlock justifiedBlock = store.getProcessedBlock(justifiedBlockRoot).get(); BeaconState finalizedState = store.getState(finalizedStateRoot).get(); BeaconBlock finalizedBlock = store.getProcessedBlock(finalizedBlockRoot).get(); RawRecord record = new RawRecord( this.nodeIndex.longValue(), newHeadState, headBlock, justifiedState, justifiedBlock, finalizedState, finalizedBlock); this.eventBus.post(record); } protected Boolean inspectBlock(Optional<BeaconBlock> block) { if (!block.isPresent()) { return false; } if (!this.store.getParent(block.get()).isPresent()) { return false; } UnsignedLong blockTime = UnsignedLong.valueOf(block.get().getSlot()) .times(UnsignedLong.valueOf(Constants.SLOT_DURATION)); // TODO: Here we reject block because time is not there, // however, the block is already removed from queue, so // we're losing a valid block here. if (this.nodeTime.compareTo(blockTime) < 0) { LOG.log(Level.FATAL, "We lost a valid block!"); return false; } return true; } protected void processFork(Optional<BeaconBlock> unprocessedBlock) { try { Boolean shouldProcessBlock = inspectBlock(unprocessedBlock); if (shouldProcessBlock) { // Get block, block root and block state root BeaconBlock block = unprocessedBlock.get(); Bytes32 blockRoot = HashTreeUtil.hash_tree_root(block.toBytes()); Bytes32 blockStateRoot = block.getState_root(); // Get parent block, parent block root, parent block state root, and parent block state BeaconBlock parentBlock = this.store.getParent(block).get(); Bytes32 parentBlockRoot = block.getParent_root(); Bytes32 parentBlockStateRoot = parentBlock.getState_root(); BeaconState parentBlockState = this.store.getState(parentBlockStateRoot).get(); // TODO: check if the fork_head's parent slot is further back than the weak subjectivity // period, should we check? // Run state transition with no blocks from the parentBlockState.slot to block.slot - 1 boolean firstLoop = true; BeaconState currentState = BeaconState.deepCopy(parentBlockState); while (currentState.getSlot().compareTo(UnsignedLong.valueOf(block.getSlot() - 1)) < 0) { if (firstLoop) { LOG.log( Level.INFO, "Transitioning state from slot: " + currentState.getSlot() + " to slot: " + UnsignedLong.valueOf(block.getSlot() - 1)); firstLoop = false; } stateTransition.initiate(currentState, null, parentBlockRoot); } // Run state transition with the block LOG.log( Level.INFO, "Process Fork: Running State transition for currentState.slot: " + currentState.getSlot() + " block.slot: " + block.getSlot()); stateTransition.initiate(currentState, block, parentBlockRoot); Bytes32 newStateRoot = HashTreeUtil.hash_tree_root(currentState.toBytes()); // Verify that the state root we have computed is the state root that block is // claiming us we should reach, save the block and the state if its correct. if (blockStateRoot.equals(newStateRoot)) { LOG.log(Level.INFO, "The fork_head's state root matches the calculated state root!"); this.store.addProcessedBlock(blockRoot, block); this.store.addState(newStateRoot, currentState); } else { LOG.log( Level.INFO, "The fork_head's state root does NOT matches the calculated state root!"); } } else { LOG.log(Level.INFO, "Skipped processing block"); } } catch (NoSuchElementException | IllegalArgumentException | StateTransitionException e) { LOG.log(Level.WARN, e.toString()); } } protected void updateHeadBlockUsingLMDGhost() { // Update justified block and state roots updateJustifiedAndFinalized(); try { // Obtain latest justified block and state that will be passed into lmd_ghost BeaconState justifiedState = store.getState(justifiedStateRoot).get(); BeaconBlock justifiedBlock = store.getProcessedBlock(justifiedBlockRoot).get(); LOG.log(Level.INFO, "justifiedState slot : " + justifiedState.getSlot()); LOG.log(Level.INFO, "justifiedBlock slot : " + justifiedBlock.getSlot()); // Run lmd_ghost to get the head block this.headBlock = LmdGhost.lmd_ghost(store, justifiedState, justifiedBlock); } catch (NoSuchElementException | StateTransitionException e) { LOG.log(Level.FATAL, "Can't update head block using lmd ghost"); } } protected void updateJustifiedAndFinalized() { // If it is the genesis epoch, keep the justified state root as genesis state root // because get_block_root gives an error if the slot is not less than state.slot if (BeaconStateUtil.slot_to_epoch(nodeSlot) .compareTo(UnsignedLong.valueOf(Constants.GENESIS_EPOCH)) != 0) { try { BeaconState headState = store.getState(headBlock.getState_root()).get(); this.finalizedBlockRoot = BeaconStateUtil.get_block_root( headState, BeaconStateUtil.get_epoch_start_slot(headState.getFinalized_epoch())); this.justifiedBlockRoot = BeaconStateUtil.get_block_root( headState, BeaconStateUtil.get_epoch_start_slot(headState.getJustified_epoch())); this.justifiedStateRoot = store.getProcessedBlock(justifiedBlockRoot).get().getState_root(); this.finalizedBlockRoot = store.getProcessedBlock(finalizedBlockRoot).get().getState_root(); } catch (Exception e) { LOG.log(Level.FATAL, "Can't update justified"); } } } }
9240e09c682d36dd6bca667a290ca1ad1a731ebd
2,730
java
Java
src/test/java/org/springframework/samples/petclinic/web/VetControllerTest.java
daisymae/tb2g-testing-spring
104b67212f5e0da095e19ef643c511f00708d7e4
[ "Apache-2.0" ]
null
null
null
src/test/java/org/springframework/samples/petclinic/web/VetControllerTest.java
daisymae/tb2g-testing-spring
104b67212f5e0da095e19ef643c511f00708d7e4
[ "Apache-2.0" ]
1
2021-06-04T22:02:40.000Z
2021-06-04T22:02:40.000Z
src/test/java/org/springframework/samples/petclinic/web/VetControllerTest.java
daisymae/tb2g-testing-spring
104b67212f5e0da095e19ef643c511f00708d7e4
[ "Apache-2.0" ]
null
null
null
29.354839
84
0.705861
1,001,701
package org.springframework.samples.petclinic.web; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.samples.petclinic.model.Vet; import org.springframework.samples.petclinic.model.Vets; import org.springframework.samples.petclinic.service.ClinicService; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * This is a simple Unit test, no MVC mock. */ @ExtendWith(MockitoExtension.class) class VetControllerTest { @Mock ClinicService clinicService; @Mock Map<String, Object> model; @InjectMocks VetController controller; List<Vet> vetsList = new ArrayList<>(); MockMvc mockMvc; @BeforeEach void setUp() { vetsList.add(new Vet()); given(clinicService.findVets()).willReturn(vetsList); // setup mockMVC; standalone setup of the controller mockMvc = MockMvcBuilders.standaloneSetup(controller).build(); } /** * MockMVC test that tests the showVetList in VetController * have mocked the service in the setup * * @throws Exception */ @Test void testControllerShowVetList() throws Exception { mockMvc.perform(get("/vets.html")) .andExpect(status().isOk()) .andExpect(model().attributeExists("vets")) .andExpect(view().name("vets/vetList")); } /** * This test is similar to above but as a POJO test. * The test above confirms the MVC parts as well. */ @Test void showVetList() { //when String view = controller.showVetList(model); //then then(clinicService).should().findVets(); then(model).should().put(anyString(), any()); assertThat("vets/VetList").isEqualToIgnoringCase(view); } @Test void showResourcesVetList() { //when Vets vets = controller.showResourcesVetList(); //then then(clinicService).should().findVets(); assertThat(vets.getVetList()).hasSize(1); } }
9240e12401a6a45a7c638e4750dc66016c57f7f7
4,142
java
Java
src/com/teleca/jamendo/activity/EqualizerActivity.java
HuTianQi/jamendo-android
6b31c7ba27441a79d4436a499b6c9c9301d21505
[ "Apache-2.0" ]
185
2015-01-06T06:07:13.000Z
2020-11-10T06:46:32.000Z
src/com/teleca/jamendo/activity/EqualizerActivity.java
shinyvince/jamendo-android
6b31c7ba27441a79d4436a499b6c9c9301d21505
[ "Apache-2.0" ]
9
2015-05-25T13:37:53.000Z
2020-05-04T08:24:23.000Z
src/com/teleca/jamendo/activity/EqualizerActivity.java
shinyvince/jamendo-android
6b31c7ba27441a79d4436a499b6c9c9301d21505
[ "Apache-2.0" ]
136
2015-01-12T03:13:34.000Z
2021-11-07T02:18:48.000Z
33.682927
97
0.6937
1,001,702
/* * Copyright (C) 2009 Teleca Poland Sp. z o.o. <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.teleca.jamendo.activity; import java.util.HashMap; import com.teleca.jamendo.JamendoApplication; import com.teleca.jamendo.R; import com.teleca.jamendo.dialog.CustomEqualizer; import android.app.Activity; import android.media.AudioManager; import android.media.audiofx.Equalizer; import android.media.audiofx.Equalizer.Settings; import android.os.Bundle; import android.util.Log; import android.util.SparseArray; import android.view.View; import android.view.Window; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RadioGroup.OnCheckedChangeListener; /** * Equalizer View - Sound Settings * * @author jessica * */ public class EqualizerActivity extends Activity{ public static final String PREFERENCE_EQUALIZER = "equalizer"; private RadioGroup mRadioGroup; private Activity mActivity = this; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setVolumeControlStream(AudioManager.STREAM_MUSIC); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.equalizer); mRadioGroup = (RadioGroup) findViewById(R.id.equalizerPreset); setupEqualizerFxAndUI(); } /** * Create the equalizer view */ private void setupEqualizerFxAndUI() { // Since there is no guarantee that app equalizer may be usable // a global equalizer may be used only to access presets final Equalizer equalizer = new Equalizer(0, 0); Log.i(JamendoApplication.TAG, "setupEqualizerFxAndUI " + equalizer.getNumberOfPresets()); Settings settings = JamendoApplication.getInstance().getEqualizerSettigns(); // Association between radio button and prest equalization final SparseArray<Short> group = new SparseArray<Short>(); for (int i = equalizer.getNumberOfPresets() - 1; i >= 0; i--) { RadioButton button = new RadioButton(this); button.setText(equalizer.getPresetName((short) i)); mRadioGroup.addView(button); group.put(button.getId(), (short) i); if (settings != null && settings.curPreset == i) { button.setChecked(true); } } // radio button that custom the equalization RadioButton custom = new RadioButton(this); custom.setText(R.string.custom); mRadioGroup.addView(custom); if (settings == null || settings.curPreset == -1) { mRadioGroup.check(custom.getId()); } equalizer.release(); // Activity for custom button, will always show the dialog custom.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { new CustomEqualizer(mActivity).show(); } }); // Event for radio button this.mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener(){ public void onCheckedChanged(RadioGroup radioGroup, int checkedId) { Short preset = group.get(checkedId); if (preset != null) { mRadioGroup.check(checkedId); if (JamendoApplication.getInstance().isEqualizerRunning()) { final Equalizer eq = JamendoApplication.getInstance().getMyEqualizer(); eq.usePreset(preset); JamendoApplication.getInstance().updateEqualizerSettings(eq.getProperties()); } else { // save for later use JamendoApplication.getInstance().setEqualizerPreset(preset); } } } }); } }
9240e1792060767cd6e4db5ee42cbe8e4c2b0444
597
java
Java
src/test/java/ohtu/unitAndRepoTests/Helpers.java
ArktinenKarpalo/ovitiimi
167b9e896386120c3eb930822a4babc8f854b8ae
[ "MIT" ]
null
null
null
src/test/java/ohtu/unitAndRepoTests/Helpers.java
ArktinenKarpalo/ovitiimi
167b9e896386120c3eb930822a4babc8f854b8ae
[ "MIT" ]
null
null
null
src/test/java/ohtu/unitAndRepoTests/Helpers.java
ArktinenKarpalo/ovitiimi
167b9e896386120c3eb930822a4babc8f854b8ae
[ "MIT" ]
2
2019-12-08T12:16:41.000Z
2019-12-09T16:34:29.000Z
23.88
100
0.700168
1,001,703
package ohtu.unitAndRepoTests; import java.util.Collection; import java.util.Iterator; import ohtu.database.entities.ISimilar; public class Helpers { public static <T extends ISimilar<T>> boolean areSimilar(Collection<T> left, Collection<T> right) { if (left.size() != right.size()) { //Fast path return false; } Iterator<T> leftIterator = left.iterator(); Iterator<T> rightIterator = right.iterator(); while (leftIterator.hasNext() && rightIterator.hasNext()) { if (!leftIterator.next().areSimilar(rightIterator.next())) { return false; } } return true; } }
9240e1cb890f56fb485c0abf3799408867121913
2,787
java
Java
sampleservice-repo/src/main/java/com/govtech/sampleservice/repo/repositories/base/BaseReadOnlyRepository.java
weihan1394/sampleservice
53fdcd37d920992495b308d29f7fbb231c2a9560
[ "Apache-2.0" ]
null
null
null
sampleservice-repo/src/main/java/com/govtech/sampleservice/repo/repositories/base/BaseReadOnlyRepository.java
weihan1394/sampleservice
53fdcd37d920992495b308d29f7fbb231c2a9560
[ "Apache-2.0" ]
2
2020-01-31T18:22:19.000Z
2021-12-10T01:21:30.000Z
sampleservice-repo/src/main/java/com/govtech/sampleservice/repo/repositories/base/BaseReadOnlyRepository.java
weihan1394/sampleservice
53fdcd37d920992495b308d29f7fbb231c2a9560
[ "Apache-2.0" ]
null
null
null
34.8375
100
0.715465
1,001,704
package com.govtech.sampleservice.repo.repositories.base; import com.govtech.sampleservice.repo.entities.EntityInterface; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import org.hibernate.SessionFactory; import org.hibernate.StatelessSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; public abstract class BaseReadOnlyRepository<T extends EntityInterface> { @PersistenceContext private EntityManager em; @Autowired SessionFactory sessionFactory; @Value("${config.pageSize}") Integer pageSize; public List<T> findAll(Class<T> clazz) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<T> cq = cb.createQuery(clazz); cq.from(clazz); TypedQuery<T> query = em.createQuery(cq); return query.getResultList(); } public T findById(Class<T> clazz, Integer id) { return em.find(clazz, id); } public List<T> findAllNonSuperseded(Class<T> clazz) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<T> cq = cb.createQuery(clazz); Root root = cq.from(clazz); cq.where(cb.isNull(root.get("temporalData").get("superseded"))); TypedQuery<T> query = em.createQuery(cq); return query.getResultList(); } public List<T> findAllNonSuperseded(Class<T> clazz, int page) { StatelessSession statelessSession = sessionFactory.openStatelessSession(); long offset = (long) page * pageSize; String query = "SELECT c FROM " + clazz.getName() + " c WHERE c.temporalData.superseded = NULL"; List resultList = statelessSession .createQuery(query) .setReadOnly(true) .setCacheable(false) .setFirstResult((int) offset) .setMaxResults(pageSize) .getResultList(); statelessSession.close(); return resultList; } // Commented out scrolling function for future use - Don't delete unless you're sure // public ScrollableResults findAllNonSupersededReadOnly(Class<T> clazz) { // StatelessSession statelessSession = // em.unwrap(Session.class).getSessionFactory().openStatelessSession(); // String query = "SELECT c FROM " + clazz.getName() + " c WHERE c.temporalData.superseded = // NULL"; // ScrollableResults scrollableResults = // return statelessSession // .createQuery(query) // .setReadOnly(true) // .setCacheable(false) // .scroll(ScrollMode.FORWARD_ONLY); // statelessSession.close(); // return scrollableResults; // } }
9240e1e8ac16a889217301051723fcb649a94270
469
java
Java
src/com/evan/javaaaaaaaaa/jvm/hotswap/HotSwapClassLoader.java
tianshangstar/Javaaaaaaaaa
fa020c712bd7c7ddaf9a01c96959c019d1c5a5ac
[ "Apache-2.0" ]
2
2018-08-23T08:00:47.000Z
2018-08-23T08:01:28.000Z
src/com/evan/javaaaaaaaaa/jvm/hotswap/HotSwapClassLoader.java
tianshangstar/Javaaaaaaaaa
fa020c712bd7c7ddaf9a01c96959c019d1c5a5ac
[ "Apache-2.0" ]
null
null
null
src/com/evan/javaaaaaaaaa/jvm/hotswap/HotSwapClassLoader.java
tianshangstar/Javaaaaaaaaa
fa020c712bd7c7ddaf9a01c96959c019d1c5a5ac
[ "Apache-2.0" ]
null
null
null
24.684211
65
0.733475
1,001,705
package com.evan.javaaaaaaaaa.jvm.hotswap; /** * 为了多次载入执行类而加入的类加载器 * 把cdefineClass方法开放出来,只有外部显示调用的时候才会使用到loadBYte方法 * 由虚拟机调用时,仍然按照原有的双亲委派规则使用loadClass方法进行加载 * <p> * 来自深入《理解java虚拟机》 章节9.3 */ public class HotSwapClassLoader extends ClassLoader { public HotSwapClassLoader() { super(HotSwapClassLoader.class.getClassLoader()); } public Class loadByte(byte[] classByte){ return defineClass(null, classByte, 0, classByte.length); } }
9240e2e2eefaf57103a7b775f96bc103fc527ecb
1,452
java
Java
common/src/main/java/me/lorenzo0111/rocketjoin/common/exception/LoadException.java
Boy0000/RocketJoin
d56ff22a8dc463c2d8a27784d6eeb2718d0c2540
[ "MIT" ]
3
2020-08-09T13:40:56.000Z
2022-03-26T15:36:35.000Z
common/src/main/java/me/lorenzo0111/rocketjoin/common/exception/LoadException.java
Boy0000/RocketJoin
d56ff22a8dc463c2d8a27784d6eeb2718d0c2540
[ "MIT" ]
37
2020-08-13T15:17:55.000Z
2022-03-12T06:10:26.000Z
common/src/main/java/me/lorenzo0111/rocketjoin/common/exception/LoadException.java
Boy0000/RocketJoin
d56ff22a8dc463c2d8a27784d6eeb2718d0c2540
[ "MIT" ]
2
2021-03-22T11:44:19.000Z
2022-02-15T20:11:53.000Z
42.705882
81
0.756198
1,001,706
/* * This file is part of RocketJoin, licensed under the MIT License. * * Copyright (c) Lorenzo0111 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.lorenzo0111.rocketjoin.common.exception; import org.jetbrains.annotations.NotNull; public class LoadException extends Exception { public LoadException(@NotNull String error) { super(String.format("Unable to load plugin: %s", error)); } }
9240e316ccedf5029fd764c5dbff910571821c1a
875
java
Java
aura/src/main/java/org/auraframework/def/RendererDef.java
augustyakaravat/aura
98d7ba491172c7ea44cbbf74be5eb858040c9c46
[ "Apache-2.0" ]
587
2015-01-01T00:42:17.000Z
2022-01-23T00:14:13.000Z
aura/src/main/java/org/auraframework/def/RendererDef.java
augustyakaravat/aura
98d7ba491172c7ea44cbbf74be5eb858040c9c46
[ "Apache-2.0" ]
156
2015-02-06T17:56:21.000Z
2019-02-27T05:19:11.000Z
aura/src/main/java/org/auraframework/def/RendererDef.java
augustyakaravat/aura
98d7ba491172c7ea44cbbf74be5eb858040c9c46
[ "Apache-2.0" ]
340
2015-01-13T14:13:38.000Z
2022-03-21T04:05:29.000Z
32.407407
75
0.738286
1,001,707
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.auraframework.def; /** * Renderer Definition. * * {@link org.auraframework.instance.RendererInstance} has render method */ public interface RendererDef extends RemotableDefinition { @Override DefDescriptor<RendererDef> getDescriptor(); }
9240e3b04621f31765a03f7ac21fe63b01fa5469
1,191
java
Java
src/main/java/fi/csc/chipster/comp/resourcemonitor/ProcessResourceMonitor.java
chipster/session-storage
16e6e88312e272f0d9997828bf73a0b205f0cb11
[ "MIT" ]
null
null
null
src/main/java/fi/csc/chipster/comp/resourcemonitor/ProcessResourceMonitor.java
chipster/session-storage
16e6e88312e272f0d9997828bf73a0b205f0cb11
[ "MIT" ]
null
null
null
src/main/java/fi/csc/chipster/comp/resourcemonitor/ProcessResourceMonitor.java
chipster/session-storage
16e6e88312e272f0d9997828bf73a0b205f0cb11
[ "MIT" ]
null
null
null
25.891304
90
0.716205
1,001,708
package fi.csc.chipster.comp.resourcemonitor; import java.io.IOException; import java.util.HashSet; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class ProcessResourceMonitor { private static Logger logger = LogManager.getLogger(); private Long pid; private HashSet<Long> allPids = new HashSet<>(); private Long maxMem; private Long currentMem; private Process javaProcess; public ProcessResourceMonitor(Process javaProcess) { this.javaProcess = javaProcess; } public Long getMaxMem() { return maxMem; } public Long getCurrentMem() { return currentMem; } public void update() throws IOException { if (pid == null) { this.pid = ProcessMonitoring.getPid(javaProcess); allPids.add(pid); } if (pid != null) { // remember all pids, even if child process ends and grandchild's ppid will be set to 1 allPids.addAll(ProcessMonitoring.getChildren(pid, true)); currentMem = ProcessMonitoring.getTotalMemory(allPids); if (this.maxMem == null || currentMem > this.maxMem) { this.maxMem = currentMem; } logger.debug("pid " + pid + " mem " + maxMem + " pid count " + allPids.size()); } } }
9240e4a433eba0e55b5a8062579c5b38d444aded
306
java
Java
src/test/examples/regress_76025099/helper/AbstractSub.java
ganadist/r8
850b5a4725954b677103a3a575239d0f330c0b0f
[ "Apache-2.0", "BSD-3-Clause" ]
8
2019-02-16T19:27:05.000Z
2020-10-30T20:10:42.000Z
src/test/examples/regress_76025099/helper/AbstractSub.java
ganadist/r8
850b5a4725954b677103a3a575239d0f330c0b0f
[ "Apache-2.0", "BSD-3-Clause" ]
3
2020-01-27T22:30:05.000Z
2020-07-31T20:58:15.000Z
src/test/examples/regress_76025099/helper/AbstractSub.java
ganadist/r8
850b5a4725954b677103a3a575239d0f330c0b0f
[ "Apache-2.0", "BSD-3-Clause" ]
5
2019-03-03T04:49:03.000Z
2021-11-23T15:47:38.000Z
38.25
77
0.777778
1,001,709
// Copyright (c) 2018, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package regress_76025099.helper; public abstract class AbstractSub extends AbstractBase { }
9240e659e00355b7dca6033b111e58e542767b89
3,188
java
Java
backend/de.metas.business/src/main/java/de/metas/security/permissions/bpartner_hierarchy/BPartnerDependentDocumentEvent.java
lxhlzq/metasfresh
c09bbf596edd878658d98ed173cc728afb2c630a
[ "RSA-MD" ]
1
2021-02-17T12:00:41.000Z
2021-02-17T12:00:41.000Z
backend/de.metas.business/src/main/java/de/metas/security/permissions/bpartner_hierarchy/BPartnerDependentDocumentEvent.java
lxhlzq/metasfresh
c09bbf596edd878658d98ed173cc728afb2c630a
[ "RSA-MD" ]
null
null
null
backend/de.metas.business/src/main/java/de/metas/security/permissions/bpartner_hierarchy/BPartnerDependentDocumentEvent.java
lxhlzq/metasfresh
c09bbf596edd878658d98ed173cc728afb2c630a
[ "RSA-MD" ]
null
null
null
30.653846
159
0.782936
1,001,710
package de.metas.security.permissions.bpartner_hierarchy; import javax.annotation.Nullable; import org.adempiere.util.lang.impl.TableRecordReference; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import de.metas.bpartner.BPartnerId; import de.metas.security.permissions.bpartner_hierarchy.handlers.BPartnerDependentDocument; import de.metas.user.UserId; import lombok.Builder; import lombok.NonNull; import lombok.Value; /* * #%L * de.metas.business * %% * Copyright (C) 2019 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ @Value @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public class BPartnerDependentDocumentEvent { public static BPartnerDependentDocumentEvent newRecord(final BPartnerDependentDocument doc) { return prepareFrom(doc) .eventType(EventType.NEW_RECORD) .build(); } public static BPartnerDependentDocumentEvent bpartnerChanged(final BPartnerDependentDocument doc) { return prepareFrom(doc) .eventType(EventType.BPARTNER_CHANGED) .build(); } private static BPartnerDependentDocumentEventBuilder prepareFrom(@NonNull final BPartnerDependentDocument doc) { return builder() .documentRef(doc.getDocumentRef()) .newBPartnerId(doc.getNewBPartnerId()) .oldBPartnerId(doc.getOldBPartnerId()) .updatedBy(doc.getUpdatedBy()); } @JsonProperty("documentRef") TableRecordReference documentRef; public enum EventType { NEW_RECORD, BPARTNER_CHANGED } @JsonProperty("eventType") EventType eventType; @JsonProperty("newBPartnerId") BPartnerId newBPartnerId; @JsonProperty("oldBPartnerId") BPartnerId oldBPartnerId; @JsonProperty("updatedBy") UserId updatedBy; @JsonCreator @Builder private BPartnerDependentDocumentEvent( @JsonProperty("documentRef") @NonNull final TableRecordReference documentRef, @JsonProperty("eventType") @NonNull final EventType eventType, @JsonProperty("newBPartnerId") @Nullable final BPartnerId newBPartnerId, @JsonProperty("oldBPartnerId") @Nullable final BPartnerId oldBPartnerId, @JsonProperty("updatedBy") @NonNull final UserId updatedBy) { this.documentRef = documentRef; this.eventType = eventType; this.newBPartnerId = newBPartnerId; this.oldBPartnerId = oldBPartnerId; this.updatedBy = updatedBy; } }
9240e8060fcee62cc7fac25028a6f99310eb16ba
2,701
java
Java
geode-wan/src/main/java/org/apache/geode/cache/client/internal/locator/wan/RemoteLocatorJoinRequest.java
nikochiko/geode
19f55add07d6a652911dc5a5e2116fcf7bf7b2f7
[ "Apache-2.0" ]
1,475
2016-12-06T06:10:53.000Z
2022-03-30T09:55:23.000Z
geode-wan/src/main/java/org/apache/geode/cache/client/internal/locator/wan/RemoteLocatorJoinRequest.java
nikochiko/geode
19f55add07d6a652911dc5a5e2116fcf7bf7b2f7
[ "Apache-2.0" ]
2,809
2016-12-06T19:24:26.000Z
2022-03-31T22:02:20.000Z
geode-wan/src/main/java/org/apache/geode/cache/client/internal/locator/wan/RemoteLocatorJoinRequest.java
Krishnan-Raghavan/geode
708588659751c1213c467f5b200b2c36952af563
[ "Apache-2.0", "BSD-3-Clause" ]
531
2016-12-06T05:48:47.000Z
2022-03-31T23:06:37.000Z
30.693182
100
0.764902
1,001,711
/* * 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.geode.cache.client.internal.locator.wan; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import org.apache.geode.internal.admin.remote.DistributionLocatorId; import org.apache.geode.internal.serialization.DataSerializableFixedID; import org.apache.geode.internal.serialization.DeserializationContext; import org.apache.geode.internal.serialization.KnownVersion; import org.apache.geode.internal.serialization.SerializationContext; /** * Requests remote locators of a remote WAN site * * * @since GemFire 6.6 * */ public class RemoteLocatorJoinRequest implements DataSerializableFixedID { private DistributionLocatorId locator = null; private int distributedSystemId = -1; public RemoteLocatorJoinRequest() { super(); } public RemoteLocatorJoinRequest(int distributedSystemId, DistributionLocatorId locator, String serverGroup) { this.distributedSystemId = distributedSystemId; this.locator = locator; } @Override public void fromData(DataInput in, DeserializationContext context) throws IOException, ClassNotFoundException { this.locator = context.getDeserializer().readObject(in); this.distributedSystemId = in.readInt(); } @Override public void toData(DataOutput out, SerializationContext context) throws IOException { context.getSerializer().writeObject(locator, out); out.writeInt(this.distributedSystemId); } public DistributionLocatorId getLocator() { return this.locator; } public int getDistributedSystemId() { return distributedSystemId; } @Override public int getDSFID() { return DataSerializableFixedID.REMOTE_LOCATOR_JOIN_REQUEST; } @Override public String toString() { return "RemoteLocatorJoinRequest{locator=" + locator + "}"; } @Override public KnownVersion[] getSerializationVersions() { return null; } }
9240e830831b9dd7d6e57c7258b04668cf391df7
2,236
java
Java
admin-provider/src/main/java/com/admin/provider/dto/MenuDTO.java
Zssaer/admin-api
0d7ba89062a00e4b43d49ceab6bee84e0687617e
[ "Apache-2.0" ]
7
2021-09-17T12:44:56.000Z
2022-02-10T03:50:45.000Z
admin-provider/src/main/java/com/admin/provider/dto/MenuDTO.java
Zssaer/admin-api
0d7ba89062a00e4b43d49ceab6bee84e0687617e
[ "Apache-2.0" ]
null
null
null
admin-provider/src/main/java/com/admin/provider/dto/MenuDTO.java
Zssaer/admin-api
0d7ba89062a00e4b43d49ceab6bee84e0687617e
[ "Apache-2.0" ]
null
null
null
19.614035
59
0.580501
1,001,712
package com.admin.provider.dto; import com.admin.provider.vo.MetaVO; import io.swagger.annotations.ApiModelProperty; import java.util.List; /** * @description: TODO * @author: Zhaotianyi * @time: 2021/9/1 15:38 */ public class MenuDTO { @ApiModelProperty(value = "id", dataType = "Integer") private Integer id; /** * 路由名称 */ @ApiModelProperty(value = "路由名称", dataType = "String") private String name; /** * 路由地址 */ @ApiModelProperty(value = "路由地址", dataType = "String") private String path; /** * 重定向地址 */ @ApiModelProperty(value = "重定向地址", dataType = "String") private String redirect; /** * 菜单元素 */ @ApiModelProperty(value = "菜单元素", dataType = "Object") private MetaVO metaVO; /** * 组件名 */ @ApiModelProperty(value = "组件名", dataType = "String") private String component; /** * 子类菜单 */ @ApiModelProperty(value = "子类菜单", dataType = "String") private List<MenuDTO> children; @ApiModelProperty(value = "路由页", dataType = "String") private String page; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPage() { return page; } public void setPage(String page) { this.page = page; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getRedirect() { return redirect; } public void setRedirect(String redirect) { this.redirect = redirect; } public MetaVO getMeta() { return metaVO; } public void setMeta(MetaVO metaVO) { this.metaVO = metaVO; } public String getComponent() { return component; } public void setComponent(String component) { this.component = component; } public List<MenuDTO> getChildren() { return children; } public void setChildren(List<MenuDTO> children) { this.children = children; } }
9240e868d9b76f73c1021b3e3af13e00d0e5b148
164
java
Java
SimpleGame/SimpleGame-android/gen/cocos2djava/SimpleGame/BuildConfig.java
cocos2d-java/cocos2d-java
019f4324a4302d1ccb20b2e3d26c1a56a85c53a6
[ "MIT" ]
26
2015-01-19T02:37:59.000Z
2021-07-11T09:48:54.000Z
SimpleGame/SimpleGame-android/gen/cocos2djava/SimpleGame/BuildConfig.java
cocos2d-java/cocos2d-java
019f4324a4302d1ccb20b2e3d26c1a56a85c53a6
[ "MIT" ]
1
2016-08-28T15:22:52.000Z
2017-02-14T13:16:09.000Z
SimpleGame/SimpleGame-android/gen/cocos2djava/SimpleGame/BuildConfig.java
cocos2d-java/cocos2d-java
019f4324a4302d1ccb20b2e3d26c1a56a85c53a6
[ "MIT" ]
20
2015-06-04T06:27:55.000Z
2020-10-22T07:52:57.000Z
27.333333
50
0.762195
1,001,713
/** Automatically generated file. DO NOT MODIFY */ package cocos2djava.SimpleGame; public final class BuildConfig { public final static boolean DEBUG = true; }
9240e95fc8945c245bb9916c0fc73e0a213d44cf
14,676
java
Java
jcode-util/src/main/java/io/github/jeddict/jcode/task/AbstractNBTask.java
alexkarezin/jeddict
49936979a289081e0b8bfbc2c0f0c83676d48d54
[ "Apache-2.0" ]
293
2017-03-17T14:47:53.000Z
2022-02-22T16:30:37.000Z
jcode-util/src/main/java/io/github/jeddict/jcode/task/AbstractNBTask.java
alexkarezin/jeddict
49936979a289081e0b8bfbc2c0f0c83676d48d54
[ "Apache-2.0" ]
298
2017-03-17T04:37:56.000Z
2022-03-29T09:46:33.000Z
jcode-util/src/main/java/io/github/jeddict/jcode/task/AbstractNBTask.java
alexkarezin/jeddict
49936979a289081e0b8bfbc2c0f0c83676d48d54
[ "Apache-2.0" ]
44
2017-03-31T19:23:30.000Z
2022-01-29T12:06:17.000Z
29.293413
109
0.578359
1,001,714
/** * Copyright 2013-2019 the original author or authors from the Jeddict project (https://jeddict.github.io/). * * 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.github.jeddict.jcode.task; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Vector; import io.github.jeddict.util.StringUtils; import org.netbeans.api.progress.aggregate.AggregateProgressFactory; import org.netbeans.api.progress.aggregate.AggregateProgressHandle; import org.netbeans.api.progress.aggregate.ProgressContributor; import io.github.jeddict.jcode.console.Console; import static io.github.jeddict.jcode.console.Console.FG_GREEN; import static io.github.jeddict.jcode.console.Console.FG_DARK_RED; import org.openide.ErrorManager; import org.openide.util.Cancellable; import org.openide.util.NbBundle; import org.openide.windows.IOProvider; import org.openide.windows.InputOutput; import org.openide.windows.TopComponent; import org.openide.windows.WindowManager; public abstract class AbstractNBTask extends Thread implements Cancellable, ITaskSupervisor { private AggregateProgressHandle progressHandle; protected ProgressContributor[] progressContribs; protected boolean cancelled = false; protected long start; protected boolean success = true; private InputOutput inputOutput; private PrintWriter out; private HashMap<String, Object> taskSettings = new HashMap<>(); private String timeMsg; private int contribCount = -1; private int counter = 0; private int logLevel = SUMMARY; private boolean logging = false; private boolean finished = false; public final static String SETTING_KEY_TASK_NAME = "TASK_NAME"; // NOI18N public final static String SETTING_KEY_TOTAL_ITEMS = "TOTAL_ITEMS"; // NOI18N public final static String SETTING_KEY_DISPLAY_OUTPUT = "DISPLAY_OUTPUT"; // NOI18N public AbstractNBTask() { } public AbstractNBTask(ITaskFinishListener listener) { addListener(listener); } public AbstractNBTask(HashMap settings) { taskSettings = settings; } public AbstractNBTask(HashMap settings, ITaskFinishListener listener) { taskSettings = settings; addListener(listener); } @Override public void run() { if (progressContribs != null && progressContribs.length > 0) { progressHandle = AggregateProgressFactory.createHandle( getTaskName(), progressContribs, this, null); } try { beginTask(); } catch (Exception e) { fail(); ErrorManager.getDefault().notify(e); } finally { finishTask(); progressHandle.finish(); } } @Override public boolean cancel() { cancelled = true; return true; } // methods that should be implemented or overriden by subclass ///////////////////////////////////////////////////////////////////// protected abstract void initTask(); protected abstract void begin(); protected abstract void finish(); /** * This method logs a "header" message. Override to replace this message * with a custom header message and invoke super to prepend or append to * this message. */ protected void beginLog() { } /** * This method logs the finish status message (success, fail or cancel) and * the run time stats. Override to replace this message with a custom header * message and invoke super to prepend or append to this message. */ protected void finishLog() { // there are some cases where the task "finish" gets called more than // once and we want to prevent the finish message from being displayed // more than once. if (finished) { return; } finished = true; log(SUMMARY); // NOI18N if (cancelled) { log(Console.wrap(NbBundle.getMessage( AbstractNBTask.class, "MSG_Report_Cancelled") + " " + // NOI18N NbBundle.getMessage( AbstractNBTask.class, "MSG_TotalTime", timeMsg), FG_DARK_RED)); // NOI18N } else if (success) { log(Console.wrap(NbBundle.getMessage( AbstractNBTask.class, "MSG_Report_Successful") + " " + // NOI18N NbBundle.getMessage( AbstractNBTask.class, "MSG_TotalTime", timeMsg), FG_GREEN)); // NOI18N } else { log(Console.wrap(NbBundle.getMessage( AbstractNBTask.class, "MSG_Report_Failed") + " " + // NOI18N NbBundle.getMessage( AbstractNBTask.class, "MSG_TotalTime", timeMsg), FG_DARK_RED)); // NOI18N } } /** * Provides tokenized defaults. Should be overriden by subclass or settings * values passed in by calling class. */ protected void initDefaultSettings() { taskSettings.put(SETTING_KEY_TASK_NAME, "<" + getBundleMessage("MSG_Default_Task_Name") + ">"); // NOI18N taskSettings.put(SETTING_KEY_TOTAL_ITEMS, -1); } // public methods that should be invoked by subclass //////////////////////////////////////////////////// @Override public boolean start(int totalItems) { return start(++contribCount, totalItems); } @Override public boolean start(int contributor, int totalItems) { if (contributor < 0 && contributor > progressContribs.length - 1) { finishTask(); return false; } if (contributor > 0) { progressContribs[contributor].finish(); } counter = 0; progressHandle.setDisplayName(getTaskName() + ": " + // NOI18N progressContribs[contributor].getTrackingId()); progressContribs[contributor].start(totalItems); return true; } @Override public int increment() { return ++counter; } @Override public int increment(int step) { counter += step; return counter; } /** * Called by task subclass to check confirm that the task hasn't been * cancelled or failed. If there is a cancellation or failure, finish() is * called. * * @return true if the process hasn't failed or been canceled */ @Override public boolean proceed() { return proceed(0); } /** * Called by task subclass to check confirm that the task hasn't been * cancelled or failed. If there is a cancellation or failure, finish() is * called. * * @param count the number of items processed so far; used for % done * calculation for the NB progress bar * * @param step the amount to increment the counter by. * * @return true if the process hasn't failed or been canceled */ @Override public boolean proceed(int step) { if (cancelled || !success) { progressContribs[contribCount].finish(); finishTask(); return false; } else if (counter > -1) { if (step > 0) { increment(step); } log(DEBUG, "count " + counter); progressContribs[contribCount].progress(counter); } return true; } public void setLogLevel(int level) { logLevel = level; } public int getLogLevel() { return logLevel; } public boolean isLogging() { return logging; } public void setLogging(boolean val) { logging = val; } /** * Outputs a blank line */ @Override public void log() { log("", true); } @Override public void log(int level) { if (logLevel < level) { return; } log("", true); } @Override public void log(int level, String msg) { if (logLevel < level) { return; } log(msg, true); } @Override public void log(int level, String msg, boolean newline) { if (logLevel < level) { return; } log(msg, newline); } /** * Outputs a message with and appends newline by default * * @param msg the message to be output */ @Override public void log(String msg) { log(msg, true); } /** * Outputs a message * * @param msg the message to be output * @param newline if true, appends newline */ @Override public void log(String msg, boolean newline) { if (newline) { out.println(msg); } else { out.print(msg); } out.flush(); } @Override public void log(String msg, int padding) { String messages[] = msg.split("\n"); log(messages[0], true); for(int i = 1 ; i< messages.length ; i++){ log(StringUtils.leftPad("\t" + messages[i], padding*2 - 1, ' '), true); // log("\t" + padLeft(messages[i], padding - 1), true); } } /** * Call this method when a failure in your task is detected and it will set * the success flag to false. The next time proceed() is called, it will * invoke finish() return false. */ @Override public void fail() { success = false; } // settings methods public String getTaskName() { return (String) getSetting(SETTING_KEY_TASK_NAME); } public void setTaskName(String taskName) { setSetting(SETTING_KEY_TASK_NAME, taskName); } public int getTotalItems() { Integer total = (Integer) getSetting(SETTING_KEY_TOTAL_ITEMS); if (total == null) { return -1; } return total; } public void setTotalItems(int total) { setSetting(SETTING_KEY_TOTAL_ITEMS, total); } public boolean isDisplayOutput() { Boolean show = (Boolean) getSetting(SETTING_KEY_DISPLAY_OUTPUT); if (show == null) { return true; } return show; } public void setDisplayOutput(boolean val) { setSetting(SETTING_KEY_DISPLAY_OUTPUT, val); } public Object getSetting(String key) { return taskSettings.get(key); } public void setSetting(String key, Object value) { taskSettings.put(key, value); } public void addListener(ITaskFinishListener listener) { if (!listeners.contains(listener)) { listeners.addElement(listener); } } public void removeListener(ITaskFinishListener listener) { listeners.removeElement(listener); } protected void initialize() { if (taskSettings == null) { initDefaultSettings(); } initTask(); initLog(); } private void initLog() { TopComponent tc = WindowManager.getDefault().findTopComponent("output"); // NOI18N if (tc != null && isDisplayOutput()) // NOI18N { tc.open(); tc.requestActive(); tc.toFront(); } inputOutput = IOProvider.getDefault().getIO(getTaskName(), false); // NOI18N try { inputOutput.getOut().reset(); out = inputOutput.getOut(); } catch (IOException e) { // TODO: ignore } if (isDisplayOutput()) // NOI18N { inputOutput.select(); inputOutput.setOutputVisible(true); } } private void beginTask() { if (getTotalItems() > -1) { progressHandle.start(getTotalItems()); } else { progressHandle.start(); } start = System.currentTimeMillis(); beginLog(); begin(); } private void finishTask() { progressContribs[progressContribs.length - 1].finish(); finish(); long total = (System.currentTimeMillis() - start) / 1000; int minutes = (int) total / 60; int seconds = (int) (total - minutes * 60); timeMsg = minutes == 0 ? seconds + " " + getBundleMessage("MSG_Seconds") // NOI18N : minutes + " " + getBundleMessage("MSG_Minutes") + // NOI18N " " + seconds + " " + getBundleMessage("MSG_Seconds"); // NOI18N finishLog(); inputOutput.getOut().flush(); inputOutput.getOut().close(); out.close(); notifyTaskFinishListeners(); } // bundle message helper methods private String getBundleMessage(String key) { return NbBundle.getMessage(AbstractNBTask.class, key); } private String getBundleMessage(String key, Object[] params) { return NbBundle.getMessage(AbstractNBTask.class, key, params); } private String getBundleMessage(String key, Object param) { return NbBundle.getMessage(AbstractNBTask.class, key, param); } private String getBundleMessage(String key, Object param, Object param0) { return NbBundle.getMessage(AbstractNBTask.class, key, param, param0); } private String getBundleMessage( String key, Object param, Object param0, Object param1) { return NbBundle.getMessage( AbstractNBTask.class, key, param, param0, param1); } private Vector<ITaskFinishListener> listeners = new Vector<>(); private void notifyTaskFinishListeners() { for (ITaskFinishListener listener : listeners) { listener.taskFinished(); } } }
9240e9e4e5403b82295205ec2b416aed7ad2f5fc
1,166
java
Java
src/main/java/frc/robot/commands/auto/AutonTurnCom.java
2130-Programmers/SwerveDrive2022
0801628de5bba9c024f4da0ce4ca0aefff2c034c
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/auto/AutonTurnCom.java
2130-Programmers/SwerveDrive2022
0801628de5bba9c024f4da0ce4ca0aefff2c034c
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/commands/auto/AutonTurnCom.java
2130-Programmers/SwerveDrive2022
0801628de5bba9c024f4da0ce4ca0aefff2c034c
[ "BSD-3-Clause" ]
1
2022-03-19T18:33:24.000Z
2022-03-19T18:33:24.000Z
26.5
73
0.722127
1,001,715
package frc.robot.commands.auto; import edu.wpi.first.wpilibj2.command.CommandBase; import frc.robot.RobotContainer; import frc.robot.subsystems.DriveTrain; public class AutonTurnCom extends CommandBase { /** Creates a new AutonTurnCom. */ private DriveTrain driveTrain; private int direction; /** * * * @param driveTrain - drivetrain * @param direction - (int) left is 1, straight is 2, right is 3 */ public AutonTurnCom(DriveTrain driveTrain, int direction) { this.driveTrain = driveTrain; this.direction = direction; addRequirements(driveTrain); // Use addRequirements() here to declare subsystem dependencies. } // Called when the command is initially scheduled. @Override public void initialize() {} // Called every time the scheduler runs while the command is scheduled. @Override public void execute() { driveTrain.autonTurn(direction); } // Called once the command ends or is interrupted. @Override public void end(boolean interrupted) {} // Returns true when the command should end. @Override public boolean isFinished() { return RobotContainer.photonSub.hasTarget; } }
9240eab5753e3f7058ad5b067d1f71bb27a0073a
356
java
Java
stella-nfe/src/main/java/br/com/caelum/stella/nfe/fluid/converter/CPFToStringConverter.java
steppat/caelum-stella
4d2ae1394f174a4c34872137b188d5d482895ca5
[ "Apache-2.0" ]
1
2021-02-26T00:21:33.000Z
2021-02-26T00:21:33.000Z
stella-nfe/src/main/java/br/com/caelum/stella/nfe/fluid/converter/CPFToStringConverter.java
steppat/caelum-stella
4d2ae1394f174a4c34872137b188d5d482895ca5
[ "Apache-2.0" ]
null
null
null
stella-nfe/src/main/java/br/com/caelum/stella/nfe/fluid/converter/CPFToStringConverter.java
steppat/caelum-stella
4d2ae1394f174a4c34872137b188d5d482895ca5
[ "Apache-2.0" ]
null
null
null
20.941176
79
0.735955
1,001,716
package br.com.caelum.stella.nfe.fluid.converter; import net.vidageek.fluid.proxy.converter.DataConverter; import br.com.caelum.stella.tinytype.CPF; /** * @author jonasabreu * */ final public class CPFToStringConverter implements DataConverter<CPF, String> { public String convert(final CPF object) { return object.getNumero(); } }
9240eb7edf65aade9a4e4abc9dbbf7c0d7f7ef20
785
java
Java
test/com/facebook/buck/jvm/java/testdata/missing_test_deps/UsesNullable.java
fkorotkov/buck
4d63790ceda1028281600af9cf75153ccb92a5f5
[ "Apache-2.0" ]
8,027
2015-01-02T05:31:44.000Z
2022-03-31T07:08:09.000Z
test/com/facebook/buck/jvm/java/testdata/missing_test_deps/UsesNullable.java
fkorotkov/buck
4d63790ceda1028281600af9cf75153ccb92a5f5
[ "Apache-2.0" ]
2,355
2015-01-01T15:30:53.000Z
2022-03-30T20:21:16.000Z
test/com/facebook/buck/jvm/java/testdata/missing_test_deps/UsesNullable.java
fkorotkov/buck
4d63790ceda1028281600af9cf75153ccb92a5f5
[ "Apache-2.0" ]
1,280
2015-01-09T03:29:04.000Z
2022-03-30T15:14:14.000Z
29.074074
76
0.745223
1,001,717
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.example; import javax.annotation.Nullable; public class UsesNullable { @Nullable private String foobar; public void testSomethingMagical() {} }
9240ec0b2ab79db520612baebe3f92de34b4ea9c
26,275
java
Java
app/src/main/java/com/facebook/FacebookSdk.java
renyuanceshi/KingKingRE
b15295bec2cee47867b786dbe0841c1a4edaff5e
[ "Unlicense" ]
null
null
null
app/src/main/java/com/facebook/FacebookSdk.java
renyuanceshi/KingKingRE
b15295bec2cee47867b786dbe0841c1a4edaff5e
[ "Unlicense" ]
null
null
null
app/src/main/java/com/facebook/FacebookSdk.java
renyuanceshi/KingKingRE
b15295bec2cee47867b786dbe0841c1a4edaff5e
[ "Unlicense" ]
null
null
null
45.458478
228
0.625347
1,001,718
package com.facebook; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.Signature; import android.os.AsyncTask; import android.support.v4.media.session.PlaybackStateCompat; import android.util.Base64; import android.util.Log; import com.facebook.appevents.AppEventsLogger; import com.facebook.internal.BoltsMeasurementEventListener; import com.facebook.internal.FetchedAppSettingsManager; import com.facebook.internal.LockOnGetVariable; import com.facebook.internal.NativeProtocol; import com.facebook.internal.ServerProtocol; import com.facebook.internal.Utility; import com.facebook.internal.Validate; import java.io.File; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Locale; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; public final class FacebookSdk { public static final String APPLICATION_ID_PROPERTY = "com.facebook.sdk.ApplicationId"; public static final String APPLICATION_NAME_PROPERTY = "com.facebook.sdk.ApplicationName"; private static final String ATTRIBUTION_PREFERENCES = "com.facebook.sdk.attributionTracking"; public static final String AUTO_LOG_APP_EVENTS_ENABLED_PROPERTY = "com.facebook.sdk.AutoLogAppEventsEnabled"; static final String CALLBACK_OFFSET_CHANGED_AFTER_INIT = "The callback request code offset can't be updated once the SDK is initialized. Call FacebookSdk.setCallbackRequestCodeOffset inside your Application.onCreate method"; static final String CALLBACK_OFFSET_NEGATIVE = "The callback request code offset can't be negative."; public static final String CALLBACK_OFFSET_PROPERTY = "com.facebook.sdk.CallbackOffset"; public static final String CLIENT_TOKEN_PROPERTY = "com.facebook.sdk.ClientToken"; private static final int DEFAULT_CALLBACK_REQUEST_CODE_OFFSET = 64206; private static final int DEFAULT_CORE_POOL_SIZE = 5; private static final int DEFAULT_KEEP_ALIVE = 1; private static final int DEFAULT_MAXIMUM_POOL_SIZE = 128; private static final int DEFAULT_THEME = R.style.com_facebook_activity_theme; private static final ThreadFactory DEFAULT_THREAD_FACTORY = new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(0); public Thread newThread(Runnable runnable) { return new Thread(runnable, "FacebookSdk #" + this.counter.incrementAndGet()); } }; private static final BlockingQueue<Runnable> DEFAULT_WORK_QUEUE = new LinkedBlockingQueue(10); private static final String FACEBOOK_COM = "facebook.com"; private static final Object LOCK = new Object(); private static final int MAX_REQUEST_CODE_RANGE = 100; private static final String PUBLISH_ACTIVITY_PATH = "%s/activities"; private static final String TAG = FacebookSdk.class.getCanonicalName(); public static final String WEB_DIALOG_THEME = "com.facebook.sdk.WebDialogTheme"; private static volatile String appClientToken; /* access modifiers changed from: private */ public static Context applicationContext; private static volatile String applicationId; private static volatile String applicationName; private static volatile Boolean autoLogAppEventsEnabled; private static LockOnGetVariable<File> cacheDir; private static int callbackRequestCodeOffset = DEFAULT_CALLBACK_REQUEST_CODE_OFFSET; private static Executor executor; private static volatile String facebookDomain = FACEBOOK_COM; private static String graphApiVersion = ServerProtocol.getDefaultAPIVersion(); private static volatile boolean isDebugEnabled = false; private static boolean isLegacyTokenUpgradeSupported = false; private static final HashSet<LoggingBehavior> loggingBehaviors = new HashSet<>(Arrays.asList(new LoggingBehavior[]{LoggingBehavior.DEVELOPER_ERRORS})); private static AtomicLong onProgressThreshold = new AtomicLong(PlaybackStateCompat.ACTION_PREPARE_FROM_SEARCH); private static Boolean sdkInitialized = false; private static volatile int webDialogTheme; public interface InitializeCallback { void onInitialized(); } public static void addLoggingBehavior(LoggingBehavior loggingBehavior) { synchronized (loggingBehaviors) { loggingBehaviors.add(loggingBehavior); updateGraphDebugBehavior(); } } public static void clearLoggingBehaviors() { synchronized (loggingBehaviors) { loggingBehaviors.clear(); } } public static Context getApplicationContext() { Validate.sdkInitialized(); return applicationContext; } public static String getApplicationId() { Validate.sdkInitialized(); return applicationId; } public static String getApplicationName() { Validate.sdkInitialized(); return applicationName; } public static String getApplicationSignature(Context context) { PackageManager packageManager; Validate.sdkInitialized(); if (context == null || (packageManager = context.getPackageManager()) == null) { return null; } try { PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 64); Signature[] signatureArr = packageInfo.signatures; if (signatureArr == null || signatureArr.length == 0) { return null; } try { MessageDigest instance = MessageDigest.getInstance("SHA-1"); instance.update(packageInfo.signatures[0].toByteArray()); return Base64.encodeToString(instance.digest(), 9); } catch (NoSuchAlgorithmException e) { return null; } } catch (PackageManager.NameNotFoundException e2) { return null; } } public static boolean getAutoLogAppEventsEnabled() { Validate.sdkInitialized(); return autoLogAppEventsEnabled.booleanValue(); } public static File getCacheDir() { Validate.sdkInitialized(); return cacheDir.getValue(); } public static int getCallbackRequestCodeOffset() { Validate.sdkInitialized(); return callbackRequestCodeOffset; } public static String getClientToken() { Validate.sdkInitialized(); return appClientToken; } public static Executor getExecutor() { synchronized (LOCK) { if (executor == null) { executor = AsyncTask.THREAD_POOL_EXECUTOR; } } return executor; } public static String getFacebookDomain() { return facebookDomain; } public static String getGraphApiVersion() { return graphApiVersion; } public static boolean getLimitEventAndDataUsage(Context context) { Validate.sdkInitialized(); return context.getSharedPreferences(AppEventsLogger.APP_EVENT_PREFERENCES, 0).getBoolean("limitEventUsage", false); } public static Set<LoggingBehavior> getLoggingBehaviors() { Set<LoggingBehavior> unmodifiableSet; synchronized (loggingBehaviors) { unmodifiableSet = Collections.unmodifiableSet(new HashSet(loggingBehaviors)); } return unmodifiableSet; } public static long getOnProgressThreshold() { Validate.sdkInitialized(); return onProgressThreshold.get(); } public static String getSdkVersion() { return FacebookSdkVersion.BUILD; } public static int getWebDialogTheme() { Validate.sdkInitialized(); return webDialogTheme; } public static boolean isDebugEnabled() { return isDebugEnabled; } public static boolean isFacebookRequestCode(int i) { return i >= callbackRequestCodeOffset && i < callbackRequestCodeOffset + 100; } public static boolean isInitialized() { boolean booleanValue; synchronized (FacebookSdk.class) { try { booleanValue = sdkInitialized.booleanValue(); } catch (Throwable th) { Class<FacebookSdk> cls = FacebookSdk.class; throw th; } } return booleanValue; } public static boolean isLegacyTokenUpgradeSupported() { return isLegacyTokenUpgradeSupported; } public static boolean isLoggingBehaviorEnabled(LoggingBehavior loggingBehavior) { boolean z; synchronized (loggingBehaviors) { z = isDebugEnabled() && loggingBehaviors.contains(loggingBehavior); } return z; } static void loadDefaultsFromMetadata(Context context) { if (context != null) { try { ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 128); if (applicationInfo != null && applicationInfo.metaData != null) { if (applicationId == null) { Object obj = applicationInfo.metaData.get(APPLICATION_ID_PROPERTY); if (obj instanceof String) { String str = (String) obj; if (str.toLowerCase(Locale.ROOT).startsWith("fb")) { applicationId = str.substring(2); } else { applicationId = str; } } else if (obj instanceof Integer) { throw new FacebookException("App Ids cannot be directly placed in the manifest.They must be prefixed by 'fb' or be placed in the string resource file."); } } if (applicationName == null) { applicationName = applicationInfo.metaData.getString(APPLICATION_NAME_PROPERTY); } if (appClientToken == null) { appClientToken = applicationInfo.metaData.getString(CLIENT_TOKEN_PROPERTY); } if (webDialogTheme == 0) { setWebDialogTheme(applicationInfo.metaData.getInt(WEB_DIALOG_THEME)); } if (callbackRequestCodeOffset == DEFAULT_CALLBACK_REQUEST_CODE_OFFSET) { callbackRequestCodeOffset = applicationInfo.metaData.getInt(CALLBACK_OFFSET_PROPERTY, DEFAULT_CALLBACK_REQUEST_CODE_OFFSET); } if (autoLogAppEventsEnabled == null) { autoLogAppEventsEnabled = Boolean.valueOf(applicationInfo.metaData.getBoolean(AUTO_LOG_APP_EVENTS_ENABLED_PROPERTY, true)); } } } catch (PackageManager.NameNotFoundException e) { } } } /* JADX WARNING: Code restructure failed: missing block: B:24:0x00a6, code lost: r0 = move-exception; */ /* JADX WARNING: Code restructure failed: missing block: B:26:0x00ae, code lost: throw new com.facebook.FacebookException("An error occurred while publishing install.", (java.lang.Throwable) r0); */ /* JADX WARNING: Code restructure failed: missing block: B:35:?, code lost: return new com.facebook.GraphResponse((com.facebook.GraphRequest) null, (java.net.HttpURLConnection) null, new com.facebook.FacebookRequestError((java.net.HttpURLConnection) null, r1)); */ /* JADX WARNING: Code restructure failed: missing block: B:6:0x000f, code lost: r0 = move-exception; */ /* JADX WARNING: Code restructure failed: missing block: B:7:0x0010, code lost: r1 = r0; com.facebook.internal.Utility.logd("Facebook-publish", r1); */ /* JADX WARNING: Exception block dominator not found, dom blocks: [B:3:0x0007, B:10:0x005d] */ /* Code decompiled incorrectly, please refer to instructions dump. */ static com.facebook.GraphResponse publishInstallAndWaitForResponse(android.content.Context r14, java.lang.String r15) { /* r12 = 0 r2 = 0 if (r14 == 0) goto L_0x0007 if (r15 != 0) goto L_0x0021 L_0x0007: java.lang.IllegalArgumentException r0 = new java.lang.IllegalArgumentException // Catch:{ Exception -> 0x000f } java.lang.String r1 = "Both context and applicationId must be non-null" r0.<init>(r1) // Catch:{ Exception -> 0x000f } throw r0 // Catch:{ Exception -> 0x000f } L_0x000f: r0 = move-exception r1 = r0 java.lang.String r0 = "Facebook-publish" com.facebook.internal.Utility.logd((java.lang.String) r0, (java.lang.Exception) r1) com.facebook.GraphResponse r0 = new com.facebook.GraphResponse com.facebook.FacebookRequestError r3 = new com.facebook.FacebookRequestError r3.<init>((java.net.HttpURLConnection) r2, (java.lang.Exception) r1) r0.<init>(r2, r2, r3) L_0x0020: return r0 L_0x0021: com.facebook.internal.AttributionIdentifiers r0 = com.facebook.internal.AttributionIdentifiers.getAttributionIdentifiers(r14) // Catch:{ Exception -> 0x000f } java.lang.String r1 = "com.facebook.sdk.attributionTracking" r3 = 0 android.content.SharedPreferences r1 = r14.getSharedPreferences(r1, r3) // Catch:{ Exception -> 0x000f } java.lang.StringBuilder r3 = new java.lang.StringBuilder // Catch:{ Exception -> 0x000f } r3.<init>() // Catch:{ Exception -> 0x000f } java.lang.StringBuilder r3 = r3.append(r15) // Catch:{ Exception -> 0x000f } java.lang.String r4 = "ping" java.lang.StringBuilder r3 = r3.append(r4) // Catch:{ Exception -> 0x000f } java.lang.String r3 = r3.toString() // Catch:{ Exception -> 0x000f } java.lang.StringBuilder r4 = new java.lang.StringBuilder // Catch:{ Exception -> 0x000f } r4.<init>() // Catch:{ Exception -> 0x000f } java.lang.StringBuilder r4 = r4.append(r15) // Catch:{ Exception -> 0x000f } java.lang.String r5 = "json" java.lang.StringBuilder r4 = r4.append(r5) // Catch:{ Exception -> 0x000f } java.lang.String r4 = r4.toString() // Catch:{ Exception -> 0x000f } r6 = 0 long r6 = r1.getLong(r3, r6) // Catch:{ Exception -> 0x000f } r5 = 0 java.lang.String r5 = r1.getString(r4, r5) // Catch:{ Exception -> 0x000f } com.facebook.internal.AppEventsLoggerUtility$GraphAPIActivityType r8 = com.facebook.internal.AppEventsLoggerUtility.GraphAPIActivityType.MOBILE_INSTALL_EVENT // Catch:{ JSONException -> 0x00a6 } java.lang.String r9 = com.facebook.appevents.AppEventsLogger.getAnonymousAppDeviceGUID(r14) // Catch:{ JSONException -> 0x00a6 } boolean r10 = getLimitEventAndDataUsage(r14) // Catch:{ JSONException -> 0x00a6 } org.json.JSONObject r0 = com.facebook.internal.AppEventsLoggerUtility.getJSONObjectForGraphAPICall(r8, r0, r9, r10, r14) // Catch:{ JSONException -> 0x00a6 } r8 = 0 java.lang.String r9 = "%s/activities" r10 = 1 java.lang.Object[] r10 = new java.lang.Object[r10] // Catch:{ Exception -> 0x000f } r11 = 0 r10[r11] = r15 // Catch:{ Exception -> 0x000f } java.lang.String r9 = java.lang.String.format(r9, r10) // Catch:{ Exception -> 0x000f } r10 = 0 com.facebook.GraphRequest r8 = com.facebook.GraphRequest.newPostRequest(r8, r9, r0, r10) // Catch:{ Exception -> 0x000f } int r0 = (r6 > r12 ? 1 : (r6 == r12 ? 0 : -1)) if (r0 == 0) goto L_0x00b9 if (r5 == 0) goto L_0x00e1 org.json.JSONObject r0 = new org.json.JSONObject // Catch:{ JSONException -> 0x00de } r0.<init>(r5) // Catch:{ JSONException -> 0x00de } r1 = r0 L_0x0089: if (r1 != 0) goto L_0x00af com.facebook.GraphRequestBatch r0 = new com.facebook.GraphRequestBatch // Catch:{ Exception -> 0x000f } r1 = 1 com.facebook.GraphRequest[] r1 = new com.facebook.GraphRequest[r1] // Catch:{ Exception -> 0x000f } r3 = 0 r1[r3] = r8 // Catch:{ Exception -> 0x000f } r0.<init>((com.facebook.GraphRequest[]) r1) // Catch:{ Exception -> 0x000f } java.lang.String r1 = "true" r3 = 0 java.util.List r0 = com.facebook.GraphResponse.createResponsesFromString(r1, r3, r0) // Catch:{ Exception -> 0x000f } r1 = 0 java.lang.Object r0 = r0.get(r1) // Catch:{ Exception -> 0x000f } com.facebook.GraphResponse r0 = (com.facebook.GraphResponse) r0 // Catch:{ Exception -> 0x000f } goto L_0x0020 L_0x00a6: r0 = move-exception com.facebook.FacebookException r1 = new com.facebook.FacebookException // Catch:{ Exception -> 0x000f } java.lang.String r3 = "An error occurred while publishing install." r1.<init>((java.lang.String) r3, (java.lang.Throwable) r0) // Catch:{ Exception -> 0x000f } throw r1 // Catch:{ Exception -> 0x000f } L_0x00af: com.facebook.GraphResponse r0 = new com.facebook.GraphResponse // Catch:{ Exception -> 0x000f } r3 = 0 r4 = 0 r5 = 0 r0.<init>((com.facebook.GraphRequest) r3, (java.net.HttpURLConnection) r4, (java.lang.String) r5, (org.json.JSONObject) r1) // Catch:{ Exception -> 0x000f } goto L_0x0020 L_0x00b9: com.facebook.GraphResponse r0 = r8.executeAndWait() // Catch:{ Exception -> 0x000f } android.content.SharedPreferences$Editor r1 = r1.edit() // Catch:{ Exception -> 0x000f } long r6 = java.lang.System.currentTimeMillis() // Catch:{ Exception -> 0x000f } r1.putLong(r3, r6) // Catch:{ Exception -> 0x000f } org.json.JSONObject r3 = r0.getJSONObject() // Catch:{ Exception -> 0x000f } if (r3 == 0) goto L_0x00d9 org.json.JSONObject r3 = r0.getJSONObject() // Catch:{ Exception -> 0x000f } java.lang.String r3 = r3.toString() // Catch:{ Exception -> 0x000f } r1.putString(r4, r3) // Catch:{ Exception -> 0x000f } L_0x00d9: r1.apply() // Catch:{ Exception -> 0x000f } goto L_0x0020 L_0x00de: r0 = move-exception r1 = r2 goto L_0x0089 L_0x00e1: r1 = r2 goto L_0x0089 */ throw new UnsupportedOperationException("Method not decompiled: com.facebook.FacebookSdk.publishInstallAndWaitForResponse(android.content.Context, java.lang.String):com.facebook.GraphResponse"); } public static void publishInstallAsync(Context context, final String str) { final Context applicationContext2 = context.getApplicationContext(); getExecutor().execute(new Runnable() { public void run() { FacebookSdk.publishInstallAndWaitForResponse(applicationContext2, str); } }); } public static void removeLoggingBehavior(LoggingBehavior loggingBehavior) { synchronized (loggingBehaviors) { loggingBehaviors.remove(loggingBehavior); } } @Deprecated public static void sdkInitialize(Context context) { synchronized (FacebookSdk.class) { try { sdkInitialize(context, (InitializeCallback) null); } catch (Throwable th) { Class<FacebookSdk> cls = FacebookSdk.class; throw th; } } } @Deprecated public static void sdkInitialize(Context context, int i) { synchronized (FacebookSdk.class) { try { sdkInitialize(context, i, (InitializeCallback) null); } catch (Throwable th) { Class<FacebookSdk> cls = FacebookSdk.class; throw th; } } } @Deprecated public static void sdkInitialize(Context context, int i, InitializeCallback initializeCallback) { synchronized (FacebookSdk.class) { try { if (sdkInitialized.booleanValue() && i != callbackRequestCodeOffset) { throw new FacebookException(CALLBACK_OFFSET_CHANGED_AFTER_INIT); } else if (i < 0) { throw new FacebookException(CALLBACK_OFFSET_NEGATIVE); } else { callbackRequestCodeOffset = i; sdkInitialize(context, initializeCallback); } } catch (Throwable th) { Class<FacebookSdk> cls = FacebookSdk.class; throw th; } } } @Deprecated public static void sdkInitialize(final Context context, final InitializeCallback initializeCallback) { synchronized (FacebookSdk.class) { try { if (!sdkInitialized.booleanValue()) { Validate.notNull(context, "applicationContext"); Validate.hasFacebookActivity(context, false); Validate.hasInternetPermissions(context, false); applicationContext = context.getApplicationContext(); loadDefaultsFromMetadata(applicationContext); if (Utility.isNullOrEmpty(applicationId)) { throw new FacebookException("A valid Facebook app id must be set in the AndroidManifest.xml or set by calling FacebookSdk.setApplicationId before initializing the sdk."); } sdkInitialized = true; FetchedAppSettingsManager.loadAppSettingsAsync(); NativeProtocol.updateAllAvailableProtocolVersionsAsync(); BoltsMeasurementEventListener.getInstance(applicationContext); cacheDir = new LockOnGetVariable<>(new Callable<File>() { public File call() throws Exception { return FacebookSdk.applicationContext.getCacheDir(); } }); getExecutor().execute(new FutureTask(new Callable<Void>() { public Void call() throws Exception { AccessTokenManager.getInstance().loadCurrentAccessToken(); ProfileManager.getInstance().loadCurrentProfile(); if (AccessToken.getCurrentAccessToken() != null && Profile.getCurrentProfile() == null) { Profile.fetchProfileForCurrentAccessToken(); } if (initializeCallback != null) { initializeCallback.onInitialized(); } AppEventsLogger.newLogger(context.getApplicationContext()).flush(); return null; } })); } else if (initializeCallback != null) { initializeCallback.onInitialized(); } } catch (Throwable th) { Class<FacebookSdk> cls = FacebookSdk.class; throw th; } } } public static void setApplicationId(String str) { applicationId = str; } public static void setApplicationName(String str) { applicationName = str; } public static void setAutoLogAppEventsEnabled(boolean z) { autoLogAppEventsEnabled = Boolean.valueOf(z); } public static void setCacheDir(File file) { cacheDir = new LockOnGetVariable<>(file); } public static void setClientToken(String str) { appClientToken = str; } public static void setExecutor(Executor executor2) { Validate.notNull(executor2, "executor"); synchronized (LOCK) { executor = executor2; } } public static void setFacebookDomain(String str) { Log.w(TAG, "WARNING: Calling setFacebookDomain from non-DEBUG code."); facebookDomain = str; } public static void setGraphApiVersion(String str) { if (!Utility.isNullOrEmpty(str) && !graphApiVersion.equals(str)) { graphApiVersion = str; } } public static void setIsDebugEnabled(boolean z) { isDebugEnabled = z; } public static void setLegacyTokenUpgradeSupported(boolean z) { isLegacyTokenUpgradeSupported = z; } public static void setLimitEventAndDataUsage(Context context, boolean z) { context.getSharedPreferences(AppEventsLogger.APP_EVENT_PREFERENCES, 0).edit().putBoolean("limitEventUsage", z).apply(); } public static void setOnProgressThreshold(long j) { onProgressThreshold.set(j); } public static void setWebDialogTheme(int i) { if (i == 0) { i = DEFAULT_THEME; } webDialogTheme = i; } private static void updateGraphDebugBehavior() { if (loggingBehaviors.contains(LoggingBehavior.GRAPH_API_DEBUG_INFO) && !loggingBehaviors.contains(LoggingBehavior.GRAPH_API_DEBUG_WARNING)) { loggingBehaviors.add(LoggingBehavior.GRAPH_API_DEBUG_WARNING); } } }
9240ec685d18df68f5e144f8043b2d7f56d278bf
1,736
java
Java
src/company/RestoreIPAddresses.java
chenwenhang/AlgorithmPractice-
e35b18094d4bf25d4e4065d5bc9a611009aff233
[ "MIT" ]
5
2019-10-25T08:51:06.000Z
2021-04-18T23:54:11.000Z
src/company/RestoreIPAddresses.java
chenwenhang/AlgorithmPractice-
e35b18094d4bf25d4e4065d5bc9a611009aff233
[ "MIT" ]
null
null
null
src/company/RestoreIPAddresses.java
chenwenhang/AlgorithmPractice-
e35b18094d4bf25d4e4065d5bc9a611009aff233
[ "MIT" ]
1
2019-11-04T07:48:06.000Z
2019-11-04T07:48:06.000Z
25.529412
90
0.421659
1,001,719
package company; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.stream.Stream; /** * @Author: Wenhang Chen * @Description:给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。 * <p> * 示例: * <p> * 输入: "25525511135" * 输出: ["255.255.11.135", "255.255.111.35"] * @Date: Created in 17:24 2/7/2020 * @Modified by: */ public class RestoreIPAddresses { public List<String> restoreIpAddresses(String s) { List<String> ret = new ArrayList<>(); StringBuilder ip = new StringBuilder(); // 四层for循环解千愁 for (int a = 1; a < 4; ++a) for (int b = 1; b < 4; ++b) for (int c = 1; c < 4; ++c) for (int d = 1; d < 4; ++d) { if (a + b + c + d == s.length()) { // 截取一段,转为数字 int n1 = Integer.parseInt(s.substring(0, a)); int n2 = Integer.parseInt(s.substring(a, a + b)); int n3 = Integer.parseInt(s.substring(a + b, a + b + c)); int n4 = Integer.parseInt(s.substring(a + b + c)); if (n1 <= 255 && n2 <= 255 && n3 <= 255 && n4 <= 255) { ip.append(n1).append('.').append(n2) .append('.').append(n3).append('.').append(n4); // 防止出现形如 01 被解析为 1 的情况,以 0 开头的那段必定为 0 if (ip.length() == s.length() + 3) ret.add(ip.toString()); ip.delete(0, ip.length()); } } } return ret; } }
9240effb8203d7e66d8291c949396d6c752098ee
1,456
java
Java
src/com/booksaw/betterTeams/commands/teama/chest/ChestDisableClaims.java
megargayu/BetterTeams
6e550b93bbc2b8b87dc8fa6dd9c7fe7b2878bf76
[ "MIT" ]
22
2020-07-12T10:42:39.000Z
2022-03-14T03:20:35.000Z
src/com/booksaw/betterTeams/commands/teama/chest/ChestDisableClaims.java
megargayu/BetterTeams
6e550b93bbc2b8b87dc8fa6dd9c7fe7b2878bf76
[ "MIT" ]
306
2020-06-05T04:52:06.000Z
2022-03-29T13:09:13.000Z
src/com/booksaw/betterTeams/commands/teama/chest/ChestDisableClaims.java
megargayu/BetterTeams
6e550b93bbc2b8b87dc8fa6dd9c7fe7b2878bf76
[ "MIT" ]
29
2020-10-06T16:56:59.000Z
2022-03-03T19:13:32.000Z
24.266667
133
0.76511
1,001,720
package com.booksaw.betterTeams.commands.teama.chest; import com.booksaw.betterTeams.CommandResponse; import com.booksaw.betterTeams.commands.SubCommand; import com.booksaw.betterTeams.events.ChestManagement; import com.booksaw.betterTeams.message.MessageManager; import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import java.util.List; public class ChestDisableClaims extends SubCommand { @Override public CommandResponse onCommand(CommandSender sender, String label, String[] args) { if (!ChestManagement.enableClaims) { return new CommandResponse("admin.chest.disable.already"); } ChestManagement.enableClaims = false; Bukkit.broadcastMessage(MessageManager.getPrefix() + MessageManager.getMessage("admin.chest.disabled.bc")); return new CommandResponse("admin.chest.disable.success"); } @Override public String getCommand() { return "disableclaims"; } @Override public String getNode() { return "admin.chest.disable"; } @Override public String getHelp() { return "Disable all chest claims for a period of time (either until '/teama chest enableclaims' is run or the server is restarted"; } @Override public String getArguments() { return ""; } @Override public int getMinimumArguments() { return 0; } @Override public int getMaximumArguments() { return 0; } @Override public void onTabComplete(List<String> options, CommandSender sender, String label, String[] args) { } }
9240f18b5ef3df3aba1fd7e5ec128d60e9a25303
652
java
Java
src/main/java/com/orbitrondev/Entity/ChatType.java
D3strukt0r/chat
2d51df8cfe3133804baf15cdd6018b78da8c9cc6
[ "MIT" ]
1
2019-12-14T09:50:54.000Z
2019-12-14T09:50:54.000Z
src/main/java/com/orbitrondev/Entity/ChatType.java
D3strukt0r/chat
2d51df8cfe3133804baf15cdd6018b78da8c9cc6
[ "MIT" ]
null
null
null
src/main/java/com/orbitrondev/Entity/ChatType.java
D3strukt0r/chat
2d51df8cfe3133804baf15cdd6018b78da8c9cc6
[ "MIT" ]
null
null
null
21.733333
50
0.516871
1,001,721
package com.orbitrondev.Entity; /** * An enum defining the different chat types. * * @author Manuele Vaccari * @version %I%, %G% * @since 0.0.1 */ public enum ChatType { DirectChat, PublicGroupChat, PrivateGroupChat; @Override public String toString() { String type = ""; switch (this) { case DirectChat: type = "DirectChat"; break; case PublicGroupChat: type = "PublicGroupChat"; break; case PrivateGroupChat: type = "PrivateGroupChat"; break; } return type; } }
9240f2436692aa97730214f71bccf1dc4faeaa41
897
java
Java
batik/src/main/java/org/jdesktop/swingx/plaf/JXMultiThumbSliderAddon.java
zhangdan660/jgdraw
7762908477af1c4bb56f73a6789342bbea810a6a
[ "Apache-2.0" ]
null
null
null
batik/src/main/java/org/jdesktop/swingx/plaf/JXMultiThumbSliderAddon.java
zhangdan660/jgdraw
7762908477af1c4bb56f73a6789342bbea810a6a
[ "Apache-2.0" ]
null
null
null
batik/src/main/java/org/jdesktop/swingx/plaf/JXMultiThumbSliderAddon.java
zhangdan660/jgdraw
7762908477af1c4bb56f73a6789342bbea810a6a
[ "Apache-2.0" ]
null
null
null
24.916667
86
0.690078
1,001,722
/* * JXMultiThumbSliderAddon.java * * Created on May 9, 2006, 4:19 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package org.jdesktop.swingx.plaf; import java.util.Arrays; import java.util.List; import org.jdesktop.swingx.JXMultiThumbSlider; /** * * @author jm158417 */ public class JXMultiThumbSliderAddon extends AbstractComponentAddon { /** Creates a new instance of JXMultiThumbSliderAddon */ public JXMultiThumbSliderAddon() { super("JXMultiThumbSliderAddon"); } @Override protected void addBasicDefaults(LookAndFeelAddons addon, List<Object> defaults) { defaults.addAll(Arrays.asList(new Object[] { defaults.add(JXMultiThumbSlider.uiClassID), defaults.add("org.jdesktop.swingx.plaf.basic.BasicMultiThumbSliderUI") })); } }
9240f3af2ec8f5a22d2e33e3f63941e0e79605b7
1,987
java
Java
BookShop/src/main/java/com/lv/service/UserServiceImpl.java
superdoog/lvsihao-126.com
cbdebf719bdb7e959f311cbea0f810ad7f2b775f
[ "Apache-2.0" ]
4
2020-09-02T06:43:37.000Z
2021-12-18T05:16:33.000Z
BookShop/src/main/java/com/lv/service/UserServiceImpl.java
superdoog/lvsihao-126.com
cbdebf719bdb7e959f311cbea0f810ad7f2b775f
[ "Apache-2.0" ]
null
null
null
BookShop/src/main/java/com/lv/service/UserServiceImpl.java
superdoog/lvsihao-126.com
cbdebf719bdb7e959f311cbea0f810ad7f2b775f
[ "Apache-2.0" ]
2
2020-12-22T15:25:41.000Z
2021-04-02T00:17:13.000Z
21.597826
68
0.552089
1,001,723
package com.lv.service; import com.lv.mapper.UserMapper; import com.lv.pojo.User; import org.springframework.stereotype.Service; import javax.annotation.Resource; import java.util.List; /** * @author lv */ @Service public class UserServiceImpl implements UserService { @Resource private UserMapper userMapper; @Override public List<User> findAllUser(int currentPage, int pageSize) { List<User> users = null; //换算索引 int currentPageNo = (currentPage - 1) * pageSize; try { users = userMapper.findAllUser(currentPageNo, pageSize); } catch (Exception e) { e.printStackTrace(); } return users; } @Override public int addUser(User user) { return userMapper.insert(user); } @Override public int getCount() { int count = 0; try { count = userMapper.getCount(); } catch (Exception e) { e.printStackTrace(); } return count; } @Override public int deleteByuid(int uid) { int flag = 0; try { flag = userMapper.deleteByuid(uid); } catch (Exception e) { e.printStackTrace(); } return flag; } @Override public User getUserById(int uid) { User user = null; try { user = userMapper.getUserById(uid); } catch (Exception e) { e.printStackTrace(); } return user; } @Override public User getUserByuname(String uname) { User user = null; try { user = userMapper.getUserByuname(uname); } catch (Exception e) { e.printStackTrace(); } return user; } @Override public int updateUser(User user) { int flag = 0; try { flag = userMapper.updateUser(user); } catch (Exception e) { e.printStackTrace(); } return flag; } }
9240f42f585114134a9a15db2672446aab6c6b3f
7,625
java
Java
bizcore/WEB-INF/caf_custom_src/com/terapico/caf/viewcomponent/VComponentCardInList.java
golap-cn/contact-web-app
b50bf66a6852b8caceaf300d35aaa38761b491cc
[ "MIT" ]
null
null
null
bizcore/WEB-INF/caf_custom_src/com/terapico/caf/viewcomponent/VComponentCardInList.java
golap-cn/contact-web-app
b50bf66a6852b8caceaf300d35aaa38761b491cc
[ "MIT" ]
null
null
null
bizcore/WEB-INF/caf_custom_src/com/terapico/caf/viewcomponent/VComponentCardInList.java
golap-cn/contact-web-app
b50bf66a6852b8caceaf300d35aaa38761b491cc
[ "MIT" ]
null
null
null
24.837134
99
0.668721
1,001,724
package com.terapico.caf.viewcomponent; import java.util.ArrayList; import java.util.Date; import java.util.List; public class VComponentCardInList extends BaseVC { protected String title; protected String brief; protected String imageUrl; protected String status; protected String displayMode; protected String documentUrl; protected Date createTime; protected List<VComponentAction> actionList; protected String flag; protected String level; protected String mode; protected List<VComponentInfoListItem> infoList; public VComponentCardInList() { super(); this.setComponentType(VComponent.CARD_IN_LIST); } public VComponentCardInList id(String id) { this.setId(id); return this; } public VComponentCardInList linkToUrl(String linkToUrl) { this.setLinkToUrl(linkToUrl); return this; } public String getTitle() { return this.title; } public void setTitle(String value) { this.title = value; } public VComponentCardInList title(String value) { this.title = value; return this; } public String getBrief() { return this.brief; } public void setBrief(String value) { this.brief = value; } public VComponentCardInList brief(String value) { this.brief = value; return this; } public String getImageUrl() { return this.imageUrl; } public void setImageUrl(String value) { this.imageUrl = value; } public VComponentCardInList imageUrl(String value) { this.imageUrl = value; return this; } public String getStatus() { return this.status; } public void setStatus(String value) { this.status = value; } public VComponentCardInList status(String value) { this.status = value; return this; } public String getDisplayMode() { return this.displayMode; } public void setDisplayMode(String value) { this.displayMode = value; } public VComponentCardInList displayMode(String value) { this.displayMode = value; return this; } public String getDocumentUrl() { return this.documentUrl; } public void setDocumentUrl(String value) { this.documentUrl = value; } public VComponentCardInList documentUrl(String value) { this.documentUrl = value; return this; } public Date getCreateTime() { return this.createTime; } public void setCreateTime(Date value) { this.createTime = value; } public VComponentCardInList createTime(Date value) { this.createTime = value; return this; } public List<VComponentAction> getActionList() { return this.actionList; } public void setActionList(List<VComponentAction> value) { this.actionList = value; } public VComponentCardInList actionList(List<VComponentAction> value) { this.actionList = value; return this; } public VComponentCardInList actionList(VComponentAction value) { ensureActionList().add(value); return this; } protected List<VComponentAction> ensureActionList() { if (this.actionList != null) { return this.actionList; } this.actionList = new ArrayList<>(); return this.actionList; } public String getFlag() { return this.flag; } public void setFlag(String value) { this.flag = value; } public VComponentCardInList flag(String value) { this.flag = value; return this; } public String getLevel() { return this.level; } public void setLevel(String value) { this.level = value; } public VComponentCardInList level(String value) { this.level = value; return this; } public String getMode() { return this.mode; } public void setMode(String value) { this.mode = value; } public VComponentCardInList mode(String value) { this.mode = value; return this; } public List<VComponentInfoListItem> getInfoList() { return this.infoList; } public void setInfoList(List<VComponentInfoListItem> value) { this.infoList = value; } public VComponentCardInList infoList(List<VComponentInfoListItem> value) { this.infoList = value; return this; } public VComponentCardInList infoList(VComponentInfoListItem value) { ensureInfoList().add(value); return this; } protected List<VComponentInfoListItem> ensureInfoList() { if (this.infoList != null) { return this.infoList; } this.infoList = new ArrayList<>(); return this.infoList; } public VComponentCardInList setAttribute(String attrName, Object value) { String stdAttrName = toStandardAttributeName(attrName); if (handledByBaseAttribute(stdAttrName, value)) { return this; } switch (attrName) { case "title": if (checkAttributeValueAssignable(value, String.class, "card_in_list的title必须是String类型")) { setTitle((String) value); } return this; case "brief": if (checkAttributeValueAssignable(value, String.class, "card_in_list的brief必须是String类型")) { setBrief((String) value); } return this; case "imageUrl": if (checkAttributeValueAssignable( value, String.class, "card_in_list的imageUrl必须是String类型")) { setImageUrl((String) value); } return this; case "status": if (checkAttributeValueAssignable(value, String.class, "card_in_list的status必须是String类型")) { setStatus((String) value); } return this; case "displayMode": if (checkAttributeValueAssignable( value, String.class, "card_in_list的displayMode必须是String类型")) { setDisplayMode((String) value); } return this; case "documentUrl": if (checkAttributeValueAssignable( value, String.class, "card_in_list的documentUrl必须是String类型")) { setDocumentUrl((String) value); } return this; case "createTime": if (checkAttributeValueAssignable(value, Date.class, "card_in_list的createTime必须是Date类型")) { setCreateTime((Date) value); } return this; case "actionList": if (checkAttributeValueAssignableFromList( value, VComponentAction.class, "card_in_list的actionList必须是List<VComponentAction>类型")) { setActionList((List<VComponentAction>) value); } return this; case "flag": if (checkAttributeValueAssignable(value, String.class, "card_in_list的flag必须是String类型")) { setFlag((String) value); } return this; case "level": if (checkAttributeValueAssignable(value, String.class, "card_in_list的level必须是String类型")) { setLevel((String) value); } return this; case "mode": if (checkAttributeValueAssignable(value, String.class, "card_in_list的mode必须是String类型")) { setMode((String) value); } return this; case "infoList": if (checkAttributeValueAssignableFromList( value, VComponentInfoListItem.class, "card_in_list的infoList必须是List<VComponentInfoListItem>类型")) { setInfoList((List<VComponentInfoListItem>) value); } return this; default: throw new RuntimeException("card_in_list 不支持设置属性 " + stdAttrName); } } public VComponentCardInList blankInfoList() { ensureInfoList().add(null); return this; } public VComponentCardInList infoList(String id, String title, String value) { ensureInfoList().add(new VComponentInfoListItem().id(id).title(title).value(value)); ensureInfoList().add(null); return this; } }
9240f463e92fa61abdca5dcf8dcb8a68d4e67bf2
198
java
Java
L05.1-annotations-reflection/src/main/java/ru/otus/l51/package-info.java
lanaflonPerso/otus_java_2018_12
bda845f9ad5e59a8c186d34014b202801ebb8088
[ "MIT" ]
null
null
null
L05.1-annotations-reflection/src/main/java/ru/otus/l51/package-info.java
lanaflonPerso/otus_java_2018_12
bda845f9ad5e59a8c186d34014b202801ebb8088
[ "MIT" ]
null
null
null
L05.1-annotations-reflection/src/main/java/ru/otus/l51/package-info.java
lanaflonPerso/otus_java_2018_12
bda845f9ad5e59a8c186d34014b202801ebb8088
[ "MIT" ]
1
2020-01-30T19:36:54.000Z
2020-01-30T19:36:54.000Z
22
53
0.732323
1,001,725
/** * some package java doc */ @PackageOwner("otus") //ElementType.PACKAGE //@PackageOwner(owner = "otus") //ElementType.PACKAGE package ru.otus.l51; import ru.otus.l51.annotations.PackageOwner;
9240f466f186e4d297ce30aecca46c61c6f2cc0e
3,014
java
Java
validator/client/src/test/java/tech/pegasys/teku/validator/client/loader/ValidatorSourceFactoryTest.java
prestonvanloon/teku
44b73e91f17348fae47fcf5162e5e3718e655d8d
[ "Apache-2.0" ]
95
2018-12-14T16:36:26.000Z
2020-02-25T14:29:14.000Z
validator/client/src/test/java/tech/pegasys/teku/validator/client/loader/ValidatorSourceFactoryTest.java
prestonvanloon/teku
44b73e91f17348fae47fcf5162e5e3718e655d8d
[ "Apache-2.0" ]
454
2018-12-13T13:32:33.000Z
2020-02-25T21:32:53.000Z
validator/client/src/test/java/tech/pegasys/teku/validator/client/loader/ValidatorSourceFactoryTest.java
prestonvanloon/teku
44b73e91f17348fae47fcf5162e5e3718e655d8d
[ "Apache-2.0" ]
53
2018-12-13T13:19:23.000Z
2020-02-21T20:37:03.000Z
43.681159
118
0.77505
1,001,726
/* * Copyright 2021 ConsenSys AG. * * 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 tech.pegasys.teku.validator.client.loader; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.mock; import java.net.http.HttpClient; import java.nio.file.Path; import java.util.Optional; import org.hyperledger.besu.plugin.services.MetricsSystem; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import tech.pegasys.teku.core.signatures.SlashingProtector; import tech.pegasys.teku.infrastructure.async.StubAsyncRunner; import tech.pegasys.teku.infrastructure.metrics.StubMetricsSystem; import tech.pegasys.teku.service.serviceutils.layout.DataDirLayout; import tech.pegasys.teku.service.serviceutils.layout.SeparateServiceDataDirLayout; import tech.pegasys.teku.spec.Spec; import tech.pegasys.teku.spec.TestSpecFactory; import tech.pegasys.teku.validator.api.InteropConfig; import tech.pegasys.teku.validator.api.ValidatorConfig; class ValidatorSourceFactoryTest { private final Spec spec = TestSpecFactory.createMinimalPhase0(); private final InteropConfig disabledInteropConfig = InteropConfig.builder().specProvider(spec).build(); final ValidatorConfig config = ValidatorConfig.builder().validatorExternalSignerSlashingProtectionEnabled(false).build(); private final SlashingProtector slashingProtector = mock(SlashingProtector.class); private final StubAsyncRunner asyncRunner = new StubAsyncRunner(); private final HttpClient httpClient = mock(HttpClient.class); private final MetricsSystem metricsSystem = new StubMetricsSystem(); private final PublicKeyLoader publicKeyLoader = new PublicKeyLoader(); @Test void mutableValidatorShouldBeSlashingProtected(@TempDir final Path tempDir) { final DataDirLayout dataDirLayout = new SeparateServiceDataDirLayout(tempDir, Optional.empty(), Optional.empty()); final ValidatorSourceFactory factory = new ValidatorSourceFactory( spec, config, disabledInteropConfig, () -> httpClient, slashingProtector, publicKeyLoader, asyncRunner, metricsSystem, Optional.of(dataDirLayout)); factory.createValidatorSources(); final Optional<ValidatorSource> source = factory.getMutableLocalValidatorSource(); assertThat(source).isPresent(); assertThat(source.get()).isInstanceOf(SlashingProtectedValidatorSource.class); } }
9240f4a99725c695efab5cfd98fb3d74d2864ab9
13,396
java
Java
spring/src/main/java/com/lagou/edu/factory/BeanFactory.java
RicardoDu/dyq
2f995029b9eb21d95037b036e2e50d1049379002
[ "Apache-2.0" ]
null
null
null
spring/src/main/java/com/lagou/edu/factory/BeanFactory.java
RicardoDu/dyq
2f995029b9eb21d95037b036e2e50d1049379002
[ "Apache-2.0" ]
3
2020-04-23T21:09:44.000Z
2021-12-09T22:12:38.000Z
spring/src/main/java/com/lagou/edu/factory/BeanFactory.java
RicardoDu/dyq
2f995029b9eb21d95037b036e2e50d1049379002
[ "Apache-2.0" ]
null
null
null
33.406484
173
0.563302
1,001,727
package com.lagou.edu.factory; import com.lagou.edu.anno.Autowired; import com.lagou.edu.anno.Transactional; import com.lagou.edu.utils.ClassUtil; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** * @author 应癫 * <p> * 工厂类,生产对象(使用反射技术) */ public class BeanFactory { /** * 代理工厂类bean */ public static final String PROXY_FACTORY = "proxyFactory"; private static ProxyFactory proxyFactory; /** * 缓存集合 * beanMap 一级缓存 * earlyMap 二级缓存 * basicMap 三级缓存 * currentBean 当前正创建bean集合 * sonMap beanName及其依赖beanName集合 * transferBean 事务bean */ private static Map<String, Object> beanMap = new HashMap<>(); private static Map<String, Object> earlyMap = new HashMap<>(); private static Map<String, Object> basicMap = new HashMap<>(); private static Set<String> currentBean = new HashSet<>(); private static Set<String> typeBeanName = new HashSet<>(); private static Map<String, Set<String>> sonMap = new HashMap<>(); private static Set<String> transferBean = new HashSet<>(); static { try { //首先初始化 组件类bean 此类组件直接存在一级缓存内 initAnnoElementComponent(BasicBeanMatchEnum.Component.getName(), BasicBeanMatchEnum.Component.getValue()); //代理工厂及事务类文件初始化 initAnnoElementTransfer(BasicBeanMatchEnum.Transfer.getName(), BasicBeanMatchEnum.Transfer.getValue()); //初始化 Service类bean Repository为Dao层注解 此层内部Autowired 允许调用Component 及其他DaoImpl initAnnoElementService(BasicBeanMatchEnum.Repository.getName(), BasicBeanMatchEnum.Repository.getValue()); //初始化 Service类bean Service为Service层注解 此层内部Autowired 可调用所有Bean initAnnoElementService(BasicBeanMatchEnum.Service.getName(), BasicBeanMatchEnum.Service.getValue()); } catch (Exception e) { e.printStackTrace(); } } /** * 事务类工具初始化 * * @param name * @param value */ private static void initAnnoElementTransfer(String name, Class<? extends Annotation> value) throws Exception { //事务类 处理 initAnnoElementService(name, value); //处理代理工厂 initBeanWithAutoWired(value, ProxyFactory.class); beanAssemblyCycle(PROXY_FACTORY, sonMap.get(PROXY_FACTORY)); //初始化代理工厂 proxyFactory = (ProxyFactory) beanMap.get(PROXY_FACTORY); sonMap.remove(PROXY_FACTORY); } /** * 服务类bean处理 * * @param name * @param value * @throws Exception */ private static void initAnnoElementService(String name, Class<? extends Annotation> value) throws Exception { //初始化Service层全部bean initAnnoElementType(name, value); //处理其权限内的Autoired initAnnoElementFiled(); //清空权限关系 sonMap.clear(); } private static void initAnnoElementComponent(String packageName, Class<? extends Annotation> ano) throws Exception { // 任务一: 扫描service(Dao)Impl文件夹 找到所有的@service(map集合) List<Class<?>> classesAll = ClassUtil.getClasses(packageName); for (Class<?> classInfo : classesAll) { //2 判断类上面是否存在注入@service的注解 一个类最多存在一个@service注解 Object serviceAnno = classInfo.getAnnotation(ano); // 实例化之后的对象 if (serviceAnno != null) { putBeanToMap(classInfo, getBeanNameWithAnnoValue(serviceAnno, classInfo), beanMap); } } } /** * 根据classInfo 生成bean 放入到对应的map中 * * @param classInfo * @param beanName * @param setToMap * @return * @throws Exception */ private static Object putBeanToMap(Class<?> classInfo, String beanName, Map setToMap) throws Exception { Object o; try { o = classInfo.getDeclaredConstructor().newInstance(); if (!typeBeanName.add(beanName)) { //注解名重复 Object aClass = (beanMap.get(beanName) == null ? (earlyMap.get(beanName) == null ? basicMap.get(beanName) : earlyMap.get(beanName)) : beanMap.get(beanName)); System.out.println(classInfo.getName() + "注解名与" + aClass.getClass().getName() + "重复"); throw new Exception(); } if (setToMap != null) { setToMap.put(beanName, o); } } catch (Exception e) { System.out.println(classInfo.getName() + "无需创建bean"); throw e; } return o; } /** * 遍历sonMap处理autowired */ private static void initAnnoElementFiled() throws Exception { for (Map.Entry<String, Set<String>> entry : sonMap.entrySet()) { String key = entry.getKey(); Set<String> value = entry.getValue(); beanAssemblyCycle(key, value); } } /** * 循环装配 * * @param k beanName * @param v 自动的集合 * @return */ private static Object beanAssemblyCycle(String k, Set<String> v) throws Exception { //map中存在bean?存在说明已经对其进行过装配 直接返回; Object keyBean = beanMap.get(k); if (keyBean != null) { return keyBean; } //currentBean中存在? if (currentBean.add(k)) { List<Map<String, Object>> toDealList = new ArrayList<>(); //遍历Set<String> String--存储全路径 (再处理为beanName) for (String name : v) { //此时name为fileName+"#"+ 存储的bean的name 或头部无ElementType注解的类的全路径 String fileName = name.split("#")[0]; String beanName = name.split("#")[1]; Object autoBean = doRealBean(beanName); Map<String, Object> autoMap = new HashMap<>(); autoMap.put(fileName, autoBean); //加入toDealList toDealList.add(autoMap); } if (earlyMap.get(k) != null) { //earlyMap获取bean 通过toDealList装配 -> beanMap keyBean = assemblyBean(earlyMap.get(k), toDealList); putEarlyToBeanMap(k, keyBean); } else { //basicMap获取bean 通过toDealList装配 -> beanMap(是否进一步操作?) keyBean = assemblyBean(basicMap.get(k), toDealList); putBasicToBeanMap(k, keyBean); } currentBean.remove(k); } else { keyBean = getCycleBean(k); } return keyBean; } /** * 完整bean * * @param fullName * @return * @throws Exception */ private static Object doRealBean(String fullName) throws Exception { String[] fullNames = fullName.split("\\."); String beanName = ClassUtil.toLowerCaseFirstOne(fullNames[fullNames.length - 1]); Object autoBean = beanMap.get(beanName);//t为基础bean //判断map中是否存在该bean if (autoBean == null) { //不存在 判断currentBean if (currentBean.contains(beanName)) { //是:出现循环依赖 autoBean = getCycleBean(beanName); } else { autoBean = basicMap.get(beanName); if (autoBean == null) { //缓存中不存在此bean 根据全路径 实例化 putBeanToMap(Class.forName(fullName), fullName, null); System.out.println(fullName + "实例化"); } else { //否 继续循环装配autoBean autoBean = beanAssemblyCycle(beanName, sonMap.get(beanName)); } } } return autoBean; } /** * 装配BEAN * * @param keyBean * @param toDealList */ private static Object assemblyBean(Object keyBean, List<Map<String, Object>> toDealList) throws NoSuchFieldException, IllegalAccessException { for (Map<String, Object> t : toDealList) { for (Map.Entry<String, Object> entry : t.entrySet()) { Object value = entry.getValue(); Field field = keyBean.getClass().getDeclaredField(entry.getKey()); field.setAccessible(true); field.set(keyBean, value); } } return keyBean; } /** * 出现循环依赖处理 * * @param k * @return */ private static Object getCycleBean(String k) { //是:出现循环依赖 Object autoBean = earlyMap.get(k); if (autoBean == null) { autoBean = putBasicToEarly(k, null); } return autoBean; } /** * 把bean从二级缓存取出并放到一级中 * * @param k beanName */ private static Object putEarlyToBeanMap(String k, Object bean) { bean = bean == null ? earlyMap.get(k) : bean; beanMap.put(k, bean); earlyMap.remove(k); return bean; } /** * 将keyBean从三级缓存中升至二级缓存 * * @param k */ private static Object putBasicToEarly(String k, Object bean) { bean = bean == null ? basicMap.get(k) : bean; if (transferBean.contains(k)) { bean = proxyFactory.getJdkProxy(bean); } earlyMap.put(k, bean); basicMap.remove(k); return bean; } /** * 把bean从三级缓存取出并放到一级中 * * @param k beanName */ private static Object putBasicToBeanMap(String k, Object bean) { bean = bean == null ? basicMap.get(k) : bean; if (transferBean.contains(k)) { bean = proxyFactory.getJdkProxy(bean); } beanMap.put(k, bean); basicMap.remove(k); return bean; } /** * ElementType.TYPE类注解(包含value属性值) 扫描并添加到三级缓存 * * @param packageName 路径 * @param ano 注解类 */ private static void initAnnoElementType(String packageName, Class<? extends Annotation> ano) throws Exception { // 任务一: 扫描service(Dao)Impl文件夹 找到所有的@service(map集合) List<Class<?>> classesAll = ClassUtil.getClasses(packageName); for (Class<?> classInfo : classesAll) { initBeanWithAutoWired(ano, classInfo); } } private static void initBeanWithAutoWired(Class<? extends Annotation> ano, Class<?> classInfo) throws Exception { //2 判断类上面是否存在注入@service的注解 一个类最多存在一个@service注解 Object serviceAnno = classInfo.getAnnotation(ano); // 实例化之后的对象 if (serviceAnno != null) { String beanName = getBeanNameWithAnnoValue(serviceAnno, classInfo); putBeanToMap(classInfo, beanName, basicMap); if (classInfo.getAnnotation(Transactional.class) != null) { transferBean.add(beanName); } //@Autowired注解 处理 Set<String> autoBean = collectAutoBean(classInfo); if (autoBean.size() > 0) { sonMap.put(beanName, autoBean); } else { //把bean从三级缓存取出并放到map中 putBasicToBeanMap(beanName, null); } } } /** * 将autoBean集中到Set中 * * @param classInfo 类文件 */ private static Set<String> collectAutoBean(Class<?> classInfo) throws InvocationTargetException, IllegalAccessException { Field[] fields = classInfo.getDeclaredFields(); Set<String> autoBean = new HashSet<>(); for (Field field : fields) { Annotation[] annos = field.getAnnotations(); for (Annotation anno : annos) { //发现AutowiredBean加入autoBean Set集合 最后存放到sonMap if (anno instanceof Autowired) { Class autoClass = (Class) field.getGenericType(); //定位到class Annotation[] annotations = autoClass.getAnnotations(); //默认全路径名 String autoName = autoClass.getName(); if (annotations.length > 0) { for (Annotation annotation : annotations) { //获取注解value String annoName = getBeanNameWithAnnoValue(annotation, autoClass); //存在value 设置beanName if (!autoName.equals(annoName)) { autoName = annoName; break; } } } autoBean.add(field.getName() + "#" + autoName); break; } } } return autoBean; } /** * 获取注解value * * @param serviceAnno */ private static String getBeanNameWithAnnoValue(Object serviceAnno, Class<?> classInfo) throws IllegalAccessException, InvocationTargetException { Method[] methods = serviceAnno.getClass().getMethods(); for (Method method : methods) { if ("value".equalsIgnoreCase(method.getName())) { Object str = method.invoke(serviceAnno); if (str != null && !"".equals(str.toString())) { return str.toString(); } else { //路径名-包名 return ClassUtil.toLowerCaseFirstOne(classInfo.getName().replace(classInfo.getPackageName(), "").substring(1)); } } } return classInfo.getName(); } /** * 任务二:对外提供获取实例对象的接口(根据id获取) */ public static Object getBean(String id) { return beanMap.get(id); } }
9240f5d3383ece66268cda23a04147f8d7fee596
282
java
Java
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/NullabilityProblem.java
teddywest32/intellij-community
e0268d7a1da1d318b441001448cdd3e8929b2f29
[ "Apache-2.0" ]
null
null
null
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/NullabilityProblem.java
teddywest32/intellij-community
e0268d7a1da1d318b441001448cdd3e8929b2f29
[ "Apache-2.0" ]
null
null
null
java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/NullabilityProblem.java
teddywest32/intellij-community
e0268d7a1da1d318b441001448cdd3e8929b2f29
[ "Apache-2.0" ]
1
2020-11-27T10:36:50.000Z
2020-11-27T10:36:50.000Z
18.8
48
0.804965
1,001,728
package com.intellij.codeInspection.dataFlow; /** * @author peter */ public enum NullabilityProblem { callNPE, fieldAccessNPE, unboxingNullable, assigningToNotNull, nullableReturn, passingNullableToNotNullParameter, passingNullableArgumentToNonAnnotatedParameter }
9240f65511ba659765b906316725cec990d10589
781
java
Java
src/main/java/com/valarao/wordlesolver/validation/GuessWordValidator.java
valarao/wordle-solver
3adaed1467405b0434bfc6d3b3fe312618b0fdd0
[ "MIT" ]
6
2022-02-21T05:03:26.000Z
2022-03-20T02:58:38.000Z
src/main/java/com/valarao/wordlesolver/validation/GuessWordValidator.java
valarao/wordle-solver
3adaed1467405b0434bfc6d3b3fe312618b0fdd0
[ "MIT" ]
14
2022-02-19T13:42:11.000Z
2022-02-19T13:55:57.000Z
src/main/java/com/valarao/wordlesolver/validation/GuessWordValidator.java
valarao/wordle-solver
3adaed1467405b0434bfc6d3b3fe312618b0fdd0
[ "MIT" ]
null
null
null
24.40625
95
0.734955
1,001,729
package com.valarao.wordlesolver.validation; import com.valarao.wordlesolver.model.PastGuess; import lombok.NonNull; import lombok.RequiredArgsConstructor; import java.util.Set; /** * Implementation of a GuessValidator to check if guess words are included in the complete set. */ @RequiredArgsConstructor public class GuessWordValidator extends GuessValidator { @NonNull private Set<String> fullWordDataset; @Override protected boolean isValid(PastGuess guess) { return fullWordDataset.contains(guess.getGuessWord()); } @Override protected String getSuccessMessage() { return "Guess word validation succeeded."; } @Override protected String getErrorMessage() { return "Guess word validation failed."; } }
9240f6b954bf3eebcd973c7f01990b68574dfe4f
3,041
java
Java
samples/client/touchvie/android/default/src/main/java/io/swagger/client/model/Awards.java
touchvie/swagger-codegen-old
3e0d74d36ebca4439ecbb44bcd72eaba56dd08e6
[ "Apache-2.0" ]
null
null
null
samples/client/touchvie/android/default/src/main/java/io/swagger/client/model/Awards.java
touchvie/swagger-codegen-old
3e0d74d36ebca4439ecbb44bcd72eaba56dd08e6
[ "Apache-2.0" ]
null
null
null
samples/client/touchvie/android/default/src/main/java/io/swagger/client/model/Awards.java
touchvie/swagger-codegen-old
3e0d74d36ebca4439ecbb44bcd72eaba56dd08e6
[ "Apache-2.0" ]
null
null
null
31.030612
131
0.678395
1,001,730
package io.swagger.client.model; import io.swagger.client.model.AwardsData; import io.swagger.client.model.CardContainer; import java.util.*; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; /** * CardContainer composed by a list of awards with nominees and winners **/ @ApiModel(description = "CardContainer composed by a list of awards with nominees and winners") public class Awards extends CardContainer { public enum TypeOfContainerEnum { text, listing, rating, map, link, awards, catalog, seasons, image, }; @SerializedName("typeOfContainer") private TypeOfContainerEnum typeOfContainer = null; public enum ContentTypeEnum { awards, }; @SerializedName("content_type") private ContentTypeEnum contentType = null; @SerializedName("data") private List<AwardsData> data = null; /** * Card container format type, determines the format of the 'data' field **/ @ApiModelProperty(required = true, value = "Card container format type, determines the format of the 'data' field") public TypeOfContainerEnum getTypeOfContainer() { return typeOfContainer; } public void setTypeOfContainer(TypeOfContainerEnum typeOfContainer) { this.typeOfContainer = typeOfContainer; } /** * Awards container content type **/ @ApiModelProperty(required = true, value = "Awards container content type") public ContentTypeEnum getContentType() { return contentType; } public void setContentType(ContentTypeEnum contentType) { this.contentType = contentType; } /** **/ @ApiModelProperty(required = true, value = "") public List<AwardsData> getData() { return data; } public void setData(List<AwardsData> data) { this.data = data; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Awards awards = (Awards) o; return (this.typeOfContainer == null ? awards.typeOfContainer == null : this.typeOfContainer.equals(awards.typeOfContainer)) && (this.contentType == null ? awards.contentType == null : this.contentType.equals(awards.contentType)) && (this.data == null ? awards.data == null : this.data.equals(awards.data)); } @Override public int hashCode() { int result = 17; result = 31 * result + (typeOfContainer == null ? 0: typeOfContainer.hashCode()); result = 31 * result + (contentType == null ? 0: contentType.hashCode()); result = 31 * result + (data == null ? 0: data.hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Awards {\n"); sb.append(" " + super.toString()).append("\n"); sb.append(" typeOfContainer: ").append(typeOfContainer).append("\n"); sb.append(" contentType: ").append(contentType).append("\n"); sb.append(" data: ").append(data).append("\n"); sb.append("}\n"); return sb.toString(); } }
9240f71cbac6be27a4beea030eee1e33de69b54f
2,906
java
Java
src/test/java/com/neovisionaries/bluetooth/ble/advertising/EddystoneEIDTest.java
sobakasu/nv-bluetooth
ef0099e941cd377571398615ea5e18cfc84cadd3
[ "Apache-2.0" ]
114
2015-05-08T17:49:25.000Z
2022-03-01T15:34:57.000Z
src/test/java/com/neovisionaries/bluetooth/ble/advertising/EddystoneEIDTest.java
sobakasu/nv-bluetooth
ef0099e941cd377571398615ea5e18cfc84cadd3
[ "Apache-2.0" ]
3
2015-09-26T14:27:36.000Z
2020-12-21T07:02:16.000Z
src/test/java/com/neovisionaries/bluetooth/ble/advertising/EddystoneEIDTest.java
sobakasu/nv-bluetooth
ef0099e941cd377571398615ea5e18cfc84cadd3
[ "Apache-2.0" ]
31
2015-09-25T17:32:28.000Z
2022-01-18T08:40:25.000Z
37.532468
94
0.636678
1,001,731
/* * Copyright (C) 2016 Neo Visionaries Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.neovisionaries.bluetooth.ble.advertising; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import java.util.List; import java.util.UUID; import org.junit.Test; import com.neovisionaries.bluetooth.ble.advertising.Eddystone.FrameType; import com.neovisionaries.bluetooth.ble.util.UUIDCreator; public class EddystoneEIDTest { @Test public void test1() { byte[] data = { (byte)13, // Length (byte)0x16, // AD Type = Service Data - 16-bit UUID (byte)0xAA, (byte)0xFE, // Eddystone UUID (byte)0x30, // Eddystone Frame Type = EID (byte)-90, // Calibrated Tx power at 0 m (byte)0x12, (byte)0x34, (byte)0x56, (byte)0x78, // 8-byte EID (byte)0x9A, (byte)0xBC, (byte)0xDE, (byte)0xF0 }; List<ADStructure> list = ADPayloadParser.getInstance().parse(data); assertNotNull("ADPayloadParser.parse(byte[]) returned null.", list); assertEquals("Unexpected size of ADStructure list.", 1, list.size()); // EddystoneUID assertTrue("Not an instance of EddystoneEID.", (list.get(0) instanceof EddystoneEID)); EddystoneEID es = (EddystoneEID)list.get(0); // AD Type assertEquals("AD Type is not 0x16.", 0x16, es.getType()); // Service UUID UUID uuid = UUIDCreator.from16(new byte[] { (byte)0xAA, (byte)0xFE }); assertEquals("Service UUID is not for Eddystone.", uuid, es.getServiceUUID()); // Frame Type assertSame("Unexpected Frame Type.", FrameType.EID, es.getFrameType()); // Tx Power assertEquals("Unexpected Tx Power.", -90, es.getTxPower()); // EID byte[] eid = { (byte)0x12, (byte)0x34, (byte)0x56, (byte)0x78, (byte)0x9A, (byte)0xBC, (byte)0xDE, (byte)0xF0 }; assertArrayEquals("Unexpected EID.", eid, es.getEID()); assertEquals("Unexpected EID (string).", "9jnerlff23u8ed01np9g6ysbhsh0dvcs", es.getEIDAsString()); } }
9240f7decd082ab61d15cf5e03b1c8a7b59900b4
28,744
java
Java
core/src/main/java/com/cloudera/labs/envelope/utils/RowUtils.java
alexvdedov/envelope
c436814720103ea35635e0b0175af61fe2be59d8
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
core/src/main/java/com/cloudera/labs/envelope/utils/RowUtils.java
alexvdedov/envelope
c436814720103ea35635e0b0175af61fe2be59d8
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
core/src/main/java/com/cloudera/labs/envelope/utils/RowUtils.java
alexvdedov/envelope
c436814720103ea35635e0b0175af61fe2be59d8
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
36.110553
126
0.565579
1,001,732
/** * Licensed to Cloudera, Inc. under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Cloudera, Inc. 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 com.cloudera.labs.envelope.utils; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.nio.ByteBuffer; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.spark.sql.Column; import org.apache.spark.sql.Row; import org.apache.spark.sql.RowFactory; import org.apache.spark.sql.types.ArrayType; import org.apache.spark.sql.types.DataType; import org.apache.spark.sql.types.DataTypes; import org.apache.spark.sql.types.DecimalType; import org.apache.spark.sql.types.MapType; import org.apache.spark.sql.types.StructField; import org.apache.spark.sql.types.StructType; import org.joda.time.DateTime; import com.cloudera.labs.envelope.spark.RowWithSchema; import com.google.common.collect.Lists; import com.google.common.collect.ObjectArrays; import scala.collection.JavaConversions; import scala.collection.Seq; import scala.runtime.AbstractFunction1; public class RowUtils { /** * <p>Converts a Java object (simple or compound, e.g. Maps and Arrays) or Row object (for Arrays, Maps, and * StructType) into a {@link Row} compatible value or values. In the latter case for Maps, the incoming Row must have * an associated schema and results in a MapType<String, Object>.</p> * <p>NOTE: If there is a conversion error with a complex type (Map, Array, StructType), the function will set * the returned value for the sub-element to 'null' if the DataType allows it, i.e. {@link ArrayType#containsNull()}. * </p> * <p>NOTE: Does not handle the following DataTypes:</p> * <ul> * <li>{@link org.apache.spark.sql.types.UserDefinedType}</li> * <li>{@link org.apache.spark.sql.types.CalendarIntervalType}</li> * </ul> * <p>Details for accepted conversion values.</p> * <dl> * <dt>BinaryType</dt> * <dd> * <ul> * <li>ByteBuffer</li> * <li>byte[]</li> * </ul> * </dd> * <dt>BooleanType</dt> * <dd> * <ul> * <li>Boolean</li> * <li>Case-insensitive String value of <code>true</code> or <code>false</code></li> * </ul> * </dd> * <dt>DateType</dt> * <dd> * <ul> * <li>Long value of milliseconds since epoch</li> * <li>String value of milliseconds since epoch</li> * <li>{@link java.util.Date} value</li> * <li>{@link org.joda.time.DateTime} value</li> * <li>or the following String value:<br/> * <pre> datetime = time | date-opt-time time = 'T' time-element [offset] date-opt-time = date-element ['T' [time-element] [offset]] date-element = std-date-element | ord-date-element | week-date-element std-date-element = yyyy ['-' MM ['-' dd]] ord-date-element = yyyy ['-' DDD] week-date-element = xxxx '-W' ww ['-' e] time-element = HH [minute-element] | [fraction] minute-element = ':' mm [second-element] | [fraction] second-element = ':' ss [fraction] fraction = ('.' | ',') digit+ offset = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]]) </pre> * </li> * </ul> * </dd> * <dt>TimestampType</dt> * <dd> * <ul> * <li>Long value of milliseconds since epoch</li> * <li>String value of milliseconds since epoch</li> * <li>{@link java.util.Date} value</li> * <li>{@link org.joda.time.DateTime} value</li> * <li>or the following String value:<br/> * <pre> datetime = time | date-opt-time time = 'T' time-element [offset] date-opt-time = date-element ['T' [time-element] [offset]] date-element = std-date-element | ord-date-element | week-date-element std-date-element = yyyy ['-' MM ['-' dd]] ord-date-element = yyyy ['-' DDD] week-date-element = xxxx '-W' ww ['-' e] time-element = HH [minute-element] | [fraction] minute-element = ':' mm [second-element] | [fraction] second-element = ':' ss [fraction] fraction = ('.' | ',') digit+ offset = 'Z' | (('+' | '-') HH [':' mm [':' ss [('.' | ',') SSS]]]) </pre> * </li> * </ul> * <p><em>Note:</em> The precision is limited to milliseconds; nanosecond resolution is not supported.</p> * </dd> * <dt>DoubleType</dt> * <dd> * <ul> * <li>Double</li> * <li>Number</li> * <li>String value of a Double</li> * </ul> * </dd> * <dt>FloatType</dt> * <dd> * <ul> * <li>Float</li> * <li>Number</li> * <li>String value of a Float</li> * </ul> * </dd> * <dt>IntegerType</dt> * <dd> * <ul> * <li>Integer</li> * <li>Number</li> * <li>String value of an Integer</li> * </ul> * </dd> * <dt>LongType</dt> * <dd> * <ul> * <li>Long</li> * <li>Number</li> * <li>String value of a Long</li> * </ul> * </dd> * <dt>NullType</dt> * <dd> * <ul> * <li><code>null</code></li> * </ul> * </dd> * <dt>ByteType</dt> * <dd> * <ul> * <li>Byte</li> * <li>Number</li> * <li>String value of a Byte</li> * </ul> * </dd> * <dt>ShortType</dt> * <dd> * <ul> * <li>Short</li> * <li>Number</li> * <li>String value of a Short</li> * </ul> * </dd> * <dt>DecimalType</dt> * <dd> * <ul> * <li>Long </li> * <li>Double</li> * <li>String value of a BigDecimal</li> * <li>BigInteger</li> * <li>BigDecimal</li> * </ul> * <p><em>Note:</em> For Double and String conversions, the parsed value will be rounded down, per * {@link RoundingMode#HALF_DOWN} convention.</p> * </dd> * <dt>StringType</dt> * <dd> * <ul> * <li>String</li> * </ul> * </dd> * <dt>ArrayType</dt> * <dd> * <ul> * <li>List of supported DataTypes</li> * <li>Row of supported DataTypes</li> * </ul> * </dd> * <dt>MapType</dt> * <dd> * <ul> * <li>Map with key/value pairs of supported DataTypes</li> * <li>Row of supported DataTypes. <em>NOTE:</em> The Row must have an associated schema or conversion will fail.</li> * </ul> * </dd> * <dt>StructType</dt> * <dd> * <ul> * <li>Map with the following restrictions: keys must be Strings and match the names of the fields in the StructType, * values must be supported DataTypes.</li> * <li>List of supported DataTypes; list must have an exact count and in-order list of values for the StructType</li> * <li>Row of supported DataTypes; Row must have an exact count and in-order list of values for the StructType</li> * </ul> * </dd> * </dl> * @param item The value for conversion * @param type The DataType of the field * @return A Row-compatible value * @see <a href="https://spark.apache.org/docs/latest/sql-programming-guide.html#data-types">Spark SQL Data Types</a> */ public static Object toRowValue(Object item, DataType type) { String typeName = type.typeName(); // Binary, Boolean, Byte, Date, Null, Decimal, Double, Float, Integer, Long, Short, String, Timestamp // Array, Map, CalendarInterval, Struct, UserDefined switch (typeName) { case "binary": // byte[] if (item instanceof ByteBuffer) { return ((ByteBuffer) item).array(); } else if (item instanceof byte[]) { return item; } else { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format", type)); } case "boolean": // boolean or Boolean if (item instanceof Boolean) { return item; } String str = item.toString(); if ("true".equals(str.toLowerCase())) { return Boolean.TRUE; } else if ("false".equals(str.toLowerCase())) { return Boolean.FALSE; } else { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } case "date": // java.sql.Date if (item instanceof Long) { return new java.sql.Date((Long) item); } else if (item instanceof String) { return new java.sql.Date(DateTime.parse((String) item).getMillis()); } else if (item instanceof Date) { return new java.sql.Date(((Date) item).getTime()); } else if (item instanceof DateTime) { return new java.sql.Date(((DateTime) item).getMillis()); } else { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } case "timestamp": // java.sql.Timestamp if (item instanceof Long) { return new Timestamp((Long) item); } else if (item instanceof String) { return new Timestamp(DateTime.parse((String) item).getMillis()); } else if (item instanceof Date) { return new Timestamp(((Date) item).getTime()); } else if (item instanceof DateTime) { return new Timestamp(((DateTime) item).getMillis()); } else { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } case "double": // double or Double if (item instanceof Double) { return item; } else if (item instanceof Number) { return ((Number) item).doubleValue(); } else { try { return Double.parseDouble((String) item); } catch (Exception ex) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } } case "float": // float or Float if (item instanceof Float) { return item; } else if (item instanceof Number) { return ((Number) item).floatValue(); } else { try { return Float.parseFloat((String) item); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } } case "integer": // int or Integer if (item instanceof Integer) { return item; } else if (item instanceof Number) { return ((Number) item).intValue(); } else { try { return Integer.parseInt((String) item); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } } case "long": // long or Long if (item instanceof Long) { return item; } else if (item instanceof Number) { return ((Number) item).longValue(); } else { try { return Long.parseLong((String) item); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } } case "null": if (item == null) { return null; } else { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } case "byte": // byte or Byte if (item instanceof Byte) { return item; } else if (item instanceof Number) { return ((Number) item).byteValue(); } else { try { return Byte.parseByte((String) item); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } } case "short": // short or Short if (item instanceof Short) { return item; } else if (item instanceof Number) { return ((Number) item).shortValue(); } else { try { return Short.parseShort((String) item); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } } case "string": // String return item.toString(); case "array": // List DataType elementType = ((ArrayType) type).elementType(); ArrayList<Object> arrayList = new ArrayList<>(); if (item instanceof List) { for (Object value : (List<?>) item) { if (null != value) { try { value = toRowValue(value, elementType); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized element format: %s[%s]", type, elementType, value)); } } else if (!((ArrayType) type).containsNull()) { throw new RuntimeException(String.format("Type[%s] - Element cannot be 'null': %s[null]", type, elementType)); } arrayList.add(value); } return arrayList; } else if (item instanceof Row) { Row row = (Row) item; for (int i = 0; i < row.length(); i++) { Object value = row.get(i); if (null != value) { try { value = toRowValue(value, elementType); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized value format: %s[%s]", type, elementType, value)); } } else if (!((ArrayType) type).containsNull()) { throw new RuntimeException(String.format("Type[%s] - Value cannot be 'null': %s[null]", type, elementType)); } arrayList.add(value); } return arrayList; } else { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } case "map": // Map MapType mapType = (MapType) type; DataType keyType = mapType.keyType(); DataType valueType = mapType.valueType(); HashMap<Object, Object> hashMap = new HashMap<>(); if (item instanceof Map) { Map<?, ?> map = (Map<?, ?>) item; for (Object k : map.keySet()) { Object key, value; try { key = toRowValue(k, keyType); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized key format: %s[%s]", type, keyType, k)); } value = map.get(k); if (null != value) { try { value = toRowValue(value, valueType); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized value format: %s[%s]", type, valueType, value)); } } else if (!mapType.valueContainsNull()) { throw new RuntimeException(String.format("Type[%s] - Value cannot be 'null': %s[null]", type, valueType)); } hashMap.put(key, value); } return hashMap; } else if (item instanceof Row) { // Convert a Row into a Map; only if there is a schema and only if the values can convert Row row = (Row) item; StructType schema = row.schema(); if (null == schema) { throw new RuntimeException(String.format("Type[%s] - Invalid Row format, no schema found: Row[%s]", type, item)); } String[] fieldNames = schema.fieldNames(); for (int i = 0; i < fieldNames.length; i++) { Object value = row.get(i); if (null != value) { try { value = toRowValue(value, valueType); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized value format: %s[%s]", type, valueType, value)); } } else if (!mapType.valueContainsNull()) { throw new RuntimeException(String.format("Type[%s] - Value cannot be 'null': %s[null]", type, valueType)); } hashMap.put(fieldNames[i], value); } return hashMap; } else { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } case "struct": // Row ArrayList<Object> valueList = new ArrayList<>(); if (item instanceof Map) { // Keys must be Strings and match the names of the fields // Values must convert to field DataTypes @SuppressWarnings("unchecked") Map<Object, Object> input = (Map<Object, Object>) item; for (StructField f : ((StructType) type).fields()) { if (input.containsKey(f.name())) { Object value = input.get(f.name()); if (null != value) { try { value = toRowValue(value, f.dataType()); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized value format: %s[%s]", type, f.dataType(), value)); } } else if (!f.nullable()) { throw new RuntimeException(String.format("Type[%s] - Value cannot be 'null': %s[null]", type, f.dataType())); } valueList.add(value); } else { throw new RuntimeException(String.format("Type[%s] - Key not found on input: %s[%s]", type, f.name(), f.dataType())); } } } else if (item instanceof List) { // An exact count, in-order list of values for the StructType // Values must convert to the field DataTypes @SuppressWarnings("unchecked") List<Object> input = (List<Object>) item; StructField[] fields = ((StructType) type).fields(); if (fields.length != input.size()) { throw new RuntimeException(String.format("Type[%s] - Invalid size of input List: %s", type, item)); } for (int i = 0; i < fields.length; i++) { Object value = input.get(i); if (null != value) { try { value = toRowValue(value, fields[i].dataType()); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized element format: %s[%s]", type, fields[i].dataType(), value)); } } else if (!fields[i].nullable()) { throw new RuntimeException(String.format("Type[%s] - Element cannot be 'null': %s[null]", type, fields[i].dataType())); } valueList.add(value); } } else if (item instanceof Row) { // An exact count, in-order list of values for the StructType // Values must convert to the field DataTypes Row input = (Row) item; StructField[] fields = ((StructType) type).fields(); if (fields.length != input.size()) { throw new RuntimeException(String.format("Type[%s] - Invalid size of input Row: %s", type, item)); } for (int i = 0; i < fields.length; i++) { Object value = input.get(i); if (null != value) { try { value = toRowValue(value, fields[i].dataType()); } catch (Exception e) { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized value format: %s[%s]", type, fields[i].dataType(), value)); } } else if (!fields[i].nullable()) { throw new RuntimeException(String.format("Type[%s] - Value cannot be 'null': %s[null]", type, fields[i].dataType())); } valueList.add(value); } } else { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } return RowFactory.create(valueList.toArray()); default: if (type.typeName().startsWith("decimal")) { // java.math.BigDecimal if (item instanceof Long) { return BigDecimal.valueOf((Long) item, ((DecimalType) type).scale()); } else if (item instanceof Double) { return BigDecimal.valueOf((Double) item).setScale(((DecimalType) type).scale(), RoundingMode.HALF_DOWN); } else if (item instanceof String) { return new BigDecimal((String) item).setScale(((DecimalType) type).scale(), RoundingMode.HALF_DOWN); } else if (item instanceof BigDecimal) { return item; } else if (item instanceof BigInteger) { return new BigDecimal((BigInteger) item, ((DecimalType) type).scale()); } else { throw new RuntimeException(String.format("Type[%s] - Invalid or unrecognized input format: %s", type, item)); } } else { throw new RuntimeException(String.format("Type[%s] - StructField DataType unrecognized or not yet implemented", type)); } } } public static StructType subsetSchema(StructType schema, final List<String> fieldNames) { Seq<StructField> fieldSeq = schema.toTraversable().filter(new AbstractFunction1<StructField, Object>() { @Override public Object apply(StructField field) { return fieldNames.contains(field.name()); } }).toSeq(); StructType subset = DataTypes.createStructType(JavaConversions.seqAsJavaList(fieldSeq)); return subset; } public static StructType subtractSchema(StructType schema, List<String> subtractFieldNames) { List<String> fieldNames = Lists.newArrayList(); for (StructField schemaField : schema.fields()) { if (!subtractFieldNames.contains(schemaField.name())) { fieldNames.add(schemaField.name()); } } StructType subtracted = subsetSchema(schema, fieldNames); return subtracted; } public static Row subsetRow(Row row, StructType subsetSchema) { Object[] values = new Object[subsetSchema.length()]; int i = 0; for (String fieldName : subsetSchema.fieldNames()) { values[i] = row.get(row.fieldIndex(fieldName)); i++; } Row subset = new RowWithSchema(subsetSchema, values); return subset; } public static Object get(Row row, String fieldName) { return row.get(row.fieldIndex(fieldName)); } public static Row set(Row row, String fieldName, Object replacement) { Object[] values = new Object[row.length()]; for (int i = 0; i < row.schema().fields().length; i++) { if (i == row.fieldIndex(fieldName)) { values[i] = replacement; } else { values[i] = row.get(i); } } return new RowWithSchema(row.schema(), values); } public static Row append(Row row, Object value) { Object[] appendedValues = ObjectArrays.concat(valuesFor(row), value); Row appendedRow = RowFactory.create(appendedValues); return appendedRow; } public static Row append(Row row, String fieldName, DataType fieldType, Object value) { StructType appendedSchema = row.schema().add(fieldName, fieldType); Object[] appendedValues = ObjectArrays.concat(valuesFor(row), value); Row appendedRow = new RowWithSchema(appendedSchema, appendedValues); return appendedRow; } public static StructType appendFields(StructType from, List<StructField> fields) { StructType to = DataTypes.createStructType(from.fields()); for (StructField field : fields) { to = to.add(field); } return to; } public static Row remove(Row row, String fieldName) { List<StructField> removedFields = Lists.newArrayList(row.schema().fields()); removedFields.remove(row.fieldIndex(fieldName)); StructType removedSchema = new StructType(removedFields.toArray(new StructField[removedFields.size()])); List<Object> removedValues = Lists.newArrayList(RowUtils.valuesFor(row)); removedValues.remove(row.fieldIndex(fieldName)); return new RowWithSchema(removedSchema, removedValues.toArray()); } public static Object[] valuesFor(Row row) { Object[] values = new Object[row.length()]; for (int i = 0; i < row.length(); i++) { values[i] = row.get(i); } return values; } public static StructType structTypeFor(List<String> fieldNames, List<String> fieldTypes) { List<StructField> fields = Lists.newArrayList(); for (int i = 0; i < fieldNames.size(); i++) { String fieldName = fieldNames.get(i); String fieldType = fieldTypes.get(i); StructField field; switch (fieldType) { case "string": field = DataTypes.createStructField(fieldName, DataTypes.StringType, true); break; case "float": field = DataTypes.createStructField(fieldName, DataTypes.FloatType, true); break; case "double": field = DataTypes.createStructField(fieldName, DataTypes.DoubleType, true); break; case "byte": field = DataTypes.createStructField(fieldName, DataTypes.ByteType, true); break; case "short": field = DataTypes.createStructField(fieldName, DataTypes.ShortType, true); break; case "int": field = DataTypes.createStructField(fieldName, DataTypes.IntegerType, true); break; case "long": field = DataTypes.createStructField(fieldName, DataTypes.LongType, true); break; case "boolean": field = DataTypes.createStructField(fieldName, DataTypes.BooleanType, true); break; case "binary": field = DataTypes.createStructField(fieldName, DataTypes.BinaryType, true); break; case "timestamp": field = DataTypes.createStructField(fieldName, DataTypes.TimestampType, true); break; default: throw new RuntimeException("Unsupported provided field type: " + fieldType); } fields.add(field); } StructType schema = DataTypes.createStructType(fields); return schema; } public static boolean different(Row first, Row second, List<String> valueFieldNames) { for (String valueFieldName : valueFieldNames) { Object firstValue = first.get(first.fieldIndex(valueFieldName)); Object secondValue = second.get(second.fieldIndex(valueFieldName)); if (firstValue != null && secondValue != null && !firstValue.equals(secondValue)) { return true; } if ((firstValue != null && secondValue == null) || (firstValue == null && secondValue != null)) { return true; } } return false; } public static Column[] toColumnArray(List<String> columnList) { Column[] columnArray = new Column[columnList.size()]; for (int i = 0; i < columnList.size(); i++) { columnArray[i] = new Column(columnList.get(i)); } return columnArray; } }
9240f9becee6ef71ceaaaca0be9ef88aad3e1317
3,576
java
Java
jfxtras-icalendarfx/src/test/java/jfxtras/icalendarfx/property/component/OrganizerTest.java
samypr100/jfxtras
77df67c4f52aa75007d8ebe2fb7e1c534e2734f5
[ "BSD-3-Clause" ]
531
2015-01-02T13:46:35.000Z
2022-03-24T00:15:06.000Z
jfxtras-icalendarfx/src/test/java/jfxtras/icalendarfx/property/component/OrganizerTest.java
samypr100/jfxtras
77df67c4f52aa75007d8ebe2fb7e1c534e2734f5
[ "BSD-3-Clause" ]
98
2015-01-06T06:09:54.000Z
2022-03-23T06:17:19.000Z
jfxtras-icalendarfx/src/test/java/jfxtras/icalendarfx/property/component/OrganizerTest.java
samypr100/jfxtras
77df67c4f52aa75007d8ebe2fb7e1c534e2734f5
[ "BSD-3-Clause" ]
150
2015-02-05T11:43:29.000Z
2022-03-31T21:23:40.000Z
47.64
203
0.721802
1,001,733
/** * Copyright (c) 2011-2021, JFXtras * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * Neither the name of the organization nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL JFXTRAS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package jfxtras.icalendarfx.property.component; import static org.junit.Assert.assertEquals; import org.junit.Test; import jfxtras.icalendarfx.properties.component.relationship.Organizer; import jfxtras.icalendarfx.utilities.ICalendarUtilities; public class OrganizerTest { @Test public void canParseOrganizer() { String content = "ORGANIZER;CN=John Smith:mailto:[email protected]"; Organizer madeProperty = Organizer.parse(content); Organizer expectedProperty = Organizer.parse("mailto:[email protected]") .withCommonName("John Smith"); assertEquals(expectedProperty, madeProperty); assertEquals(content, expectedProperty.toString()); } @Test public void canParseOrganizer2() { String content = "ORGANIZER;CN=John Smith;DIR=\"ldap://example.com:6666/o=ABC%20Industries,c=US???(cn=Jim%20Dolittle)\";LANGUAGE=en;SENT-BY=\"mailto:[email protected]\":mailto:[email protected]"; Organizer madeProperty = Organizer.parse(content); Organizer expectedProperty = Organizer.parse("mailto:[email protected]") .withCommonName("John Smith") .withDirectoryEntryReference("ldap://example.com:6666/o=ABC%20Industries,c=US???(cn=Jim%20Dolittle)") .withLanguage("en") .withSentBy("mailto:[email protected]"); assertEquals(expectedProperty, madeProperty); assertEquals(ICalendarUtilities.foldLine(content).toString(), expectedProperty.toString()); } @Test public void canParseOrganizer3() { String content = "ORGANIZER;CN=Papa Smurf:mailto:[email protected]"; Organizer madeProperty = Organizer.parse(content); Organizer expectedProperty = Organizer.parse("mailto:[email protected]") .withCommonName("Papa Smurf"); assertEquals(expectedProperty, madeProperty); assertEquals(ICalendarUtilities.foldLine(content).toString(), expectedProperty.toString()); } }
9240fae9b7fa67524af7b88433041e9f3796518d
1,845
java
Java
codes/java/leetcodes/src/main/java/com/hit/basmath/learn/recursion_i/_95.java
hemanthkodandarama/myleetcode
e13073e7c2ed473a932aae72659066b3e56cfdfd
[ "MIT" ]
41
2018-08-30T02:55:16.000Z
2022-03-15T01:02:04.000Z
codes/java/leetcodes/src/main/java/com/hit/basmath/learn/recursion_i/_95.java
hemanthkodandarama/myleetcode
e13073e7c2ed473a932aae72659066b3e56cfdfd
[ "MIT" ]
1
2019-06-27T07:42:12.000Z
2019-06-28T02:19:59.000Z
codes/java/leetcodes/src/main/java/com/hit/basmath/learn/recursion_i/_95.java
hemanthkodandarama/myleetcode
e13073e7c2ed473a932aae72659066b3e56cfdfd
[ "MIT" ]
19
2019-06-27T18:29:47.000Z
2022-02-24T16:25:25.000Z
25.625
110
0.452033
1,001,734
package com.hit.basmath.learn.recursion_i; import com.hit.common.TreeNode; import java.util.ArrayList; import java.util.List; /** * 95. Unique Binary Search Trees II * <p> * Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. * <p> * Example: * <p> * Input: 3 * <p> * Output: * <p> * [ * [1,null,3,2], * [3,2,null,1], * [3,1,null,null,2], * [2,1,3], * [1,null,2,null,3] * ] * <p> * Explanation: * <p> * The above output corresponds to the 5 unique BST's shown below: * <p> * 1 3 3 2 1 * \ / / / \ \ * 3 2 1 1 3 2 * / / \ \ * 2 1 2 3 */ public class _95 { public List<TreeNode> generateTrees(int n) { List<TreeNode>[] result = new List[n + 1]; result[0] = new ArrayList<TreeNode>(); if (n == 0) { return result[0]; } result[0].add(null); for (int len = 1; len <= n; len++) { result[len] = new ArrayList<TreeNode>(); for (int j = 0; j < len; j++) { for (TreeNode nodeL : result[j]) { for (TreeNode nodeR : result[len - j - 1]) { TreeNode node = new TreeNode(j + 1); node.left = nodeL; node.right = clone(nodeR, j + 1); result[len].add(node); } } } } return result[n]; } private TreeNode clone(TreeNode n, int offset) { if (n == null) { return null; } TreeNode node = new TreeNode(n.val + offset); node.left = clone(n.left, offset); node.right = clone(n.right, offset); return node; } }
9240fba60d5d460ee3d1689b3b463b61a55907bc
8,983
java
Java
ExtractedJars/Health_com.huawei.health/javafiles/com/autonavi/amap/mapcore/tools/GlMapUtil.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/Health_com.huawei.health/javafiles/com/autonavi/amap/mapcore/tools/GlMapUtil.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/Health_com.huawei.health/javafiles/com/autonavi/amap/mapcore/tools/GlMapUtil.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
34.953307
116
0.584103
1,001,735
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.autonavi.amap.mapcore.tools; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.content.res.Resources; import android.text.TextUtils; import android.util.TypedValue; import java.io.*; public class GlMapUtil { public GlMapUtil() { // 0 0:aload_0 // 1 1:invokespecial #45 <Method void Object()> // 2 4:return } public static byte[] decodeAssetResData(Context context, String s) { context = ((Context) (context.getAssets())); // 0 0:aload_0 // 1 1:invokevirtual #58 <Method AssetManager Context.getAssets()> // 2 4:astore_0 byte abyte0[]; context = ((Context) (((AssetManager) (context)).open(s))); // 3 5:aload_0 // 4 6:aload_1 // 5 7:invokevirtual #64 <Method InputStream AssetManager.open(String)> // 6 10:astore_0 s = ((String) (new ByteArrayOutputStream())); // 7 11:new #66 <Class ByteArrayOutputStream> // 8 14:dup // 9 15:invokespecial #67 <Method void ByteArrayOutputStream()> // 10 18:astore_1 abyte0 = new byte[1024]; // 11 19:sipush 1024 // 12 22:newarray byte[] // 13 24:astore_3 _L1: int i = ((InputStream) (context)).read(abyte0); // 14 25:aload_0 // 15 26:aload_3 // 16 27:invokevirtual #73 <Method int InputStream.read(byte[])> // 17 30:istore_2 label0: { if(i <= -1) break label0; // 18 31:iload_2 // 19 32:iconst_m1 // 20 33:icmple 46 try { ((ByteArrayOutputStream) (s)).write(abyte0, 0, i); // 21 36:aload_1 // 22 37:aload_3 // 23 38:iconst_0 // 24 39:iload_2 // 25 40:invokevirtual #77 <Method void ByteArrayOutputStream.write(byte[], int, int)> } //* 26 43:goto 25 //* 27 46:aload_1 //* 28 47:invokevirtual #81 <Method byte[] ByteArrayOutputStream.toByteArray()> //* 29 50:astore_3 //* 30 51:aload_1 //* 31 52:invokevirtual #84 <Method void ByteArrayOutputStream.close()> //* 32 55:aload_0 //* 33 56:invokevirtual #85 <Method void InputStream.close()> //* 34 59:aload_3 //* 35 60:areturn // Misplaced declaration of an exception variable catch(Context context) //* 36 61:astore_0 { return null; // 37 62:aconst_null // 38 63:areturn } // Misplaced declaration of an exception variable catch(Context context) //* 39 64:astore_0 { return null; // 40 65:aconst_null // 41 66:areturn } } goto _L1 abyte0 = ((ByteArrayOutputStream) (s)).toByteArray(); ((ByteArrayOutputStream) (s)).close(); ((InputStream) (context)).close(); return abyte0; } public static int dipToPixel(Context context, int i) { if(context == null) //* 0 0:aload_0 //* 1 1:ifnonnull 6 return i; // 2 4:iload_1 // 3 5:ireturn float f = i; // 4 6:iload_1 // 5 7:i2f // 6 8:fstore_2 try { f = TypedValue.applyDimension(1, f, context.getResources().getDisplayMetrics()); // 7 9:iconst_1 // 8 10:fload_2 // 9 11:aload_0 // 10 12:invokevirtual #93 <Method Resources Context.getResources()> // 11 15:invokevirtual #99 <Method android.util.DisplayMetrics Resources.getDisplayMetrics()> // 12 18:invokestatic #105 <Method float TypedValue.applyDimension(int, float, android.util.DisplayMetrics)> // 13 21:fstore_2 } //* 14 22:fload_2 //* 15 23:f2i //* 16 24:ireturn // Misplaced declaration of an exception variable catch(Context context) //* 17 25:astore_0 { return i; // 18 26:iload_1 // 19 27:ireturn } return (int)f; } public static String getAppVersionName(Context context) { try { context = ((Context) (context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName)); // 0 0:aload_0 // 1 1:invokevirtual #113 <Method PackageManager Context.getPackageManager()> // 2 4:aload_0 // 3 5:invokevirtual #117 <Method String Context.getPackageName()> // 4 8:iconst_0 // 5 9:invokevirtual #123 <Method PackageInfo PackageManager.getPackageInfo(String, int)> // 6 12:getfield #129 <Field String PackageInfo.versionName> // 7 15:astore_0 } //* 8 16:aload_0 //* 9 17:areturn // Misplaced declaration of an exception variable catch(Context context) //* 10 18:astore_0 { return ""; // 11 19:ldc1 #131 <String ""> // 12 21:areturn } return ((String) (context)); } public static String getString(Context context, int i) { return context.getResources().getString(i); // 0 0:aload_0 // 1 1:invokevirtual #93 <Method Resources Context.getResources()> // 2 4:iload_1 // 3 5:invokevirtual #136 <Method String Resources.getString(int)> // 4 8:areturn } public static boolean isAssic(String s) { if(TextUtils.isEmpty(((CharSequence) (s)))) //* 0 0:aload_0 //* 1 1:invokestatic #144 <Method boolean TextUtils.isEmpty(CharSequence)> //* 2 4:ifeq 9 return false; // 3 7:iconst_0 // 4 8:ireturn s = ((String) (s.toCharArray())); // 5 9:aload_0 // 6 10:invokevirtual #150 <Method char[] String.toCharArray()> // 7 13:astore_0 for(int i = 0; i < s.length; i++) //* 8 14:iconst_0 //* 9 15:istore_1 //* 10 16:iload_1 //* 11 17:aload_0 //* 12 18:arraylength //* 13 19:icmpge 46 if(s[i] >= '\u0100' || s[i] <= 0) //* 14 22:aload_0 //* 15 23:iload_1 //* 16 24:caload //* 17 25:sipush 256 //* 18 28:icmpge 37 //* 19 31:aload_0 //* 20 32:iload_1 //* 21 33:caload //* 22 34:ifgt 39 return false; // 23 37:iconst_0 // 24 38:ireturn // 25 39:iload_1 // 26 40:iconst_1 // 27 41:iadd // 28 42:istore_1 //* 29 43:goto 16 return true; // 30 46:iconst_1 // 31 47:ireturn } public static int spToPixel(Context context, int i) { return (int)TypedValue.applyDimension(2, i, context.getResources().getDisplayMetrics()); // 0 0:iconst_2 // 1 1:iload_1 // 2 2:i2f // 3 3:aload_0 // 4 4:invokevirtual #93 <Method Resources Context.getResources()> // 5 7:invokevirtual #99 <Method android.util.DisplayMetrics Resources.getDisplayMetrics()> // 6 10:invokestatic #105 <Method float TypedValue.applyDimension(int, float, android.util.DisplayMetrics)> // 7 13:f2i // 8 14:ireturn } public static final int AMAP_ENGINE_TYPE_DISPLAY_EXTERNAL_1 = 2; public static final int AMAP_ENGINE_TYPE_DISPLAY_EXTERNAL_1_EAGLE_EYE = 3; public static final int AMAP_ENGINE_TYPE_DISPLAY_EXTERNAL_2 = 4; public static final int AMAP_ENGINE_TYPE_DISPLAY_EXTERNAL_2_EAGLE_EYE = 5; public static final int AMAP_ENGINE_TYPE_DISPLAY_EXTERNAL_3 = 6; public static final int AMAP_ENGINE_TYPE_DISPLAY_EXTERNAL_3_EAGLE_EYE = 7; public static final int AN_ENGINE_ID_DISPLAY_EXTERNAL_1 = 3; public static final int AN_ENGINE_ID_DISPLAY_EXTERNAL_1_EAGLE_EYE = 4; public static final int AN_ENGINE_ID_DISPLAY_EXTERNAL_2 = 5; public static final int AN_ENGINE_ID_DISPLAY_EXTERNAL_2_EAGLE_EYE = 6; public static final int AN_ENGINE_ID_DISPLAY_EXTERNAL_3 = 7; public static final int AN_ENGINE_ID_DISPLAY_EXTERNAL_3_EAGLE_EYE = 8; public static final int AN_ENGINE_ID_EAGLE_EYE = 2; public static final int AN_ENGINE_ID_INVALID = -1; public static final int AN_ENGINE_ID_MAIN = 1; public static final int DEVICE_DISPLAY_DPI_HIGH = 320; public static final int DEVICE_DISPLAY_DPI_LOW = 120; public static final int DEVICE_DISPLAY_DPI_MEDIAN = 240; public static final int DEVICE_DISPLAY_DPI_NORMAL = 160; public static final int DEVICE_DISPLAY_DPI_XHIGH = 480; public static final int DEVICE_DISPLAY_DPI_XXHIGH = 640; }
9240fbb3f0feff7e6f7c155c4c37f4944ebab331
289
java
Java
core-banking/src/com/example/banking/entity/AccountStatus.java
deepcloudlabs/dcl204-2020-feb-03
3ff8a6ca1093bf57e91712486673bc42fcb44d68
[ "MIT" ]
null
null
null
core-banking/src/com/example/banking/entity/AccountStatus.java
deepcloudlabs/dcl204-2020-feb-03
3ff8a6ca1093bf57e91712486673bc42fcb44d68
[ "MIT" ]
null
null
null
core-banking/src/com/example/banking/entity/AccountStatus.java
deepcloudlabs/dcl204-2020-feb-03
3ff8a6ca1093bf57e91712486673bc42fcb44d68
[ "MIT" ]
null
null
null
13.952381
46
0.662116
1,001,736
package com.example.banking.entity; /** * * @author Binnur Kurt <[email protected]> * */ public enum AccountStatus { ACTIVE(100), CLOSED(200), PASSIVE(300); private int code; private AccountStatus(int code) { this.code = code; } public int getCode() { return code; } }
9240fc4105e857745d39ac3f02b6e986d300bd55
988
java
Java
src/main/java/com/synopsys/integration/blackduck/api/manual/view/PolicyViolationVulnerabilityView.java
blackducksoftware/blackduck-common-api
b57e1b9a358944d6d30b8fde4b0bcc4b1eb3963d
[ "Apache-2.0" ]
1
2021-04-27T20:32:14.000Z
2021-04-27T20:32:14.000Z
src/main/java/com/synopsys/integration/blackduck/api/manual/view/PolicyViolationVulnerabilityView.java
blackducksoftware/blackduck-common-api
b57e1b9a358944d6d30b8fde4b0bcc4b1eb3963d
[ "Apache-2.0" ]
3
2020-01-21T07:34:23.000Z
2021-04-07T06:39:05.000Z
src/main/java/com/synopsys/integration/blackduck/api/manual/view/PolicyViolationVulnerabilityView.java
blackducksoftware/blackduck-common-api
b57e1b9a358944d6d30b8fde4b0bcc4b1eb3963d
[ "Apache-2.0" ]
1
2021-03-03T10:49:49.000Z
2021-03-03T10:49:49.000Z
24.097561
142
0.715587
1,001,737
/* * blackduck-common-api * * Copyright (c) 2021 Synopsys, Inc. * * Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide. */ package com.synopsys.integration.blackduck.api.manual.view; import java.util.Set; import com.synopsys.integration.blackduck.api.core.BlackDuckView; public class PolicyViolationVulnerabilityView extends BlackDuckView { private String name; private String description; private Set<String> violatingPolicyNames; private String errorMessage; private String warningMessage; public String getName() { return name; } public String getDescription() { return description; } public Set<String> getViolatingPolicyNames() { return violatingPolicyNames; } public String getErrorMessage() { return errorMessage; } public String getWarningMessage() { return warningMessage; } }
9240fca8db71cdae1854800001127ad602bec175
7,588
java
Java
android/guava-testlib/test/com/google/common/collect/testing/OpenJdk6MapTests.java
dmgerman/guava
cd0c423cd6248cbcbf6345a6d9124c3d8c667b19
[ "Apache-2.0" ]
null
null
null
android/guava-testlib/test/com/google/common/collect/testing/OpenJdk6MapTests.java
dmgerman/guava
cd0c423cd6248cbcbf6345a6d9124c3d8c667b19
[ "Apache-2.0" ]
4
2021-11-02T19:40:16.000Z
2022-03-30T19:24:27.000Z
android/guava-testlib/test/com/google/common/collect/testing/OpenJdk6MapTests.java
dmgerman/guava
cd0c423cd6248cbcbf6345a6d9124c3d8c667b19
[ "Apache-2.0" ]
null
null
null
17.605568
608
0.807986
1,001,738
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Copyright (C) 2009 The Guava Authors * * 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. */ end_comment begin_package DECL|package|com.google.common.collect.testing package|package name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|testing package|; end_package begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|Lists operator|. name|newArrayList import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|testing operator|. name|testers operator|. name|CollectionAddAllTester operator|. name|getAddAllUnsupportedNonePresentMethod import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|testing operator|. name|testers operator|. name|CollectionAddAllTester operator|. name|getAddAllUnsupportedSomePresentMethod import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|testing operator|. name|testers operator|. name|CollectionAddTester operator|. name|getAddUnsupportedNotPresentMethod import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|testing operator|. name|testers operator|. name|CollectionCreationTester operator|. name|getCreateWithNullUnsupportedMethod import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|testing operator|. name|testers operator|. name|MapCreationTester operator|. name|getCreateWithNullKeyUnsupportedMethod import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|testing operator|. name|testers operator|. name|MapEntrySetTester operator|. name|getContainsEntryWithIncomparableKeyMethod import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|testing operator|. name|testers operator|. name|MapEntrySetTester operator|. name|getContainsEntryWithIncomparableValueMethod import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|testing operator|. name|testers operator|. name|MapPutAllTester operator|. name|getPutAllNullKeyUnsupportedMethod import|; end_import begin_import import|import static name|com operator|. name|google operator|. name|common operator|. name|collect operator|. name|testing operator|. name|testers operator|. name|MapPutTester operator|. name|getPutNullKeyUnsupportedMethod import|; end_import begin_import import|import name|java operator|. name|lang operator|. name|reflect operator|. name|Method import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Arrays import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collection import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Map import|; end_import begin_import import|import name|junit operator|. name|framework operator|. name|Test import|; end_import begin_comment comment|/** * Tests the {@link Map} implementations of {@link java.util}, suppressing tests that trip known * bugs in OpenJDK 6 or higher. * * @author Kevin Bourrillion */ end_comment begin_comment comment|/* * TODO(cpovirk): consider renaming this class in light of our now running it * under JDK7 */ end_comment begin_class DECL|class|OpenJdk6MapTests specifier|public class|class name|OpenJdk6MapTests extends|extends name|TestsForMapsInJavaUtil block|{ DECL|method|suite () specifier|public specifier|static name|Test name|suite parameter_list|() block|{ return|return operator|new name|OpenJdk6MapTests argument_list|() operator|. name|allTests argument_list|() return|; block|} annotation|@ name|Override DECL|method|suppressForTreeMapNatural () specifier|protected name|Collection argument_list|< name|Method argument_list|> name|suppressForTreeMapNatural parameter_list|() block|{ return|return name|Arrays operator|. name|asList argument_list|( name|getPutNullKeyUnsupportedMethod argument_list|() argument_list|, name|getPutAllNullKeyUnsupportedMethod argument_list|() argument_list|, name|getCreateWithNullKeyUnsupportedMethod argument_list|() argument_list|, name|getCreateWithNullUnsupportedMethod argument_list|() argument_list|, comment|// for keySet name|getContainsEntryWithIncomparableKeyMethod argument_list|() argument_list|, name|getContainsEntryWithIncomparableValueMethod argument_list|() argument_list|) return|; block|} annotation|@ name|Override DECL|method|suppressForConcurrentHashMap () specifier|protected name|Collection argument_list|< name|Method argument_list|> name|suppressForConcurrentHashMap parameter_list|() block|{ comment|/* * The entrySet() of ConcurrentHashMap, unlike that of other Map * implementations, supports add() under JDK8. This seems problematic, but I * didn't see that discussed in the review, which included many other * changes: http://goo.gl/okTTdr * * TODO(cpovirk): decide what the best long-term action here is: force users * to suppress (as we do now), stop testing entrySet().add() at all, make * entrySet().add() tests tolerant of either behavior, introduce a map * feature for entrySet() that supports add(), or something else */ return|return name|Arrays operator|. name|asList argument_list|( name|getAddUnsupportedNotPresentMethod argument_list|() argument_list|, name|getAddAllUnsupportedNonePresentMethod argument_list|() argument_list|, name|getAddAllUnsupportedSomePresentMethod argument_list|() argument_list|) return|; block|} annotation|@ name|Override DECL|method|suppressForConcurrentSkipListMap () specifier|protected name|Collection argument_list|< name|Method argument_list|> name|suppressForConcurrentSkipListMap parameter_list|() block|{ name|List argument_list|< name|Method argument_list|> name|methods init|= name|newArrayList argument_list|() decl_stmt|; name|methods operator|. name|addAll argument_list|( name|super operator|. name|suppressForConcurrentSkipListMap argument_list|() argument_list|) expr_stmt|; name|methods operator|. name|add argument_list|( name|getContainsEntryWithIncomparableKeyMethod argument_list|() argument_list|) expr_stmt|; name|methods operator|. name|add argument_list|( name|getContainsEntryWithIncomparableValueMethod argument_list|() argument_list|) expr_stmt|; return|return name|methods return|; block|} block|} end_class end_unit
9240fcd9be59d4d95f8229db0c00be3d2f67c754
1,497
java
Java
app/controllers/DeviceController.java
mayconbordin/ubipri-server
ffc4fa78fdef493d8b7d8314347e233f205cc448
[ "Apache-2.0" ]
null
null
null
app/controllers/DeviceController.java
mayconbordin/ubipri-server
ffc4fa78fdef493d8b7d8314347e233f205cc448
[ "Apache-2.0" ]
null
null
null
app/controllers/DeviceController.java
mayconbordin/ubipri-server
ffc4fa78fdef493d8b7d8314347e233f205cc448
[ "Apache-2.0" ]
null
null
null
23.761905
77
0.735471
1,001,739
package controllers; import java.util.List; import javax.inject.Inject; import dao.DeviceDAO; import models.Device; import models.Functionality; import models.User; import models.serialization.Views; import play.Logger; import play.data.Form; import play.mvc.Result; import play.mvc.Security; import utils.http.BaseController; import utils.security.Secured; public class DeviceController extends BaseController { private final Logger.ALogger logger = Logger.of("application"); @Inject DeviceDAO deviceDao; @Security.Authenticated(Secured.class) public Result getDevice(String code) { Device device = deviceDao.findByFieldWith("code", code, "functionalities"); if (device == null) { notFound("Device not found", 404); } return ok(device, Views.Full.class); } @Security.Authenticated(Secured.class) public Result updateDevice(String code) { Device device = deviceDao.findByField("code", code); if (device == null) { notFound("Device not found", 404); } Form<Device> form = Form.form(Device.class).bindFromRequest(); if (form.hasErrors()) { return invalidForm(form); } device.setName(form.get().getName()); device.setCode(form.get().getCode()); deviceDao.update(device); return ok(device, Views.Full.class); } @Security.Authenticated(Secured.class) public Result listFunctionalities(String code) { Device device = deviceDao.findByFieldWith("code", code, "functionalities"); return ok(device.getFunctionalities()); } }
9240fcf28259e5001b88d7a5b3003c6835886ac5
4,502
java
Java
graphicsExercises/fields/labyrinth/LabyrinthSolverModel.java
jonathansotoan/deitel
dc181762331a0d61c902d67c2323926cf83cec4a
[ "MIT" ]
2
2018-02-10T22:17:16.000Z
2020-02-23T05:14:54.000Z
graphicsExercises/fields/labyrinth/LabyrinthSolverModel.java
jonathansotoan/deitel
dc181762331a0d61c902d67c2323926cf83cec4a
[ "MIT" ]
null
null
null
graphicsExercises/fields/labyrinth/LabyrinthSolverModel.java
jonathansotoan/deitel
dc181762331a0d61c902d67c2323926cf83cec4a
[ "MIT" ]
3
2016-05-09T17:33:37.000Z
2019-02-25T03:37:36.000Z
34.630769
104
0.650378
1,001,740
//Exercise 15.20 package deitel.graphicsExercises.fields.labyrinth; import java.awt.Point; import java.util.Random; public class LabyrinthSolverModel { private Labyrinth labyrinth; private char identifier; public LabyrinthSolverModel () { this (createRandomLabyrinth (new char[12][12], '#', '.'), 'x'); } public LabyrinthSolverModel (Labyrinth labyrinthToResolve, char pathIdentifier) { labyrinth = labyrinthToResolve; identifier = pathIdentifier != labyrinth.getWallSymbol () && pathIdentifier != labyrinth.getFreeSpaceSymbol () && pathIdentifier != '-' ? pathIdentifier : 'x'; } public final char getIdentifier () { return identifier; } @Override public String toString () { String results = String.format ("Start point: %s End point: %s\n", labyrinth.getStartPoint (), labyrinth.getEndPoint ()); for (byte j = 0; j < labyrinth.getRows (); ++j) { for (byte k = 0; k < labyrinth.getColumns (); ++k) results += labyrinth.getValueAt (j, k) + " "; results = results.concat ("\n"); } return results + "The labyrinth is " + (isResolved () ? "" : "not ") + "resolved"; } public final void solve () { solve (labyrinth.getStartPoint ().x, labyrinth.getStartPoint ().y); } private final void solve (final int row, final int column) { if (column == labyrinth.getEndPoint ().y && row == labyrinth.getEndPoint ().x) labyrinth.setValueAt (row, column, getIdentifier ()); else if (labyrinth.getValueAt (row - 1, column) == labyrinth.getFreeSpaceSymbol ()) { labyrinth.setValueAt (row, column, getIdentifier ()); solve (row - 1, column); } else if (labyrinth.getValueAt (row, column + 1) == labyrinth.getFreeSpaceSymbol ()) { labyrinth.setValueAt (row, column, getIdentifier ()); solve (row, column + 1); } else if (labyrinth.getValueAt (row + 1, column) == labyrinth.getFreeSpaceSymbol ()) { labyrinth.setValueAt (row, column, getIdentifier ()); solve (row + 1, column); } else if (labyrinth.getValueAt (row, column - 1) == labyrinth.getFreeSpaceSymbol ()) { labyrinth.setValueAt (row, column, getIdentifier ()); solve (row, column - 1); } else { labyrinth.setValueAt (row, column, '-'); Point identifierPosition = whereIs (row, column, getIdentifier ()); if (identifierPosition.x != -1) { labyrinth.setValueAt (identifierPosition.x, identifierPosition.y, labyrinth.getFreeSpaceSymbol ()); solve (identifierPosition.x, identifierPosition.y); } } } private final Point whereIs (int row, int column, char value) { if (labyrinth.getValueAt (row - 1, column) == value) return new Point (row - 1, column); if (labyrinth.getValueAt (row + 1, column) == value) return new Point (row + 1, column); if (labyrinth.getValueAt (row, column - 1) == value) return new Point (row, column - 1); if (labyrinth.getValueAt (row, column + 1) == value) return new Point (row, column + 1); //else return new Point (-1, -1);//If the current labyrinth hasn't solution } public final boolean isResolved () { if (labyrinth.getValueAt (labyrinth.getEndPoint ().x, labyrinth.getEndPoint ().y) == getIdentifier ()) return true; else return false; } public static Labyrinth createRandomLabyrinth (char[][] field, final char wall, final char freeSpace) { Random ran = new Random (); Point initPoint, finalPoint; if (ran.nextBoolean ()) initPoint = new Point (0, ran.nextInt (field[0].length - 2) + 1); else initPoint = new Point (ran.nextInt (field.length - 2) + 1, 0); if (ran.nextBoolean ()) finalPoint = new Point (field[0].length - 1, ran.nextInt (field[0].length - 2) + 1); else finalPoint = new Point (ran.nextInt (field.length - 2) + 1, field.length - 1); //Note: the freeSpace has 75% posibilites to be selected (except in the borders) for (byte j = 0; j < field.length; ++j) for (byte k = 0; k < field[0].length; ++k) if (j == 0 || j == field.length - 1 || k == 0 || k == field[j].length - 1) field[j][k] = wall;//this instruction is to set wall at the border else if (ran.nextBoolean ()) if (ran.nextBoolean ()) field[j][k] = freeSpace; else field[j][k] = wall; else field[j][k] = freeSpace; field[initPoint.x][initPoint.y] = freeSpace; field[finalPoint.x][finalPoint.y] = freeSpace; return new Labyrinth (field, wall, freeSpace, initPoint.x, initPoint.y, finalPoint.x, finalPoint.y); } }
9240fd849db012951d9e541cd8580677add01dc9
2,738
java
Java
olv-core/src/main/java/pl/otros/logview/api/pluginable/LogFilterValueChangeListenerImpl.java
benlazaro/otroslogviewer
5a8971ffc5369ed72aa1f8de0177bbcfc0a52dca
[ "Apache-2.0" ]
393
2015-03-17T07:10:04.000Z
2022-02-26T21:53:41.000Z
olv-core/src/main/java/pl/otros/logview/api/pluginable/LogFilterValueChangeListenerImpl.java
benlazaro/otroslogviewer
5a8971ffc5369ed72aa1f8de0177bbcfc0a52dca
[ "Apache-2.0" ]
250
2015-03-18T14:44:56.000Z
2022-03-24T19:10:44.000Z
olv-core/src/main/java/pl/otros/logview/api/pluginable/LogFilterValueChangeListenerImpl.java
benlazaro/otroslogviewer
5a8971ffc5369ed72aa1f8de0177bbcfc0a52dca
[ "Apache-2.0" ]
100
2015-03-30T06:04:18.000Z
2022-03-06T11:35:28.000Z
38.56338
167
0.744704
1,001,741
package pl.otros.logview.api.pluginable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pl.otros.logview.api.StatusObserver; import pl.otros.logview.api.gui.LogDataRowFilter; import pl.otros.logview.api.gui.LogDataTableModel; import javax.swing.*; import javax.swing.table.TableRowSorter; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; public class LogFilterValueChangeListenerImpl implements LogFilterValueChangeListener { private static final Logger LOGGER = LoggerFactory.getLogger(LogFilterValueChangeListenerImpl.class.getName()); private final TableRowSorter<LogDataTableModel> rowSorter; private final Collection<LogFilter> logFilters; private final StatusObserver observer; private final JTable table; private int lastKnownSelectedRowInModel = -1; public LogFilterValueChangeListenerImpl(JTable table, TableRowSorter<LogDataTableModel> rowSorter, Collection<LogFilter> logFilters, StatusObserver statusObserver) { super(); this.table = table; this.rowSorter = rowSorter; this.logFilters = logFilters; this.observer = statusObserver; } @Override public void valueChanged() { LOGGER.trace("Value of filter have changed, updating view"); int selectedRow = table.getSelectedRow(); if (selectedRow >= 0) { lastKnownSelectedRowInModel = table.convertRowIndexToModel(selectedRow); } LOGGER.trace("Last selected row is {}", selectedRow); List<LogFilter> enabledFiltersList = logFilters.stream().filter(LogFilter::isEnable).collect(Collectors.toList()); enabledFiltersList.forEach(logFilter -> LOGGER.trace("Filter \"{}\" is in use", logFilter.getName())); LogFilter[] enabledFilters = new LogFilter[enabledFiltersList.size()]; enabledFilters = enabledFiltersList.toArray(enabledFilters); LogDataRowFilter dataRowFilter = new LogDataRowFilter(enabledFilters); rowSorter.setRowFilter(dataRowFilter); int filtered = rowSorter.getViewRowCount(); if (observer != null) { if (filtered > 0) { observer.updateStatus(filtered + " messages passed filters"); } else { observer.updateStatus("No messages passed filters", StatusObserver.LEVEL_ERROR); } } if (lastKnownSelectedRowInModel >= 0 && lastKnownSelectedRowInModel < table.getModel().getRowCount()) { int toSelectInView = table.convertRowIndexToView(lastKnownSelectedRowInModel); if (toSelectInView >= 0) { LOGGER.info("Last selected row was {} (view index: {})", selectedRow, toSelectInView); table.scrollRectToVisible(table.getCellRect(toSelectInView, 0, false)); } else { LOGGER.info("Selected row was filtered out"); } } } }
924100270bc9603301edecaf066da34445c925d0
1,984
java
Java
modules/jaxws-integration/test/org/apache/axis2/jaxws/rpclit/stringarray/sei/Echo.java
sameeragunarathne/wso2-axis2-1
9e3827fb0136a0cb79252bec933bdc01629c03db
[ "Apache-2.0" ]
1
2020-01-05T04:46:29.000Z
2020-01-05T04:46:29.000Z
modules/jaxws-integration/test/org/apache/axis2/jaxws/rpclit/stringarray/sei/Echo.java
sameeragunarathne/wso2-axis2-1
9e3827fb0136a0cb79252bec933bdc01629c03db
[ "Apache-2.0" ]
null
null
null
modules/jaxws-integration/test/org/apache/axis2/jaxws/rpclit/stringarray/sei/Echo.java
sameeragunarathne/wso2-axis2-1
9e3827fb0136a0cb79252bec933bdc01629c03db
[ "Apache-2.0" ]
null
null
null
28.753623
101
0.672883
1,001,742
/* * 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.axis2.jaxws.rpclit.stringarray.sei; import org.test.rpclit.stringarray.StringArray; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.jws.soap.SOAPBinding.Style; /** * This class was generated by the JAXWS SI. * JAX-WS RI 2.0_01-b15-fcs * Generated source version: 2.0 * */ @WebService(name = "Echo", targetNamespace = "http://sei.stringarray.rpclit.jaxws.axis2.apache.org") @SOAPBinding(style = Style.RPC) public interface Echo { /** * * @param arg0 * @return * returns java.lang.String */ @WebMethod @WebResult(partName = "return") public String echoString( @WebParam(name = "arg0", partName = "arg0") String arg0); /** * * @param arg0 * @return * returns org.test.rpclit.stringarray.StringArray */ @WebMethod @WebResult(partName = "return") public StringArray echoStringArray( @WebParam(name = "arg0", partName = "arg0") StringArray arg0); }
924100740529c4d5914cce36be79031bcf7e4f2c
1,179
java
Java
orion-office/src/test/java/com/orion/office/excel/writer/WriteUser.java
lijiahangmax/orion-k
4f097dcb8bbba32001b261c21d06d00708f374df
[ "MIT" ]
2
2022-03-14T03:03:40.000Z
2022-03-24T10:10:25.000Z
orion-office/src/test/java/com/orion/office/excel/writer/WriteUser.java
lijiahangmax/orion-k
4f097dcb8bbba32001b261c21d06d00708f374df
[ "MIT" ]
1
2022-03-03T07:07:34.000Z
2022-03-10T01:19:07.000Z
orion-office/src/test/java/com/orion/office/excel/writer/WriteUser.java
lijiahangmax/orion-k
4f097dcb8bbba32001b261c21d06d00708f374df
[ "MIT" ]
1
2021-06-03T05:26:29.000Z
2021-06-03T05:26:29.000Z
15.932432
48
0.587786
1,001,743
package com.orion.office.excel.writer; import java.math.BigDecimal; import java.util.Date; /** * @author Jiahang Li * @version 1.0.0 * @since 2021/1/14 9:53 */ public class WriteUser { private Long id; private String name; private String formula; private Date date; private BigDecimal balance; private String disable; 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 String getFormula() { return formula; } public void setFormula(String formula) { this.formula = formula; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public BigDecimal getBalance() { return balance; } public void setBalance(BigDecimal balance) { this.balance = balance; } public String getDisable() { return disable; } public void setDisable(String disable) { this.disable = disable; } }
924100cd1e8a2103348eba4ad96b4bb2887a7454
2,905
java
Java
Study_2021/Study_Old/JavaStudy/src/main/java/server/service/Response.java
henghengya/ComputerWorld
162bb1d1b4bd389cb993194e01488a322323fa6e
[ "MulanPSL-1.0" ]
2
2020-08-14T09:45:34.000Z
2022-01-01T06:17:53.000Z
Study_2021/Study_Old/JavaStudy/src/main/java/server/service/Response.java
henghengya/ComputerWorld
162bb1d1b4bd389cb993194e01488a322323fa6e
[ "MulanPSL-1.0" ]
18
2020-12-03T13:26:40.000Z
2022-01-01T06:17:39.000Z
Study_2021/Study_Old/JavaStudy/src/main/java/server/service/Response.java
henghengya/ComputerWorld
162bb1d1b4bd389cb993194e01488a322323fa6e
[ "MulanPSL-1.0" ]
null
null
null
29.343434
107
0.562478
1,001,744
package server.service; import java.io.*; import java.net.Socket; import java.util.Date; /** * 封装response信息 * * @Date 2020/02/15 23:42 * @Created by lan-mao.top */ public class Response implements Closeable { private Socket socket; private StringBuilder content; private StringBuilder headers; private int code; private long length; private static final String BLANK = " "; private static final String CRLF = "\r\n"; private BufferedWriter bufferedWriter ; { content = new StringBuilder(); headers = new StringBuilder(); length = 0; } public Response(Socket socket){ this.socket = socket; try { bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF-8")); } catch (IOException e) { e.printStackTrace(); } } public Response(OutputStream outputStream){ try { bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } private void setHeaders(int code){ headers.append("HTTP/1.1").append(BLANK); switch (code){ case 404:{ headers.append(404).append(BLANK).append("NOT FOUND"); break; } case 505:{ headers.append(200).append(BLANK).append("SERVER ERROR"); break; } default:{ headers.append(200).append(BLANK).append("OK"); break; } } headers.append(CRLF); headers.append("Date:").append(new Date()).append(CRLF); headers.append("Content-type:text/html;charset=UTF-8").append(CRLF); headers.append("Server:").append("TestServer/0.0.1").append(CRLF); headers.append("Content-Length:").append(length).append(CRLF); headers.append(CRLF); } public Response print(String content){ this.content.append(content); length += content.getBytes().length; return this; } public Response println(String content){ return print(content + "\n"); } public void send(int code){ setHeaders(code); System.out.println("------------"); System.out.println(headers); System.out.println(content); System.out.println("------------"); try { bufferedWriter.append(headers).append(content); bufferedWriter.flush(); } catch (IOException e) { e.printStackTrace(); } } @Override public void close() throws IOException { if (socket!=null){ socket.shutdownOutput(); }else { if (bufferedWriter!=null){ bufferedWriter.close(); } } } }
92410351831f5564ecdfebabadadb486a4ca98f4
654
java
Java
src/main/java/com/contrastsecurity/cassandra/migration/utils/CachePrepareStatement.java
mhowarth/cassandra-migration
a1c022c7f054ae8e6b41e072998ff8db67756102
[ "ECL-2.0", "Apache-2.0" ]
122
2015-08-29T16:03:54.000Z
2022-03-17T12:08:57.000Z
src/main/java/com/contrastsecurity/cassandra/migration/utils/CachePrepareStatement.java
mhowarth/cassandra-migration
a1c022c7f054ae8e6b41e072998ff8db67756102
[ "ECL-2.0", "Apache-2.0" ]
28
2015-08-31T14:42:39.000Z
2019-03-15T15:47:59.000Z
src/main/java/com/contrastsecurity/cassandra/migration/utils/CachePrepareStatement.java
mhowarth/cassandra-migration
a1c022c7f054ae8e6b41e072998ff8db67756102
[ "ECL-2.0", "Apache-2.0" ]
70
2015-08-31T10:57:12.000Z
2021-12-16T10:46:14.000Z
25.153846
98
0.772171
1,001,745
package com.contrastsecurity.cassandra.migration.utils; import java.util.concurrent.ConcurrentHashMap; import com.datastax.driver.core.PreparedStatement; import com.datastax.driver.core.Session; public class CachePrepareStatement { private ConcurrentHashMap<Integer, PreparedStatement> cacheStatement = new ConcurrentHashMap<>(); private Session session; public CachePrepareStatement(Session session) { this.session = session; } public PreparedStatement prepare(String s){ PreparedStatement ps = cacheStatement.get(s.hashCode()); if(ps == null){ ps = session.prepare(s); cacheStatement.put(s.hashCode(), ps); } return ps; } }
9241068544d7022a3df450aae01a39d2b66a12dd
730
java
Java
app/src/main/java/com/example/terry/huaqiweather/db/Province.java
Terry-XuZhou/huaqiweather
32033927975f61a47850d5eb1d8b5d93184bbe97
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/terry/huaqiweather/db/Province.java
Terry-XuZhou/huaqiweather
32033927975f61a47850d5eb1d8b5d93184bbe97
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/terry/huaqiweather/db/Province.java
Terry-XuZhou/huaqiweather
32033927975f61a47850d5eb1d8b5d93184bbe97
[ "Apache-2.0" ]
null
null
null
21.470588
53
0.669863
1,001,746
package com.example.terry.huaqiweather.db; import org.litepal.crud.DataSupport; import java.security.PublicKey; /** * Created by terry on 2018/5/24. */ public class Province extends DataSupport{ private int id; private String provinceName; private int provinceCode; public int getId(){ return id; } public void setId(int id){ this.id=id; } public String getProvinceName(){ return provinceName; } public void setProvinceName(String provinceName){ this.provinceName=provinceName; } public int getProvinceCode(){ return provinceCode; } public void setProvinceCode(int provinceCode){ this.provinceCode=provinceCode; } }
924106ad6006d516f9ac700fdb159928b7fb6bb7
2,094
java
Java
CodiceFiscaleGUI/src/codicefiscale/MeseNascita.java
xStevatt/CodiceFiscale
3fe95f77eac95eb310d254862923d8d7ca622520
[ "MIT" ]
null
null
null
CodiceFiscaleGUI/src/codicefiscale/MeseNascita.java
xStevatt/CodiceFiscale
3fe95f77eac95eb310d254862923d8d7ca622520
[ "MIT" ]
null
null
null
CodiceFiscaleGUI/src/codicefiscale/MeseNascita.java
xStevatt/CodiceFiscale
3fe95f77eac95eb310d254862923d8d7ca622520
[ "MIT" ]
null
null
null
30.347826
98
0.570678
1,001,747
package codicefiscale; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; /** * * @author xStevatt */ public class MeseNascita { public String workOnMese(String mesenascita) { String codicefiscale = ""; if(mesenascita.equalsIgnoreCase("Gennaio") || mesenascita.equalsIgnoreCase("January")) { codicefiscale = "A"; } if(mesenascita.equalsIgnoreCase("Febbraio") || mesenascita.equalsIgnoreCase("February")) { codicefiscale = "B"; } if(mesenascita.equalsIgnoreCase("Marzo") || mesenascita.equalsIgnoreCase("March")) { codicefiscale = "C"; } if(mesenascita.equalsIgnoreCase("Aprile") || mesenascita.equalsIgnoreCase("April")) { codicefiscale = "D"; } if(mesenascita.equalsIgnoreCase("Maggio") || mesenascita.equalsIgnoreCase("May")) { codicefiscale = "E"; } if(mesenascita.equalsIgnoreCase("Giugno") || mesenascita.equalsIgnoreCase("June")) { codicefiscale = "H"; } if(mesenascita.equalsIgnoreCase("Luglio") || mesenascita.equalsIgnoreCase("July")) { codicefiscale = "L"; } if(mesenascita.equalsIgnoreCase("Agosto") || mesenascita.equalsIgnoreCase("August")) { codicefiscale = "M"; } if(mesenascita.equalsIgnoreCase("Settembre") || mesenascita.equalsIgnoreCase("September")) { codicefiscale = "P"; } if(mesenascita.equalsIgnoreCase("Ottobre") || mesenascita.equalsIgnoreCase("October")) { codicefiscale = "R"; } if(mesenascita.equalsIgnoreCase("Novembre") || mesenascita.equalsIgnoreCase("November")) { codicefiscale = "S"; } if(mesenascita.equalsIgnoreCase("Dicembre") || mesenascita.equalsIgnoreCase("December")) { codicefiscale = "T"; } return codicefiscale; } }
9241075f7bee96ce0342fd90940167565db9eacc
825
java
Java
spinach/spinach-frame/src/main/java/com/yang/spinach/frame/utils/XmlUtil.java
yangb0/spinach
b4b5f9827b692b284c70c61ddf65dad813129b25
[ "Apache-2.0" ]
8
2015-07-05T13:48:38.000Z
2017-01-03T00:59:03.000Z
spinach/spinach-frame/src/main/java/com/yang/spinach/frame/utils/XmlUtil.java
yangb0/spinach
b4b5f9827b692b284c70c61ddf65dad813129b25
[ "Apache-2.0" ]
null
null
null
spinach/spinach-frame/src/main/java/com/yang/spinach/frame/utils/XmlUtil.java
yangb0/spinach
b4b5f9827b692b284c70c61ddf65dad813129b25
[ "Apache-2.0" ]
null
null
null
22.916667
84
0.707879
1,001,748
package com.yang.spinach.frame.utils; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; /** * 通过XStream进行xml与java Bean 的转换 */ public class XmlUtil { private static final String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?> "; /** * java bean 转化为xml * * @param object * @param objClass * @return */ public static String parseBeanToXml(Object object, Class<?> objClass) { String xmlString = ""; XStream xStream = new XStream(new DomDriver()); xStream.processAnnotations(objClass); xmlString = xStream.toXML(object); xmlString = header + xmlString; return xmlString; } public static Object fromXml(String xml, Class<?> objClass) { XStream xStream = new XStream(); xStream.processAnnotations(objClass); return xStream.fromXML(xml); } }
9241079b37d698a8c74c5340582594b592db6b9b
2,305
java
Java
appfabric-uaa/src/main/java/com/davidche/appfabric/uaa/service/PasswordResetTokenService.java
DavidSche/appfabric
f8e191b5c6f87ade55fd6449fad12adbd164de8a
[ "Apache-2.0" ]
null
null
null
appfabric-uaa/src/main/java/com/davidche/appfabric/uaa/service/PasswordResetTokenService.java
DavidSche/appfabric
f8e191b5c6f87ade55fd6449fad12adbd164de8a
[ "Apache-2.0" ]
null
null
null
appfabric-uaa/src/main/java/com/davidche/appfabric/uaa/service/PasswordResetTokenService.java
DavidSche/appfabric
f8e191b5c6f87ade55fd6449fad12adbd164de8a
[ "Apache-2.0" ]
null
null
null
35.461538
97
0.742733
1,001,749
package com.davidche.appfabric.uaa.service; import com.davidche.appfabric.uaa.exception.InvalidTokenRequestException; import com.davidche.appfabric.uaa.log.MyLoggable; import com.davidche.appfabric.uaa.model.PasswordResetToken; import com.davidche.appfabric.uaa.repository.PasswordResetTokenRepository; import com.davidche.appfabric.uaa.util.Util; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.time.Instant; import java.util.Optional; @MyLoggable @Service public class PasswordResetTokenService { private final PasswordResetTokenRepository passwordResetTokenRepository; @Value("${app.token.password.reset.duration}") private Long expiration; @Autowired public PasswordResetTokenService(PasswordResetTokenRepository passwordResetTokenRepository) { this.passwordResetTokenRepository = passwordResetTokenRepository; } /** * Saves the given password reset token */ public PasswordResetToken save(PasswordResetToken passwordResetToken) { return passwordResetTokenRepository.save(passwordResetToken); } /** * Finds a token in the database given its naturalId */ public Optional<PasswordResetToken> findByToken(String token) { return passwordResetTokenRepository.findByToken(token); } /** * Creates and returns a new password token to which a user must be associated */ public PasswordResetToken createToken() { PasswordResetToken passwordResetToken = new PasswordResetToken(); String token = Util.generateRandomUuid(); passwordResetToken.setToken(token); passwordResetToken.setExpiryDate(Instant.now().plusMillis(expiration)); return passwordResetToken; } /** * Verify whether the token provided has expired or not on the basis of the current * server time and/or throw error otherwise */ public void verifyExpiration(PasswordResetToken token) { if (token.getExpiryDate().compareTo(Instant.now()) < 0) { throw new InvalidTokenRequestException("Password Reset Token", token.getToken(), "Expired token. Please issue a new request"); } } }
924108e5550b50913f66cebbf55578023cbdb7ef
2,895
java
Java
Java/atcoder/beginner_100_199/beginner_109/C.java
nirvanarsc/CompetitiveProgramming
e96d446285a6872b0a922278355cd0f9319155b8
[ "MIT" ]
2
2021-06-02T16:11:46.000Z
2021-12-23T20:37:02.000Z
Java/atcoder/beginner_100_199/beginner_109/C.java
nirvanarsc/CompetitiveProgramming
e96d446285a6872b0a922278355cd0f9319155b8
[ "MIT" ]
null
null
null
Java/atcoder/beginner_100_199/beginner_109/C.java
nirvanarsc/CompetitiveProgramming
e96d446285a6872b0a922278355cd0f9319155b8
[ "MIT" ]
1
2021-05-14T14:19:14.000Z
2021-05-14T14:19:14.000Z
26.559633
81
0.463903
1,001,750
package atcoder.beginner_100_199.beginner_109; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Random; import java.util.StringTokenizer; public final class C { public static int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } public static void main(String[] args) { final FastScanner fs = new FastScanner(); final int n = fs.nextInt(); final int x = fs.nextInt(); final int[] arr = fs.nextIntArray(n); int res = Math.abs(x - arr[0]); for (int i = 0; i < n; i++) { res = gcd(res, Math.abs(x - arr[i])); } System.out.println(res); } static final class Util { public static void shuffleSort(int[] x) { shuffle(x); Arrays.sort(x); } public static void shuffleSort(long[] x) { shuffle(x); Arrays.sort(x); } public static void shuffle(int[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } public static void shuffle(long[] x) { final Random r = new Random(); for (int i = 0; i <= x.length - 2; i++) { final int j = i + r.nextInt(x.length - i); swap(x, i, j); } } public static void swap(int[] x, int i, int j) { final int t = x[i]; x[i] = x[j]; x[j] = t; } public static void swap(long[] x, int i, int j) { final long t = x[i]; x[i] = x[j]; x[j] = t; } private Util() {} } static class FastScanner { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(""); private String next() { while (!st.hasMoreTokens()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { //noinspection CallToPrintStackTrace e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } int[] nextIntArray(int n) { final int[] a = new int[n]; for (int i = 0; i < n; i++) { a[i] = nextInt(); } return a; } long[] nextLongArray(int n) { final long[] a = new long[n]; for (int i = 0; i < n; i++) { a[i] = nextLong(); } return a; } } }
9241090fdcf4c005894544db5594a40743128b6a
2,856
java
Java
gojek-commons-jpa/src/test/java/com/gojek/jpa/util/ArrayTypeTest.java
Masriyan/gojek-commons
b9a0cfef7b3a30eacb4d5262e43dd2ca321504c9
[ "Apache-2.0" ]
23
2017-11-26T18:05:48.000Z
2021-01-11T02:47:47.000Z
gojek-commons-jpa/src/test/java/com/gojek/jpa/util/ArrayTypeTest.java
Masriyan/gojek-commons
b9a0cfef7b3a30eacb4d5262e43dd2ca321504c9
[ "Apache-2.0" ]
6
2017-12-26T07:45:48.000Z
2018-02-05T08:49:25.000Z
gojek-commons-jpa/src/test/java/com/gojek/jpa/util/ArrayTypeTest.java
Masriyan/gojek-commons
b9a0cfef7b3a30eacb4d5262e43dd2ca321504c9
[ "Apache-2.0" ]
12
2017-12-15T03:14:16.000Z
2021-01-29T09:20:09.000Z
34
132
0.771359
1,001,751
/** * */ package com.gojek.jpa.util; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import java.sql.Array; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SharedSessionContractImplementor; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * @author ganeshs * */ public class ArrayTypeTest { private ArrayType arrayType; @BeforeMethod public void setup() { arrayType = new ArrayType(); } @Test public void shouldGetArrayFromResultSet() throws HibernateException, SQLException { String[] expected = new String[] {"test1", "test2"}; ResultSet rs = mock(ResultSet.class); Array array = mock(Array.class); when(array.getArray()).thenReturn(expected); when(rs.getArray("some_name")).thenReturn(array); assertEquals(arrayType.nullSafeGet(rs, new String[] {"some_name"}, mock(SharedSessionContractImplementor.class), null), expected); } @Test public void shouldReturnNullIfResultFieldIsNull() throws HibernateException, SQLException { ResultSet rs = mock(ResultSet.class); when(rs.getArray("some_name")).thenReturn(null); assertNull(arrayType.nullSafeGet(rs, new String[] {"some_name"}, mock(SharedSessionContractImplementor.class), null)); } @Test public void shouldReturnNullIfResultArrayIsNull() throws HibernateException, SQLException { ResultSet rs = mock(ResultSet.class); Array array = mock(Array.class); when(array.getArray()).thenReturn(null); when(rs.getArray("some_name")).thenReturn(array); assertNull(arrayType.nullSafeGet(rs, new String[] {"some_name"}, mock(SharedSessionContractImplementor.class), null)); } @Test public void shouldSetArrayToStatement() throws HibernateException, SQLException { String[] value = new String[] {"test1", "test2"}; SharedSessionContractImplementor session = mock(SharedSessionContractImplementor.class); Connection connection = mock(Connection.class); Array array = mock(Array.class); when(connection.createArrayOf("text", value)).thenReturn(array); when(session.connection()).thenReturn(connection); PreparedStatement st = mock(PreparedStatement.class); arrayType.nullSafeSet(st, value, 0, session); verify(st).setArray(0, array); } @Test public void shouldSetNullArrayToStatement() throws HibernateException, SQLException { SharedSessionContractImplementor session = mock(SharedSessionContractImplementor.class); PreparedStatement st = mock(PreparedStatement.class); arrayType.nullSafeSet(st, null, 0, session); verify(st).setNull(0, Types.ARRAY); } }
9241095af3721fa31014b5e05824cc5940328209
976
java
Java
files/java/Scrabble/ImagesCache.java
soumya997/daattali.github.io
f94657a2417a9dfd6d2180a05e5bc28a9aaf038f
[ "MIT" ]
60
2015-03-01T00:48:35.000Z
2022-01-06T01:10:27.000Z
files/java/Scrabble/ImagesCache.java
soumya997/daattali.github.io
f94657a2417a9dfd6d2180a05e5bc28a9aaf038f
[ "MIT" ]
20
2015-03-26T20:56:16.000Z
2021-02-21T21:03:55.000Z
files/java/Scrabble/ImagesCache.java
soumya997/daattali.github.io
f94657a2417a9dfd6d2180a05e5bc28a9aaf038f
[ "MIT" ]
468
2015-05-19T20:48:32.000Z
2022-03-22T22:26:48.000Z
23.238095
84
0.673156
1,001,752
import java.util.HashMap; import javax.swing.ImageIcon; import java.net.URL; /** * Dean Attali<br> * March 10, 2006<br><br> * * This class is a cache of all the images (letters).<br> * Instead of loading the images all the time, this only loads * an image once using a HashMap * * @author Dean Attali * @version 1 March 2006 */ public class ImagesCache { // A hashmap that relates sprites with their names private static HashMap<String, ImageIcon> sprites=new HashMap<String, ImageIcon>(); /** * Returns the specified image * @param name the name of the image * @return the sprite, as an ImageIcon **/ public static ImageIcon getSprite(String name) { ImageIcon img = sprites.get(name); if (img == null) { Debug.println("Image "+name+ " loaded"); try{ URL url = new URL("https://deanattali.com/files/java/Scrabble/" + name); img = new ImageIcon(url); }catch(Exception ex){} sprites.put(name,img); } return img; } }
92410a38086a23430a95d4b613ba0657e705a7ed
1,347
java
Java
consumer/src/main/java/com/breach/huajinbao/service/quest/Impl/RequestServiceImpl.java
breaches/Financial
c53cefa30355f020e435820afd427cb89d151a80
[ "MIT" ]
7
2019-01-23T23:57:25.000Z
2022-03-15T05:43:11.000Z
consumer/src/main/java/com/breach/huajinbao/service/quest/Impl/RequestServiceImpl.java
breaches/Financial
c53cefa30355f020e435820afd427cb89d151a80
[ "MIT" ]
null
null
null
consumer/src/main/java/com/breach/huajinbao/service/quest/Impl/RequestServiceImpl.java
breaches/Financial
c53cefa30355f020e435820afd427cb89d151a80
[ "MIT" ]
4
2019-03-04T08:11:25.000Z
2020-09-15T01:32:37.000Z
29.933333
82
0.715664
1,001,753
package com.breach.huajinbao.service.quest.Impl; import com.breach.common.entity.ConsumerQuestionnaire; import com.breach.common.mapper.IConsumerQuestionnaireMapper; import com.breach.huajinbao.service.quest.IRequestService; import com.breach.huajinbao.util.global.GlobalConsumerUtil; import com.breach.huajinbao.util.quest.test; import com.breach.huajinbao.util.sign.ConsumerSessionUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; @Service public class RequestServiceImpl implements IRequestService { @Autowired private IConsumerQuestionnaireMapper consumerQuestionnaireMapper; String s=null; @Override public Map quest1(ConsumerQuestionnaire q) { if(GlobalConsumerUtil.isLogin()) { q.setConsumerId(ConsumerSessionUtil.getConsumer().getConsumerId()); ConsumerQuestionnaire consumerQuestionnaire = q.setType(test.test1()); String type = consumerQuestionnaire.getType(); s=type; consumerQuestionnaireMapper.insert(q); }else { HashMap map = new HashMap(); map.put("cuowu", 200); return map; } return null; } @Override public String end() { return s; } }
92410a5ccdb014d5f6be1f3c21e6c54790f62121
4,684
java
Java
toggle-impl/src/test/java/com.xpto.impl/ToggleServiceImplTest.java
pdcarv/lagom-toggle-router
703049df9ac6cb1e1e63772786c62813335ef381
[ "Apache-2.0" ]
null
null
null
toggle-impl/src/test/java/com.xpto.impl/ToggleServiceImplTest.java
pdcarv/lagom-toggle-router
703049df9ac6cb1e1e63772786c62813335ef381
[ "Apache-2.0" ]
null
null
null
toggle-impl/src/test/java/com.xpto.impl/ToggleServiceImplTest.java
pdcarv/lagom-toggle-router
703049df9ac6cb1e1e63772786c62813335ef381
[ "Apache-2.0" ]
null
null
null
37.174603
190
0.70047
1,001,754
package com.xpto.impl; import akka.Done; import com.lightbend.lagom.javadsl.api.transport.Forbidden; import com.lightbend.lagom.javadsl.api.transport.NotFound; import com.lightbend.lagom.javadsl.testkit.ServiceTest; import com.xpto.api.FeatureMessage; import com.xpto.api.ToggleService; import com.xpto.impl.toggleRouter.Router; import com.xpto.impl.toggleRouter.ToggleRouter; import lombok.Value; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import javax.inject.Inject; import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import static com.lightbend.lagom.javadsl.testkit.ServiceTest.defaultSetup; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static play.inject.Bindings.bind; public class ToggleServiceImplTest { private static ServiceTest.TestServer testServer; private static ToggleService toggleService; private final static ServiceTest.Setup setup = defaultSetup().withCassandra(true) .configureBuilder(b -> // by default, cassandra-query-journal delays propagation of events by 10sec. In test we're using // a 1 node cluster so this delay is not necessary. b.configure("cassandra-query-journal.eventual-consistency-delay", "0") .overrides( bind(ToggleRouter.Factory.class).to(FactoryStub.class), bind(Router.class).to(ToggleRouterStub.class)) ); private static FeatureMessage message; @BeforeClass public static void beforeAll() { testServer = ServiceTest.startServer(setup); toggleService = testServer.client(ToggleService.class); message = new FeatureMessage("1", "redButton", "1", "abc", true, true); } @AfterClass public static void afterAll() { testServer.stop(); } @Test public void shouldBeAbleToCreateAFeatureWhenUserIsAdmin() throws Exception { assertThat(createFeature(message, new Header("User-Token", "Xm28dxc"))).isInstanceOf(Done.class); } @Test public void shouldNotBeAbleToCreateAFeatureIfIfUserIsNotAnAdmin() throws Exception { assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> createFeature(message, new Header("User-Token", "da39a3e"))).withMessage(String.valueOf(new Forbidden("You must have admin privileges"))); } @Test public void shouldBeAbleToRetrieveAFeatureIfExists() throws Exception { createFeature(message, new Header("User-Token", "Xm28dxc")); assertThat(getFeature(message.getId(), message.getVersion())).isEqualTo(message); } @Test public void shouldThrowNotFoundWhenFeatureDoesNotExist() throws Exception { assertThatExceptionOfType(ExecutionException.class).isThrownBy(() -> getFeature("2", "3")).withCauseInstanceOf(NotFound.class); } @Test public void shouldBeAbleToTellIfAToggleIsEnabled() throws Exception { createFeature(message, new Header("User-Token", "Xm28dxc")); assertThat(isFeatureEnabled(message)).isTrue(); } private Boolean isFeatureEnabled(FeatureMessage featureMessage) throws Exception { return toggleService.isEnabled(featureMessage.getId(), featureMessage.getVersion()).invoke().toCompletableFuture().get(5, TimeUnit.SECONDS); } private Done createFeature(FeatureMessage featureMessage, Header header) throws Exception { return toggleService.createToggle().handleRequestHeader(f -> f.withHeader(header.getName(), header.getValue())).invoke(featureMessage).toCompletableFuture().get(5, TimeUnit.SECONDS); } private FeatureMessage getFeature(String id, String version) throws Exception { return toggleService.toggle(id, version).invoke().toCompletableFuture().get(5, TimeUnit.SECONDS); } @Value public static class Header { private final String name; private final String value; } public static class ToggleRouterStub implements Router { @Inject public ToggleRouterStub() { } @Override public Boolean isEnabled() { return true; } @Override public Boolean isDisabled() { return false; } } public static class FactoryStub implements ToggleRouter.Factory { @Override public Router buildInstance(Optional<String> serviceName, Feature feature) { return new ToggleRouterStub(); } } }
92410a64d47dc0727b706e34a7d09c2ac57c6e88
589
java
Java
Chapter06/DebuggingExercises/DebugSix2.java
mavaddat-javid-education/java-debugging-DucklyFish
b057dd64020a5fa3e86de74584f15e1747c7ff72
[ "MIT" ]
7
2020-02-10T02:48:50.000Z
2022-03-23T01:39:03.000Z
Chapter06/DebuggingExercises/DebugSix2.java
mavaddat-javid-education/java-debugging-DucklyFish
b057dd64020a5fa3e86de74584f15e1747c7ff72
[ "MIT" ]
null
null
null
Chapter06/DebuggingExercises/DebugSix2.java
mavaddat-javid-education/java-debugging-DucklyFish
b057dd64020a5fa3e86de74584f15e1747c7ff72
[ "MIT" ]
4
2019-12-05T17:00:39.000Z
2022-02-02T23:30:47.000Z
28.047619
54
0.558574
1,001,755
// DebugSix2.java // Display every character between Unicode 65 and 122 // Start new line after 20 characters public class DebugSix2 { public static void main(String args[]) { char letter; int a; final int MIN = 65; final int MAX = 122; final int STOPLINE1 = 85; final int STOPLINE2 = 122; for(a = MIN; a <= MAX; a++) letter = (char)a; System.out.print(" " + letter); if((a == STOPLINE1) & (a == STOPLINE2)) System.out.println(); System.out.println("\nEnd of application") } }
92410b4ed52487997b226fdc9626fa5723333e55
1,067
java
Java
common/src/main/java/io/nybbles/progcalc/common/ResultMessage.java
jeffpanici75/programmers-calculator
8eb26c55ba5363133d0f5fac38005be0569e3b04
[ "MIT" ]
1
2020-04-07T15:48:09.000Z
2020-04-07T15:48:09.000Z
common/src/main/java/io/nybbles/progcalc/common/ResultMessage.java
jeffpanici75/programmers-calculator
8eb26c55ba5363133d0f5fac38005be0569e3b04
[ "MIT" ]
null
null
null
common/src/main/java/io/nybbles/progcalc/common/ResultMessage.java
jeffpanici75/programmers-calculator
8eb26c55ba5363133d0f5fac38005be0569e3b04
[ "MIT" ]
1
2021-03-10T00:51:33.000Z
2021-03-10T00:51:33.000Z
20.921569
95
0.626054
1,001,756
package io.nybbles.progcalc.common; public class ResultMessage { private String _code; private String _message; private String _details; private ResultMessageType _type = ResultMessageType.Info; public ResultMessage() { } public ResultMessage(ResultMessageType type, String code, String message) { _type = type; _code = code; _message = message; } public ResultMessage(ResultMessageType type, String code, String message, String details) { this(type, code, message); _details = details; } public String getCode() { return _code; } public void setCode(String code) { this._code = code; } public String getMessage() { return _message; } public void setMessage(String message) { _message = message; } public String getDetails() { return _details; } public void setDetails(String details) { _details = details; } public ResultMessageType getType() { return _type; } }
92410b6d59cd856fc81343de8b592b6cb0607d4c
1,378
java
Java
src/main/java/com/lithium/mineraloil/jmeter/test_elements/LoopElement.java
MatthewBramer/mineraloil-jmeter
c650dd7a11616f74c867f3576580539cedabf3f1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/lithium/mineraloil/jmeter/test_elements/LoopElement.java
MatthewBramer/mineraloil-jmeter
c650dd7a11616f74c867f3576580539cedabf3f1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/lithium/mineraloil/jmeter/test_elements/LoopElement.java
MatthewBramer/mineraloil-jmeter
c650dd7a11616f74c867f3576580539cedabf3f1
[ "Apache-2.0" ]
null
null
null
38.277778
92
0.758345
1,001,757
package com.lithium.mineraloil.jmeter.test_elements; import com.google.common.base.Preconditions; import lombok.Builder; import org.apache.jmeter.control.LoopController; import org.apache.jmeter.control.gui.LoopControlPanel; import org.apache.jmeter.testelement.TestElement; @Builder public class LoopElement extends JMeterStepImpl<LoopElement> { private String name; private Integer loopCount; private Boolean continueForever; private Boolean isFirst; // for cases where it's a test element public TestElement getTestElement() { return getLoopController(); } // for cases where it's pulled in to a ThreadGroupElement public LoopController getLoopController() { Preconditions.checkNotNull(name); LoopController loopController = new LoopController(); loopController.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName()); loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName()); loopController.setProperty(TestElement.NAME, name); loopController.setProperty(TestElement.ENABLED, true); loopController.setLoops(getOptionalValue(loopCount, 1)); loopController.setContinueForever(getOptionalValue(continueForever, false)); loopController.setFirst(getOptionalValue(isFirst, true)); return loopController; } }
92410b858fc794a56668c57cba024cee26d5c532
532
java
Java
app/src/main/java/com/martinrevert/latorrentola/SettingsFragment.java
martinrevert/LaTorrentola
53990fe7b20c452d656afc74fb0f187e3e33d20a
[ "MIT" ]
null
null
null
app/src/main/java/com/martinrevert/latorrentola/SettingsFragment.java
martinrevert/LaTorrentola
53990fe7b20c452d656afc74fb0f187e3e33d20a
[ "MIT" ]
null
null
null
app/src/main/java/com/martinrevert/latorrentola/SettingsFragment.java
martinrevert/LaTorrentola
53990fe7b20c452d656afc74fb0f187e3e33d20a
[ "MIT" ]
null
null
null
19
63
0.731203
1,001,758
package com.martinrevert.latorrentola; import android.os.Bundle; import android.preference.PreferenceFragment; import androidx.annotation.Nullable; /** * A simple {@link Fragment} subclass. */ public class SettingsFragment extends PreferenceFragment { public SettingsFragment() { // Required empty public constructor } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); } }
92410bec4e62f0642158a2ca9fb87e67751381cb
1,100
java
Java
ruoyi-admin/src/main/java/com/ruoyi/code/service/IAppraisedtorService.java
XXLdu/fyjd
7172f4722106af6579a924c7a396c4d44d9d08d5
[ "MIT" ]
null
null
null
ruoyi-admin/src/main/java/com/ruoyi/code/service/IAppraisedtorService.java
XXLdu/fyjd
7172f4722106af6579a924c7a396c4d44d9d08d5
[ "MIT" ]
null
null
null
ruoyi-admin/src/main/java/com/ruoyi/code/service/IAppraisedtorService.java
XXLdu/fyjd
7172f4722106af6579a924c7a396c4d44d9d08d5
[ "MIT" ]
null
null
null
17.741935
80
0.591818
1,001,759
package com.ruoyi.code.service; import java.util.List; import com.ruoyi.code.domain.Appraisedtor; /** * 被鉴定人Service接口 * * @author ruoyi * @date 2020-05-31 */ public interface IAppraisedtorService { /** * 查询被鉴定人 * * @param id 被鉴定人ID * @return 被鉴定人 */ public Appraisedtor selectAppraisedtorById(String id); /** * 查询被鉴定人列表 * * @param appraisedtor 被鉴定人 * @return 被鉴定人集合 */ public List<Appraisedtor> selectAppraisedtorList(Appraisedtor appraisedtor); /** * 新增被鉴定人 * * @param appraisedtor 被鉴定人 * @return 结果 */ public int insertAppraisedtor(Appraisedtor appraisedtor); /** * 修改被鉴定人 * * @param appraisedtor 被鉴定人 * @return 结果 */ public int updateAppraisedtor(Appraisedtor appraisedtor); /** * 批量删除被鉴定人 * * @param ids 需要删除的数据ID * @return 结果 */ public int deleteAppraisedtorByIds(String ids); /** * 删除被鉴定人信息 * * @param id 被鉴定人ID * @return 结果 */ public int deleteAppraisedtorById(String id); }
92410c0d55c9739153e7dab724a8d4f8619c2bfe
10,530
java
Java
jmq-client/jmq-client-core/src/test/java/com/ipd/jmq/client/SelectPartitionTest.java
tiglabs-workspace/jmq
b8823da6d75e6fea39939ddcc2757eaa70aa3663
[ "Apache-2.0" ]
null
null
null
jmq-client/jmq-client-core/src/test/java/com/ipd/jmq/client/SelectPartitionTest.java
tiglabs-workspace/jmq
b8823da6d75e6fea39939ddcc2757eaa70aa3663
[ "Apache-2.0" ]
null
null
null
jmq-client/jmq-client-core/src/test/java/com/ipd/jmq/client/SelectPartitionTest.java
tiglabs-workspace/jmq
b8823da6d75e6fea39939ddcc2757eaa70aa3663
[ "Apache-2.0" ]
1
2018-12-13T02:01:39.000Z
2018-12-13T02:01:39.000Z
36.061644
177
0.496011
1,001,760
package com.ipd.jmq.client; import com.ipd.jmq.client.connection.ClusterTransportManager; import com.ipd.jmq.client.connection.TransportConfig; import com.ipd.jmq.client.connection.TransportManager; import com.ipd.jmq.common.model.ConsumerConfig; import com.ipd.jmq.client.consumer.ConsumerStrategy; import com.ipd.jmq.client.consumer.MessageConsumer; import com.ipd.jmq.client.consumer.MessageListener; import com.ipd.jmq.client.producer.LoadBalance; import com.ipd.jmq.client.producer.MessageProducer; import com.ipd.jmq.common.cluster.TopicConfig; import com.ipd.jmq.common.exception.JMQException; import com.ipd.jmq.common.message.Message; import com.ipd.jmq.common.network.v3.netty.failover.ElectTransport; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.List; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicLong; /** * 测试选择partition发送与消费,包含指定partition生产和消费以及非指定partition生产和消费 * * Created by zhangkepeng on 15-11-18. */ public class SelectPartitionTest { private static final Logger logger = Logger.getLogger(SelectPartitionTest.class); private TransportManager manager; private MessageProducer producer; private MessageConsumer messageConsumer; private AtomicLong producerCount = new AtomicLong(1); private AtomicLong errProducerCount = new AtomicLong(1); private AtomicLong consumerCount = new AtomicLong(1); private String topic = "abc"; private String app = "abc"; private String address="10.12.167.47:50088"; /** * 开启连接 */ @Before public void setUp() throws Exception { TransportConfig config = new TransportConfig(); config.setApp(app); //设置broker地址 config.setAddress(address); //设置用户名 config.setUser("jmq"); //设置密码 config.setPassword("jmq"); //设置发送超时 config.setSendTimeout(10000); //设置是否使用epoll模式,windows环境下设置为false,linux环境下设置为true config.setEpoll(true); //创建集群连接管理器 manager = new ClusterTransportManager(config); manager.start(); } /** * 关闭连接资源 * @throws Exception */ @After public void terDown() throws Exception { if (manager != null) { manager.stop(); } if (producer != null) { producer.stop(); } if (messageConsumer != null) { messageConsumer.stop(); } } /** * 测试指定partition消费 * * @throws Exception */ @Test public void testSelectPartitionProducer() throws Exception { //创建发送者 producer = new MessageProducer(manager); producer.setLoadBalance(new ProducerLoadBalanceTest()); producer.setTransportManager(manager); producer.start(); Thread.sleep(3000); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 100; i++) { try{ send(i); logger.info("producer count is " + producerCount.getAndIncrement()); }catch (Exception e){ e.printStackTrace(); logger.info("error count is " + errProducerCount.getAndIncrement()); System.out.println("error i = "+i); } } } }).start(); CountDownLatch latch = new CountDownLatch(1); latch.await(); } /** * 远程与本地消费消息,远程与本地可以在消费策略上进行配置 * * @throws Exception */ @Test public void testConsumer() throws Exception{ ConsumerConfig consumerConfig = new ConsumerConfig(); messageConsumer = new MessageConsumer(consumerConfig, manager, null); new Thread(new Runnable() { @Override public void run() { try { messageConsumer.start(); } catch (Exception e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } messageConsumer.subscribe(topic, new MessageListener() { @Override public void onMessage(List<Message> messages) throws Exception { if (messages != null && !messages.isEmpty()) { for (Message msg : messages) { logger.info("message queueId is " + msg.getQueueId()); logger.info("consumer count is " + consumerCount.getAndIncrement()); } } } }); } }).start(); CountDownLatch latch = new CountDownLatch(1); latch.await(); } /** * 发送消息 * * @throws Exception */ @Test public void testProducer() throws Exception { //创建发送者 producer = new MessageProducer(manager); producer.setTransportManager(manager); producer.start(); Thread.sleep(3000); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 44; i++) { try{ send(i); logger.info("producer count is " + producerCount.getAndIncrement()); }catch (Exception e){ e.printStackTrace(); logger.info("error count is " + errProducerCount.getAndIncrement()); System.out.println("error i = "+i); } } } }).start(); CountDownLatch latch = new CountDownLatch(1); latch.await(); } /** * 测试从指定partition拉取消息,实现指定分组、队列号规则 * * @throws Exception */// TODO: 12/21/16 interface removed @Test public void testPullFromSelectPartition() throws Exception{ /*ConsumerConfig consumerConfig = new ConsumerConfig(); messageConsumer = new MessageConsumer(consumerConfig, manager, null); new Thread(new Runnable() { @Override public void run() { try { while (true) { try { messageConsumer.start(); //手动拉取消息 messageConsumer.pullFromBroker(topic, new MessageListener() { @Override public void onMessage(List<Message> messages) throws Exception { if (messages != null && !messages.isEmpty()) { for (Message msg : messages) { logger.info("message queueId is " + msg.getQueueId()); logger.info("consumer count is " + consumerCount.getAndIncrement()); } } } }, new ConsumerStrategy() { @Override public String electBrokerGroup(TopicConfig topicConfig, byte dataCenter) { Random r = new Random(); int size = topicConfig.getGroups().size(); int j = r.nextInt(size); int i = 0; for (String group : topicConfig.getGroups()) { if (j == i) { return group; } i++; } return null; } @Override public short electQueueId(String groupName, TopicConfig topicConfig, byte dataCenter) { short size = topicConfig.getQueues(); short queueId; Random r = new Random(); queueId = (short)(r.nextInt(size) + 1); return queueId; } @Override public void pullEnd(String groupName, short queueId) { if (logger.isDebugEnabled()) { logger.debug(String.format("pull from %s %d", groupName, queueId)); } } }); }catch (Exception e){ logger.error("",e); } } } catch (Exception e) { e.printStackTrace(); } } }).start(); CountDownLatch latch = new CountDownLatch(1); latch.await();*/ } /** * 非事务的单条发送 */ protected void send(int i) throws JMQException { Message message = new Message(topic, topic + "_test_wei_" + i, topic + "_rid_" + i); producer.send(message); } /** * 实现指定partition接口,选择链路及队列 */ public class ProducerLoadBalanceTest implements LoadBalance { @Override public <T extends ElectTransport> T electTransport(List<T> transports, List<T> errTransports, Message message, byte dataCenter, TopicConfig config) throws JMQException { int hashcode = message.getBusinessId().hashCode(); int size = transports.size(); int ind; if(hashcode==Integer.MIN_VALUE){ ind = 0; }else{ ind = Math.abs(hashcode) % size; } logger.info("transport is " + transports.get(ind).getGroup()); return transports.get(ind); } @Override public <T extends ElectTransport> short electQueueId(T transport, Message message, byte dataCenter, TopicConfig config) throws JMQException { logger.info("queueId is " + 1); return 1; } } }
92410c7f62a5a8eaa61694d4d00c003a9470d36b
915
java
Java
src/main/java/levas/ugikerberosprincipaltest/Main.java
rlevas/UGIKerberosPrincipalTest
2c931bbb84c571287f4d6032a79b18ceb9f2a5a4
[ "Unlicense" ]
null
null
null
src/main/java/levas/ugikerberosprincipaltest/Main.java
rlevas/UGIKerberosPrincipalTest
2c931bbb84c571287f4d6032a79b18ceb9f2a5a4
[ "Unlicense" ]
null
null
null
src/main/java/levas/ugikerberosprincipaltest/Main.java
rlevas/UGIKerberosPrincipalTest
2c931bbb84c571287f4d6032a79b18ceb9f2a5a4
[ "Unlicense" ]
null
null
null
28.59375
116
0.730055
1,001,761
package levas.ugikerberosprincipaltest; import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; public class Main { public static void main(String[] args) throws IOException { // Enable Kerberos debugging System.setProperty("sun.security.krb5.debug", "true"); String principalName = args[0]; String keytabFilePath = args[1]; Configuration conf = new Configuration(); conf.set("hadoop.security.authentication", "kerberos"); // Enable Kerberos authentication UserGroupInformation.setConfiguration(conf); UserGroupInformation user = UserGroupInformation.loginUserFromKeytabAndReturnUGI(principalName, keytabFilePath); if (user != null) { System.out.print("Authenticated user: "); System.out.println(user.getUserName()); } else { System.out.println("UGI is null"); } } }
92410cda933ce6514d4d735338c944ece5767075
3,451
java
Java
serialization/src/main/java/com/twitter/serial/serializer/BuilderSerializer.java
dstmath/Serial
b75f8ab98acedc5621eceb0deb7bbdd59f9279d0
[ "Apache-2.0" ]
901
2017-07-24T23:46:21.000Z
2022-03-31T13:57:40.000Z
serialization/src/main/java/com/twitter/serial/serializer/BuilderSerializer.java
dstmath/Serial
b75f8ab98acedc5621eceb0deb7bbdd59f9279d0
[ "Apache-2.0" ]
27
2017-07-28T20:54:32.000Z
2021-12-01T23:08:56.000Z
serialization/src/main/java/com/twitter/serial/serializer/BuilderSerializer.java
dstmath/Serial
b75f8ab98acedc5621eceb0deb7bbdd59f9279d0
[ "Apache-2.0" ]
79
2017-07-28T05:40:00.000Z
2022-03-21T16:15:07.000Z
39.215909
119
0.70878
1,001,762
/* * Copyright 2017 Twitter * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twitter.serial.serializer; import com.twitter.serial.object.Builder; import com.twitter.serial.stream.SerializerInput; import com.twitter.serial.util.OptionalFieldException; import com.twitter.serial.util.SerializationException; import com.twitter.serial.util.SerializationUtils; import org.jetbrains.annotations.NotNull; import java.io.EOFException; import java.io.IOException; import java.io.OptionalDataException; /** * A base serializer for a class that has an {@link Builder}. The serialized data delimits the boundaries * of the object and provides basic support for versioning. */ public abstract class BuilderSerializer<T, B extends Builder<T>> extends ObjectSerializer<T> { protected BuilderSerializer() { } protected BuilderSerializer(int versionNumber) { super(versionNumber); } public void deserialize(@NotNull SerializationContext context, @NotNull SerializerInput input, @NotNull B builder) throws IOException, ClassNotFoundException { if (SerializationUtils.readNullIndicator(input)) { return; } final int deserializedVersionNumber = input.readObjectStart(); if (deserializedVersionNumber > mVersionNumber) { throw new SerializationException( "Version number found (" + deserializedVersionNumber + ") is " + "greater than the maximum supported value (" + mVersionNumber + ")"); } deserialize(context, input, builder, deserializedVersionNumber); input.readObjectEnd(); } @NotNull @Override protected final T deserializeObject(@NotNull SerializationContext context, @NotNull SerializerInput input, int versionNumber) throws IOException, ClassNotFoundException { final B builder = createBuilder(); deserialize(context, input, builder, versionNumber); return builder.build(); } private void deserialize(@NotNull SerializationContext context, @NotNull SerializerInput input, @NotNull B builder, int versionNumber) throws IOException, ClassNotFoundException { try { //noinspection BlacklistedMethod deserializeToBuilder(context, input, builder, versionNumber); } catch (OptionalDataException | EOFException | OptionalFieldException ignore) { // This may happen when reading optional fields. The builder should already // contain all the available fields, so just ignore the exception. } } @NotNull protected abstract B createBuilder(); protected abstract void deserializeToBuilder(@NotNull SerializationContext context, @NotNull SerializerInput input, @NotNull B builder, int versionNumber) throws IOException, ClassNotFoundException; }
92410cdd1eaf7bbcd0102f85f4358598447ad98b
6,092
java
Java
Lab4/src/academy/pocu/comp2500/lab4/Program.java
GyuCheol/java_oop_studying
507ecef9c0d5b0a32a1afaec7f50b80b5e512e47
[ "MIT" ]
null
null
null
Lab4/src/academy/pocu/comp2500/lab4/Program.java
GyuCheol/java_oop_studying
507ecef9c0d5b0a32a1afaec7f50b80b5e512e47
[ "MIT" ]
null
null
null
Lab4/src/academy/pocu/comp2500/lab4/Program.java
GyuCheol/java_oop_studying
507ecef9c0d5b0a32a1afaec7f50b80b5e512e47
[ "MIT" ]
null
null
null
38.075
76
0.594222
1,001,763
package academy.pocu.comp2500.lab4; public class Program { public static void main(String[] args) { { MemoryCache memCacheA = MemoryCache.getInstance("A"); MemoryCache memCacheB = MemoryCache.getInstance("B"); MemoryCache memCacheC = MemoryCache.getInstance("C"); assert memCacheA == MemoryCache.getInstance("A"); assert memCacheB == MemoryCache.getInstance("B"); assert memCacheC == MemoryCache.getInstance("C"); MemoryCache.setMaxInstanceCount(3); MemoryCache memCacheD = MemoryCache.getInstance("D"); assert memCacheA != MemoryCache.getInstance("A"); assert memCacheC == MemoryCache.getInstance("C"); assert memCacheB != MemoryCache.getInstance("B"); assert memCacheD != MemoryCache.getInstance("D"); } { MemoryCache memCache = MemoryCache.getInstance("A"); memCache.addEntry("key1", "value1"); memCache.addEntry("key2", "value2"); memCache.addEntry("key3", "value3"); memCache.addEntry("key4", "value4"); memCache.addEntry("key5", "value5"); memCache.setMaxEntryCount(3); assert memCache.getEntryOrNull("key1") == null; assert memCache.getEntryOrNull("key2") == null; assert memCache.getEntryOrNull("key3") != null; assert memCache.getEntryOrNull("key4") != null; assert memCache.getEntryOrNull("key5") != null; memCache.addEntry("key6", "value6"); assert memCache.getEntryOrNull("key3") == null; memCache.getEntryOrNull("key4"); memCache.getEntryOrNull("key5"); memCache.getEntryOrNull("key4"); memCache.addEntry("key7", "value7"); assert memCache.getEntryOrNull("key6") == null; memCache.addEntry("key5", "value5_updated"); memCache.addEntry("key8", "value8"); assert memCache.getEntryOrNull("key4") == null; assert memCache.getEntryOrNull("key5").equals("value5_updated"); memCache.setEvictionPolicy(EvictionPolicy.FIRST_IN_FIRST_OUT); memCache.addEntry("key9", "value9"); assert memCache.getEntryOrNull("key5") == null; memCache.addEntry("key10", "value10"); assert memCache.getEntryOrNull("key7") == null; memCache.setMaxEntryCount(1); assert memCache.getEntryOrNull("key8") == null; assert memCache.getEntryOrNull("key9") == null; assert memCache.getEntryOrNull("key10").equals("value10"); memCache.setMaxEntryCount(5); memCache.setEvictionPolicy(EvictionPolicy.LAST_IN_FIRST_OUT); memCache.addEntry("key11", "value11"); memCache.addEntry("key12", "value12"); memCache.addEntry("key13", "value13"); memCache.addEntry("key14", "value14"); assert memCache.getEntryOrNull("key10") != null; assert memCache.getEntryOrNull("key11") != null; assert memCache.getEntryOrNull("key12") != null; assert memCache.getEntryOrNull("key13") != null; assert memCache.getEntryOrNull("key14") != null; memCache.addEntry("key15", "value15"); assert memCache.getEntryOrNull("key14") == null; assert memCache.getEntryOrNull("key13") != null; assert memCache.getEntryOrNull("key11") != null; assert memCache.getEntryOrNull("key12") != null; assert memCache.getEntryOrNull("key10") != null; assert memCache.getEntryOrNull("key15") != null; memCache.setEvictionPolicy(EvictionPolicy.LEAST_RECENTLY_USED); memCache.addEntry("key16", "value16"); assert memCache.getEntryOrNull("key13") == null; assert memCache.getEntryOrNull("key10") != null; assert memCache.getEntryOrNull("key11") != null; assert memCache.getEntryOrNull("key12") != null; assert memCache.getEntryOrNull("key15") != null; assert memCache.getEntryOrNull("key16") != null; } { MemoryCache.clear(); MemoryCache.setMaxInstanceCount(5); MemoryCache memCacheA = MemoryCache.getInstance("A"); MemoryCache memCacheB = MemoryCache.getInstance("B"); MemoryCache memCacheC = MemoryCache.getInstance("C"); MemoryCache memCacheD = MemoryCache.getInstance("D"); MemoryCache memCacheE = MemoryCache.getInstance("E"); assert memCacheA != null; assert memCacheB != null; assert memCacheC != null; assert memCacheD != null; assert memCacheE != null; assert memCacheA == MemoryCache.getInstance("A"); assert memCacheB == MemoryCache.getInstance("B"); assert memCacheC == MemoryCache.getInstance("C"); assert memCacheD == MemoryCache.getInstance("D"); assert memCacheE == MemoryCache.getInstance("E"); memCacheA.addEntry("test", "test"); assert memCacheA.getEntryOrNull("test") == "test"; memCacheB.addEntry("test", "test"); assert memCacheB.getEntryOrNull("test") == "test"; MemoryCache.setMaxInstanceCount(3); assert memCacheC == MemoryCache.getInstance("C"); assert memCacheD == MemoryCache.getInstance("D"); assert memCacheE == MemoryCache.getInstance("E"); assert memCacheA != MemoryCache.getInstance("A"); assert memCacheB != MemoryCache.getInstance("B"); // A, B는 삭제후 새로 생성된 instance이니 위에서 추가했던 entry가 없을것임 memCacheA = MemoryCache.getInstance("A"); memCacheB = MemoryCache.getInstance("B"); assert memCacheA.getEntryOrNull("test") == null; assert memCacheB.getEntryOrNull("test") == null; MemoryCache.clear(); } } }
92410ddbbd2164bff7aac2effb7a3b6e73de2ba0
3,591
java
Java
puree/src/androidTest/java/com/cookpad/puree/outputs/PureeOutputTest.java
operando/puree-android
3fb7fb7ac2b95683d4681ac4bda3cfebd499abef
[ "MIT" ]
309
2015-01-04T11:44:56.000Z
2022-03-30T06:24:28.000Z
puree/src/androidTest/java/com/cookpad/puree/outputs/PureeOutputTest.java
operando/puree-android
3fb7fb7ac2b95683d4681ac4bda3cfebd499abef
[ "MIT" ]
36
2015-02-21T01:24:15.000Z
2021-09-07T07:12:58.000Z
puree/src/androidTest/java/com/cookpad/puree/outputs/PureeOutputTest.java
operando/puree-android
3fb7fb7ac2b95683d4681ac4bda3cfebd499abef
[ "MIT" ]
60
2015-01-13T09:16:45.000Z
2021-12-23T08:47:17.000Z
30.176471
83
0.533278
1,001,764
package com.cookpad.puree.outputs; import com.cookpad.puree.PureeFilter; import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; import org.junit.runner.RunWith; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.Nonnull; import androidx.test.ext.junit.runners.AndroidJUnit4; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; @RunWith(AndroidJUnit4.class) public class PureeOutputTest { @Test public void discardLog() { final PureeOutput output = new PureeOutput() { @Override public void emit(String jsonLog) { // because first filter discards log. fail("log should be discarded by first filter"); } @Nonnull @Override public OutputConfiguration configure(OutputConfiguration conf) { return conf; } @Nonnull @Override public String type() { return "output"; } }; output.registerFilter(new PureeFilter() { @Override public String apply(String jsonLog) { // discard log return null; } }); output.registerFilter(new PureeFilter() { @Override public String apply(String jsonLog) { return jsonLog + "event_time" + System.currentTimeMillis(); } }); output.receive(""); } @Test public void testFilter_multipleModifications() throws JSONException { final AtomicReference<String> result = new AtomicReference<>(); final PureeOutput output = new PureeOutput() { @Override public void emit(String jsonLog) { result.set(jsonLog); } @Nonnull @Override public OutputConfiguration configure(OutputConfiguration conf) { return conf; } @Nonnull @Override public String type() { return "output"; } }; output.registerFilter(new PureeFilter() { @Override public String apply(String jsonLog) { try { JSONObject jsonObject = new JSONObject(); jsonObject.put("filter1", "foo"); return jsonObject.toString(); } catch (JSONException e) { throw new RuntimeException(e); } } }); output.registerFilter(new PureeFilter() { @Override public String apply(String jsonLog) { try { JSONObject jsonObject = new JSONObject(jsonLog); if (jsonObject.has("filter1")) { jsonObject.put("filter1", jsonObject.getString("filter1")); } jsonObject.put("filter2", "bar"); return jsonObject.toString(); } catch (JSONException e) { throw new RuntimeException(e); } } }); output.receive(""); final JSONObject resultObject = new JSONObject(result.get()); assertThat(resultObject.has("filter1"), is(true)); assertThat(resultObject.getString("filter1"), is("foo")); assertThat(resultObject.has("filter2"), is(true)); assertThat(resultObject.getString("filter2"), is("bar")); } }
92410e28ae036c2450037908e851f9afde52077c
376
java
Java
web/src/main/java/uk/ac/ebi/phenotype/web/dto/Author.java
jwgwarren/PhenotypeData
a1a36fd0efacc6515ad843ff7ce4bebc3ae98393
[ "Apache-2.0" ]
1
2018-04-03T06:44:47.000Z
2018-04-03T06:44:47.000Z
web/src/main/java/uk/ac/ebi/phenotype/web/dto/Author.java
jwgwarren/PhenotypeData
a1a36fd0efacc6515ad843ff7ce4bebc3ae98393
[ "Apache-2.0" ]
655
2016-05-16T13:04:02.000Z
2022-03-25T14:06:36.000Z
web/src/main/java/uk/ac/ebi/phenotype/web/dto/Author.java
jwgwarren/PhenotypeData
a1a36fd0efacc6515ad843ff7ce4bebc3ae98393
[ "Apache-2.0" ]
6
2017-06-16T13:43:37.000Z
2020-02-27T12:57:07.000Z
19.789474
36
0.784574
1,001,765
package uk.ac.ebi.phenotype.web.dto; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor @Builder public class Author { private String fullName; private String firstName; private String lastName; private String initials; private String affiliation; }
92410ef4bd664a299c5cb74f571eb2efc7531d45
268
java
Java
src/main/java/pages/android/YoutubeSearchScreen.java
Baldroster/android-box
283b425776bf4c84fd8c130033d9601ecc9949d6
[ "MIT" ]
null
null
null
src/main/java/pages/android/YoutubeSearchScreen.java
Baldroster/android-box
283b425776bf4c84fd8c130033d9601ecc9949d6
[ "MIT" ]
null
null
null
src/main/java/pages/android/YoutubeSearchScreen.java
Baldroster/android-box
283b425776bf4c84fd8c130033d9601ecc9949d6
[ "MIT" ]
null
null
null
19.142857
90
0.802239
1,001,766
package pages.android; import pages.android.blocks.SearchBlock; import ru.lanit.at.pages.AbstractScreen; import ru.lanit.at.pages.annotations.Title; @Title("Поиск") public interface YoutubeSearchScreen extends AbstractScreen, SearchBlock.WithSearchBlock { }
92410f6b70930e40f708ef35ae2e020993573b3c
514
java
Java
libs/chat-workflow-testing/src/main/java/org/finos/springbot/tests/work/DisplayWork.java
robmoffat/symphony-java-client-parent
28024420e29fbd694d40c100f0f3f2ac4cfe773c
[ "Apache-2.0" ]
10
2019-11-04T09:57:58.000Z
2020-08-11T22:05:18.000Z
libs/chat-workflow-testing/src/main/java/org/finos/springbot/tests/work/DisplayWork.java
robmoffat/symphony-java-client-parent
28024420e29fbd694d40c100f0f3f2ac4cfe773c
[ "Apache-2.0" ]
30
2022-01-28T09:12:12.000Z
2022-03-30T08:24:44.000Z
libs/chat-workflow-testing/src/main/java/org/finos/springbot/tests/work/DisplayWork.java
robmoffat/symphony-java-client-parent
28024420e29fbd694d40c100f0f3f2ac4cfe773c
[ "Apache-2.0" ]
8
2019-10-21T10:34:58.000Z
2020-08-14T19:33:04.000Z
15.117647
56
0.714008
1,001,767
package org.finos.springbot.tests.work; import org.finos.springbot.workflow.annotations.Display; import org.finos.springbot.workflow.annotations.Work; @Work public class DisplayWork { @Display(name = "Some crazy name") String s; @Display(visible = false) String invisible; public String getS() { return s; } public void setS(String s) { this.s = s; } public String getInvisible() { return invisible; } public void setInvisible(String invisible) { this.invisible = invisible; } }
92410f94c9245e8aff3916acf2c3a1881e683a3d
1,983
java
Java
1.JavaSyntax/task/task10/task1012/Solution.java
vladyslavkarpovych/JavaRushTasks
614667a0f475e6f413b70682d15b3119139c49d6
[ "MIT" ]
null
null
null
1.JavaSyntax/task/task10/task1012/Solution.java
vladyslavkarpovych/JavaRushTasks
614667a0f475e6f413b70682d15b3119139c49d6
[ "MIT" ]
null
null
null
1.JavaSyntax/task/task10/task1012/Solution.java
vladyslavkarpovych/JavaRushTasks
614667a0f475e6f413b70682d15b3119139c49d6
[ "MIT" ]
null
null
null
33.610169
168
0.609682
1,001,768
package com.javarush.task.task10.task1012; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; /* Количество букв Ввести с клавиатуры 10 строчек и подсчитать в них количество различных букв (для 33 букв алфавита). Вывести результат на экран. Пример вывода: а 5 б 8 в 3 г 7 д 0 … я 9 */ public class Solution { public static void main(String[] args) throws Exception { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //алфавит String abc = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"; char[] abcArray = abc.toCharArray(); ArrayList<Character> alphabet = new ArrayList<>(); for (int i = 0; i < abcArray.length; i++) { alphabet.add(abcArray[i]); } //ввод строк ArrayList<String> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { String s = reader.readLine(); list.add(s.toLowerCase()); } int abcCount=0; // объявили счетчик for ( char x : alphabet) // идем по alphabet и по букве присваеваем в переменню char "x"... { for ( String y : list) // теперь идем по введенному списку и берем оттдуа по строке и присваем каждую строчку к "у" { for (char z : y.toCharArray()) // расскладываем строчку на буквенный массив и присваем каждую букву по массиву в переменную "z" { if ( x == z ) // остается теперь сравнить букву с алфавита с буквами из введенной строки abcCount++; // когда буква встречается счетчик +1 } } System.out.println(x + " " + abcCount); // выводим букву из алфавита и наш счетчик для этой буквы abcCount=0; // не забываем обнулить счетчки после прохождения каждой буквы из алфавита, иначе он посчетает кол-во всех совпадений со всеми буквами из списка } } }
92411069dd2bd3db95d219f2c9057aed99089d42
6,275
java
Java
src/test/java/net/nyhm/bitty/example/BittyExample.java
nebaughman/bitty
9c6c6044dee5a58a92d0e0ed44f012bfcca93acc
[ "MIT" ]
null
null
null
src/test/java/net/nyhm/bitty/example/BittyExample.java
nebaughman/bitty
9c6c6044dee5a58a92d0e0ed44f012bfcca93acc
[ "MIT" ]
null
null
null
src/test/java/net/nyhm/bitty/example/BittyExample.java
nebaughman/bitty
9c6c6044dee5a58a92d0e0ed44f012bfcca93acc
[ "MIT" ]
null
null
null
29.880952
99
0.690837
1,001,769
package net.nyhm.bitty.example; import io.netty.util.CharsetUtil; import net.nyhm.bitty.*; 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.client.utils.URIBuilder; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import static org.junit.Assert.assertEquals; // TODO: Notice that these tests often fail when run together, but will pass when run individually. // // One problem is timing between starting the service and calling it. See HttpService.start() // The service starts asynchronously. The start method needs to wait until the service is started, // or provide a Future for the caller to optionally await startup. public class BittyExample { private static final Logger log = LoggerFactory.getLogger(BittyExample.class); private static final int PORT = 8888; private static final String MESSAGE = "Hello"; @Test public void testResponse() throws Exception { ContentType contentType = new ContentType( new MimeType("text", "plain"), CharsetUtil.UTF_8 ); ServerLogic logic = new CannedResponseLogic(MESSAGE, contentType); HttpServer server = new HttpServer(logic, PORT, 1, 1); HttpService service = new HttpService(server); service.start(); assertEquals(MESSAGE, sendGet()); service.stop(); } @Test public void testEcho() throws Exception { HttpService service = new HttpService( new HttpServer(new EchoLogic(), PORT, 1, 1) ); service.start(); String response = sendPost(MESSAGE); log.info(response.getClass().getName()); assertEquals(MESSAGE, response); service.stop(); } @Test public void testIgnore() throws Exception { try (HttpService service = buildService(new IgnoreLogic())) { service.start(); sendGet(); } } /** * Test throwing an exception from ServerLogic. Server should continue to operate. */ @Test public void testException() throws Exception { try (HttpService service = buildService(new FailOnce(new EchoLogic()))) { service.start(); try { log.info("Second attempt"); sendGet(); // this should fail (FailOnce logic) } catch (Exception e) { log.info("Expected exception", e); } log.info("Second attempt"); String response = sendPost(MESSAGE); // this should work assertEquals(MESSAGE, response); } } /** * Send a GET request to the serverUri() */ private static String sendGet() throws Exception { try (CloseableHttpClient client = buildClient()) { HttpGet request = new HttpGet(serverUri()); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); String content = EntityUtils.toString(entity); return content; } } /** * Send a POST request with the given body to the serverUri() */ private static String sendPost(String body) throws Exception { try (CloseableHttpClient client = buildClient()) { HttpEntity entity = new StringEntity(body, CharsetUtil.UTF_8); HttpPost request = new HttpPost(serverUri()); request.setEntity(entity); HttpResponse response = client.execute(request); String content = EntityUtils.toString(response.getEntity()); return content; } } /** * Test service endpoint */ private static URI serverUri() throws Exception { return new URIBuilder() .setScheme("http") .setHost("localhost") .setPort(PORT) .build(); } private static CloseableHttpClient buildClient() { return HttpClientBuilder.create() .disableAutomaticRetries() .build(); } private static HttpService buildService(ServerLogic logic) { return new HttpService(new HttpServer(logic, PORT, 1, 1)); } /** * Always returns the specified content */ private static final class CannedResponseLogic implements ServerLogic { private final String responseMessage; private final ContentType contentType; CannedResponseLogic(String responseMessage, ContentType contentType) { this.responseMessage = responseMessage; this.contentType = contentType; } @Override public void processRequest(ClientRequest request, ServerResponse response) throws Exception { log.info("Client request"); request.logRequest(); response.setContentType(contentType); response.respond(responseMessage); } } /** * Echoes the content of the request body (only for POST) */ private static final class EchoLogic implements ServerLogic { @Override public void processRequest(ClientRequest request, ServerResponse response) throws Exception { String body = request.getBody(); log.info("Client request", body); request.logRequest(); response.setContentType(new ContentType( new MimeType("text", "plain"), CharsetUtil.UTF_8 )); response.respond(body); } } /** * Sends back empty content (otherwise ignored) */ private static final class IgnoreLogic implements ServerLogic { @Override public void processRequest(ClientRequest request, ServerResponse response) throws Exception { log.info("Ignoring request", request); response.respond(""); // must respond, even with nothing } } /** * Fail the first client request, then proxy the rest to another ServerLogic */ private static final class FailOnce implements ServerLogic { private int mFailCount = 0; private ServerLogic mFallback; FailOnce(ServerLogic fallback) { mFallback = fallback; } @Override public void processRequest(ClientRequest request, ServerResponse response) throws Exception { if (mFailCount < 1) { mFailCount++; throw new Exception("Testing exception"); } else { mFallback.processRequest(request, response); } } } }
924111e01587c4106852e5ff0aec4fec275e21bf
1,798
java
Java
2021-05-09/学之思开源考试系统 - Postgresql版/source/xzs/src/main/java/com/mindskip/xzs/service/impl/FileUploadImpl.java
ritaswc/wechat_app_template
d6ba56b70b09bc755f7d4d6b696b9e9b53511faa
[ "MIT" ]
395
2017-02-24T02:59:29.000Z
2022-03-31T15:48:19.000Z
2021-05-09/学之思开源考试系统 - Postgresql版/source/xzs/src/main/java/com/mindskip/xzs/service/impl/FileUploadImpl.java
ritaswc/wechat_app_template
d6ba56b70b09bc755f7d4d6b696b9e9b53511faa
[ "MIT" ]
7
2020-03-17T08:33:00.000Z
2021-09-02T23:10:46.000Z
2021-05-09/学之思开源考试系统 - Postgresql版/source/xzs/src/main/java/com/mindskip/xzs/service/impl/FileUploadImpl.java
ritaswc/wechat_app_template
d6ba56b70b09bc755f7d4d6b696b9e9b53511faa
[ "MIT" ]
235
2017-03-14T03:31:38.000Z
2022-03-29T16:14:51.000Z
37.458333
99
0.73693
1,001,770
package com.mindskip.xzs.service.impl; import com.mindskip.xzs.configuration.property.QnConfig; import com.mindskip.xzs.configuration.property.SystemConfig; import com.mindskip.xzs.service.FileUpload; import com.google.gson.Gson; import com.qiniu.common.QiniuException; import com.qiniu.http.Response; import com.qiniu.storage.Configuration; import com.qiniu.storage.Region; import com.qiniu.storage.UploadManager; import com.qiniu.storage.model.DefaultPutRet; import com.qiniu.util.Auth; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.InputStream; @Service public class FileUploadImpl implements FileUpload { private final Logger logger = LoggerFactory.getLogger(FileUpload.class); private final SystemConfig systemConfig; @Autowired public FileUploadImpl(SystemConfig systemConfig) { this.systemConfig = systemConfig; } @Override public String uploadFile(InputStream inputStream, long size, String extName) { QnConfig qnConfig = systemConfig.getQn(); Configuration cfg = new Configuration(Region.region2()); UploadManager uploadManager = new UploadManager(cfg); Auth auth = Auth.create(qnConfig.getAccessKey(), qnConfig.getSecretKey()); String upToken = auth.uploadToken(qnConfig.getBucket()); try { Response response = uploadManager.put(inputStream, null, upToken, null, null); DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class); return qnConfig.getUrl() + "/" + putRet.key; } catch (QiniuException ex) { logger.error(ex.getMessage(), ex); } return null; } }
924112ae21d908d8d1878419c90773466fb07063
1,443
java
Java
libs/api/src/main/java/com/ultimatesoftware/banking/api/factories/MongoTestMockFactory.java
dionny/testing-microservices-introduction
3c42f2c794808073ad6eb307f803f4073ba99762
[ "Apache-2.0" ]
27
2019-04-15T19:08:42.000Z
2022-02-01T13:14:54.000Z
libs/api/src/main/java/com/ultimatesoftware/banking/api/factories/MongoTestMockFactory.java
dionny/testing-microservices-introduction
3c42f2c794808073ad6eb307f803f4073ba99762
[ "Apache-2.0" ]
4
2018-06-14T17:31:58.000Z
2018-06-27T14:42:56.000Z
libs/api/src/main/java/com/ultimatesoftware/banking/api/factories/MongoTestMockFactory.java
dionny/testing-microservices-introduction
3c42f2c794808073ad6eb307f803f4073ba99762
[ "Apache-2.0" ]
9
2019-04-03T21:04:38.000Z
2022-02-13T06:14:03.000Z
42.441176
105
0.817048
1,001,771
package com.ultimatesoftware.banking.api.factories; import com.mongodb.ServerAddress; import com.mongodb.reactivestreams.client.MongoClient; import com.mongodb.reactivestreams.client.MongoClients; import com.ultimatesoftware.banking.api.configuration.ConfigurationConstants; import de.bwaldvogel.mongo.MongoServer; import de.bwaldvogel.mongo.backend.memory.MemoryBackend; import io.micronaut.configuration.mongo.reactive.DefaultReactiveMongoConfiguration; import io.micronaut.context.annotation.Bean; import io.micronaut.context.annotation.Factory; import io.micronaut.context.annotation.Primary; import io.micronaut.context.annotation.Requires; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Singleton; @Factory @Requires(env = ConfigurationConstants.EXTERNAL_MOCKS) public class MongoTestMockFactory { private static final Logger LOG = LoggerFactory.getLogger(MongoTestMockFactory.class); @Primary @Bean @Singleton public MongoClient mongoClient(DefaultReactiveMongoConfiguration defaultReactiveMongoConfiguration) { LOG.info("Mocking Mongo Client with embedded memory client."); MongoServer server = new MongoServer(new MemoryBackend()); ServerAddress serverAddress = new ServerAddress(server.bind()); defaultReactiveMongoConfiguration.setHost(serverAddress); return MongoClients.create(defaultReactiveMongoConfiguration.buildSettings()); } }
9241133bcba405bd5add5140bba9a30458228c19
434
java
Java
src/test/java/uk/co/jemos/podam/test/dto/pdm3/Pdm3PojoConstructor.java
LaxmanChandraKumar/TestRe
6b942cc4ddaf1b9d3c6fedce539161608e5d6ea8
[ "MIT" ]
172
2015-01-19T17:48:42.000Z
2022-03-30T23:42:36.000Z
src/test/java/uk/co/jemos/podam/test/dto/pdm3/Pdm3PojoConstructor.java
LaxmanChandraKumar/TestRe
6b942cc4ddaf1b9d3c6fedce539161608e5d6ea8
[ "MIT" ]
108
2015-01-03T15:23:16.000Z
2022-03-23T14:19:35.000Z
src/test/java/uk/co/jemos/podam/test/dto/pdm3/Pdm3PojoConstructor.java
LaxmanChandraKumar/TestRe
6b942cc4ddaf1b9d3c6fedce539161608e5d6ea8
[ "MIT" ]
671
2015-02-08T21:48:38.000Z
2022-03-15T00:55:58.000Z
16.692308
80
0.665899
1,001,772
package uk.co.jemos.podam.test.dto.pdm3; /** * Pojo to test <a href="https://agileguru.atlassian.net/browse/PDM-3">PDM-3</a> * * @author daivanov * */ public class Pdm3PojoConstructor<T extends RuntimeException> { private T name; public Pdm3PojoConstructor(T name) { this.name = name; } public T getName() { return name; } @Override public String toString() { return String.format("{name: '%s'}", name); } }