repo_name stringlengths 7 70 | file_path stringlengths 9 215 | context list | import_statement stringlengths 47 10.3k | token_num int64 643 100k | cropped_code stringlengths 62 180k | all_code stringlengths 62 224k | next_line stringlengths 9 1.07k | gold_snippet_index int64 0 117 | created_at stringlengths 25 25 | level stringclasses 9
values |
|---|---|---|---|---|---|---|---|---|---|---|
quentin452/DangerRPG-Continuation | src/main/java/mixac1/hooklib/minecraft/PrimaryClassTransformer.java | [
{
"identifier": "AsmHook",
"path": "src/main/java/mixac1/hooklib/asm/AsmHook.java",
"snippet": "public class AsmHook implements Cloneable, Comparable<AsmHook> {\n\n private String targetClassName;\n private String targetMethodName;\n private List<Type> targetMethodParameters = new ArrayList<Typ... | import cpw.mods.fml.common.asm.transformers.deobf.FMLDeobfuscatingRemapper;
import mixac1.hooklib.asm.AsmHook;
import mixac1.hooklib.asm.HookClassTransformer;
import mixac1.hooklib.asm.HookInjectorClassVisitor;
import net.minecraft.launchwrapper.IClassTransformer;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Type;
import java.util.HashMap;
import java.util.List; | 5,450 | package mixac1.hooklib.minecraft;
public class PrimaryClassTransformer extends HookClassTransformer implements IClassTransformer {
static PrimaryClassTransformer instance = new PrimaryClassTransformer();
boolean registeredSecondTransformer;
public PrimaryClassTransformer() {
if (instance != null) {
this.hooksMap.putAll(PrimaryClassTransformer.instance.getHooksMap());
PrimaryClassTransformer.instance.getHooksMap()
.clear();
} else {
registerHookContainer(SecondaryTransformerHook.class.getName());
}
instance = this;
}
@Override
public byte[] transform(String oldName, String newName, byte[] bytecode) {
return transform(newName, bytecode);
}
@Override | package mixac1.hooklib.minecraft;
public class PrimaryClassTransformer extends HookClassTransformer implements IClassTransformer {
static PrimaryClassTransformer instance = new PrimaryClassTransformer();
boolean registeredSecondTransformer;
public PrimaryClassTransformer() {
if (instance != null) {
this.hooksMap.putAll(PrimaryClassTransformer.instance.getHooksMap());
PrimaryClassTransformer.instance.getHooksMap()
.clear();
} else {
registerHookContainer(SecondaryTransformerHook.class.getName());
}
instance = this;
}
@Override
public byte[] transform(String oldName, String newName, byte[] bytecode) {
return transform(newName, bytecode);
}
@Override | protected HookInjectorClassVisitor createInjectorClassVisitor(ClassWriter cw, List<AsmHook> hooks) { | 2 | 2023-10-31 21:00:14+00:00 | 8k |
Tamiflu233/DingVideo | dingvideobackend/src/main/java/com/dataispower/dingvideobackend/service/LikeServiceImpl.java | [
{
"identifier": "Comment",
"path": "dingvideobackend/src/main/java/com/dataispower/dingvideobackend/entity/Comment.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@Document(collection = com.dataispower.dingvideobackend.common.TableColumns.COMMENT)\npublic class Comment implements Seri... | import com.dataispower.dingvideobackend.entity.Comment;
import com.dataispower.dingvideobackend.entity.UserLike;
import com.dataispower.dingvideobackend.entity.Video;
import com.dataispower.dingvideobackend.repository.LikeRepository;
import com.dataispower.dingvideobackend.repository.UserRepository;
import com.dataispower.dingvideobackend.repository.VideoRepository;
import com.dataispower.dingvideobackend.service.interfaces.CommentService;
import com.dataispower.dingvideobackend.service.interfaces.LikeService;
import com.dataispower.dingvideobackend.service.interfaces.RedisLikeService;
import com.dataispower.dingvideobackend.service.interfaces.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*; | 3,956 | package com.dataispower.dingvideobackend.service;
/**
* author:heroding
* date:2023/11/6 16:06
* description:点赞服务类
**/
@Service
public class LikeServiceImpl implements LikeService {
@Autowired
private LikeRepository userLikeRepository;
@Autowired
private RedisLikeService redisLikeService;
@Autowired
private VideoRepository videoRepository;
@Autowired | package com.dataispower.dingvideobackend.service;
/**
* author:heroding
* date:2023/11/6 16:06
* description:点赞服务类
**/
@Service
public class LikeServiceImpl implements LikeService {
@Autowired
private LikeRepository userLikeRepository;
@Autowired
private RedisLikeService redisLikeService;
@Autowired
private VideoRepository videoRepository;
@Autowired | private UserRepository userRepository; | 4 | 2023-10-25 07:16:43+00:00 | 8k |
MiguelPereiraDantas/E-commerce-Java | src/main/java/br/com/fourstore/controller/SaleController.java | [
{
"identifier": "ServiceSale",
"path": "src/main/java/br/com/fourstore/service/ServiceSale.java",
"snippet": "@Service\npublic class ServiceSale {\n\t\n\t@Autowired\n\tServiceProduct serviceProduct;\n\t\n\t@Autowired\n\tServiceHistoric serviceHistoric;\n\t\n\tprivate static List<Product> cart = new Arra... | import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.fourstore.service.ServiceSale;
import br.com.fourstore.model.Credit;
import br.com.fourstore.model.Debit;
import br.com.fourstore.model.Money;
import br.com.fourstore.model.Pix;
import br.com.fourstore.model.Product;
import br.com.fourstore.model.Sale; | 5,305 | package br.com.fourstore.controller;
@RestController
@RequestMapping("/sale")
public class SaleController {
@Autowired
ServiceSale serviceSale;
@GetMapping("/cart")
public List<Product> getCart(){
return serviceSale.getCart();
}
@GetMapping("/cart/{sku}")
public Product getProductInCart(@PathVariable("sku") String sku) {
return serviceSale.searchProductBySkuInCart(sku);
}
@PostMapping("/cart/add/{sku}/{theAmount}")
public String postInCart(@PathVariable("sku") String sku, @PathVariable("theAmount") Integer theAmount) {
return serviceSale.addProductToCart(sku, theAmount);
}
@DeleteMapping("/cart/delete/{sku}/{theAmount}")
public String deleteInCart(@PathVariable("sku") String sku, @PathVariable("theAmount") Integer theAmount) {
return serviceSale.removeProductFromCart(sku, theAmount);
}
@DeleteMapping("/cart/empty")
public String deleteCart() {
return serviceSale.emptyCart();
}
@GetMapping("/cart/total")
public Double getTotal() {
return serviceSale.purchaseTotal();
}
@GetMapping("/cart/checkcart")
public List<Product> getCheckCart(){
return serviceSale.checkCart();
}
@PostMapping("/cart/finalizar/credit")
public Sale postHistoricCredit(@RequestBody Credit credit) {
return serviceSale.checkout(1, credit);
}
@PostMapping("/cart/finalizar/debit")
public Sale postHistoricDebit(@RequestBody Debit debit) {
return serviceSale.checkout(2, debit);
}
@PostMapping("/cart/finalizar/money")
public Sale postHistoricMoney(@RequestBody Money money) {
return serviceSale.checkout(3, money);
}
@PostMapping("/cart/finalizar/pix") | package br.com.fourstore.controller;
@RestController
@RequestMapping("/sale")
public class SaleController {
@Autowired
ServiceSale serviceSale;
@GetMapping("/cart")
public List<Product> getCart(){
return serviceSale.getCart();
}
@GetMapping("/cart/{sku}")
public Product getProductInCart(@PathVariable("sku") String sku) {
return serviceSale.searchProductBySkuInCart(sku);
}
@PostMapping("/cart/add/{sku}/{theAmount}")
public String postInCart(@PathVariable("sku") String sku, @PathVariable("theAmount") Integer theAmount) {
return serviceSale.addProductToCart(sku, theAmount);
}
@DeleteMapping("/cart/delete/{sku}/{theAmount}")
public String deleteInCart(@PathVariable("sku") String sku, @PathVariable("theAmount") Integer theAmount) {
return serviceSale.removeProductFromCart(sku, theAmount);
}
@DeleteMapping("/cart/empty")
public String deleteCart() {
return serviceSale.emptyCart();
}
@GetMapping("/cart/total")
public Double getTotal() {
return serviceSale.purchaseTotal();
}
@GetMapping("/cart/checkcart")
public List<Product> getCheckCart(){
return serviceSale.checkCart();
}
@PostMapping("/cart/finalizar/credit")
public Sale postHistoricCredit(@RequestBody Credit credit) {
return serviceSale.checkout(1, credit);
}
@PostMapping("/cart/finalizar/debit")
public Sale postHistoricDebit(@RequestBody Debit debit) {
return serviceSale.checkout(2, debit);
}
@PostMapping("/cart/finalizar/money")
public Sale postHistoricMoney(@RequestBody Money money) {
return serviceSale.checkout(3, money);
}
@PostMapping("/cart/finalizar/pix") | public Sale postHistoricPix(@RequestBody Pix pix) { | 4 | 2023-10-26 15:48:53+00:00 | 8k |
thinhunan/wonder8-promotion-rule | java/src/test/java/com/github/thinhunan/wonder8/promotion/rule/StrategyTest.java | [
{
"identifier": "BestMatch",
"path": "java/src/main/java/com/github/thinhunan/wonder8/promotion/rule/model/strategy/BestMatch.java",
"snippet": "public class BestMatch {\n\n MatchType type;\n\n public MatchType getType() {\n return type;\n }\n\n public void setType(MatchType type) {\n... | import com.github.thinhunan.wonder8.promotion.rule.model.*;
import com.github.thinhunan.wonder8.promotion.rule.model.strategy.BestMatch;
import com.github.thinhunan.wonder8.promotion.rule.model.strategy.Match;
import com.github.thinhunan.wonder8.promotion.rule.model.strategy.MatchGroup;
import com.github.thinhunan.wonder8.promotion.rule.model.strategy.MatchType;
import org.junit.Assert;
import org.junit.Test;
import java.util.*;
import java.util.stream.Collectors; | 5,664 | Assert.assertTrue(!rule7.check(items)); //dont match
match = Strategy.bestMatch(Collections.singletonList(rule2), items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//01 * 2,02 * 6
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule2), items);
//Assert.assertEquals((121200 * 2) / -2, match.totalDiscount());//02 * 2
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
List<Rule> rules = Arrays.asList(rule2,rule6,rule7);
match = Strategy.bestMatch(rules, items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//matches rule2, gets 4 match groups
match = Strategy.bestOfOnlyOnceDiscount(rules, items);
//Assert.assertEquals((121200 * 6) / -2, match.totalDiscount());//matches rule6, gets 1 match group
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
}
@Test
public void testoneSKUSum() {
String ruleString2 = "[#k01#k02].oneSKUSum(20000) -> -50%",
ruleString6 = "[#k01#k02].oneSKUSum(727200) -> -50%",
ruleString7 = "$.oneSKUSum(727201) -> -50%";
Rule rule2 = Interpreter.parseString(ruleString2).asRule(),
rule6 = Interpreter.parseString(ruleString6).asRule(),
rule7 = Interpreter.parseString(ruleString7).asRule();
List<Item> items = Arrays.asList(
new ItemImpl("01", "01", "01", "01", "01", "01", 10000),
new ItemImpl("01", "01", "01", "01", "01", "01", 10000),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "03", "03", 50)
);
Assert.assertTrue(rule2.check(items));
Assert.assertEquals((10000 * 2 + 121200 * 6 + 50) / -2, rule2.discount(items));//01,02,03
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, rule2.discountFilteredItems(items));//01,02
Assert.assertTrue(rule6.check(items));
Assert.assertEquals((10000 * 2 + 121200 * 6 + 50) / -2, rule6.discount(items));//01,02,03
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, rule6.discountFilteredItems(items));//01,02
Assert.assertTrue(!rule7.check(items)); //dont match
//#region deprecated api
BestMatch match = Strategy.bestMatch(Collections.singletonList(rule6), items);
//Assert.assertEquals(121200 * 6 / -2, match.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule6), items);
//Assert.assertEquals(121200 * 6 / -2, match.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
match = Strategy.bestMatch(Collections.singletonList(rule2), items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//01 * 2,02 * 6
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule2), items);
//Assert.assertEquals(121200 / -2, match.totalDiscount());//02 * 2
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
List<Rule> rules = Arrays.asList(rule2,rule6,rule7);
match = Strategy.bestMatch(rules, items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//matches rule2, gets 4 match groups
match = Strategy.bestOfOnlyOnceDiscount(rules, items);
//Assert.assertEquals((121200 * 6) / -2, match.totalDiscount());//matches rule6, gets 1 match group
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
//#endregion
//#region new api
BestMatch best = Strategy.bestChoice(Collections.singletonList(rule6), items,MatchType.OneRule);
//Assert.assertEquals(121200 * 6 / -2, best.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
best = Strategy.bestChoice(Collections.singletonList(rule6), items,MatchType.OneTime);
//Assert.assertEquals(121200 * 6 / -2, best.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
best = Strategy.bestChoice(Collections.singletonList(rule2), items,MatchType.OneRule);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, best.totalDiscount());//01 * 2,02 * 6
best = Strategy.bestChoice(Collections.singletonList(rule2), items, MatchType.OneTime);
//Assert.assertEquals(121200 / -2, best.totalDiscount());//02 * 1
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
rules = Arrays.asList(rule2,rule6,rule7);
best = Strategy.bestChoice(rules, items,MatchType.OneRule);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, best.totalDiscount());//matches rule2, gets 7 match groups
best = Strategy.bestChoice(rules, items, MatchType.OneTime);
//Assert.assertEquals((121200 * 6) / -2, best.totalDiscount());//matches rule6, gets 1 match group
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
best = Strategy.bestChoice(rules, items,MatchType.MultiRule);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, best.totalDiscount());
Rule rule8 = Interpreter.parseString("[#k01#k02#k03].oneSKUSum(727200) -> -60%").asRule();
rules=Arrays.asList(rule2,rule6,rule7,rule8);
best = Strategy.bestChoice(rules, items,MatchType.MultiRule);
Assert.assertEquals((10000 * 2 + 121200 * 6 +50) * 6 / -10 , best.totalDiscount());
//#endregion
}
@Test
public void testDiscountPerPrice(){
List<Item> items = Arrays.asList(
new ItemImpl("01", "01", "01", "01", "01", "01", 39000),
new ItemImpl("01", "01", "01", "01", "02", "01", 11000),
new ItemImpl("02", "02", "02", "02", "03", "02", 11000)
);
Rule rule1 = Interpreter.parseString("$.count(3)->-7000/15000").asRule(),
rule2 = Interpreter.parseString("$.count(1)->-1000/10000").asRule(),
rule3 = Interpreter.parseString("$.sum(15000)->-7000/15000").asRule();
List<Rule> rules = Arrays.asList(rule1,rule2); | package com.github.thinhunan.wonder8.promotion.rule;
public class StrategyTest {
// c01有3个商品70块,其中p01有2张50块,p02有1张20块,其它都只有1张20块,10个商品210块
// k01 30块(3000分),其它都是20块
private static List<Item> _getSelectedItems() {
Item[] selectedItems = new Item[]{
new ItemImpl("c01", "分类01", "p01", "SPU01", "k01", "SKU01", 2000),
new ItemImpl("c01", "分类01", "p01", "SPU01", "k01", "SKU01", 2000),
new ItemImpl("c01", "分类01", "p01", "SPU01", "k02", "SKU02", 3000),
new ItemImpl("c01", "分类01", "p02", "SPU02", "k03", "SKU03", 4000),
new ItemImpl("c02", "分类02", "p03", "SPU03", "k04", "SKU04", 5000),
new ItemImpl("c03", "分类03", "p04", "SPU04", "k05", "SKU05", 6000),
new ItemImpl("c04", "分类04", "p05", "SPU05", "k06", "SKU06", 7000),
new ItemImpl("c05", "分类05", "p06", "SPU06", "k07", "SKU07", 8000),
new ItemImpl("c06", "分类06", "p07", "SPU07", "k08", "SKU08", 9000),
new ItemImpl("c07", "分类07", "p08", "SPU08", "k09", "SKU09", 2000),
new ItemImpl("c08", "分类08", "p09", "SPU09", "t10", "SKU10", 3000)
};
return Arrays.stream(selectedItems).collect(Collectors.toList());
}
private static List<Item> _getRandomPriceItems() {
Random r = new Random();
Item[] selectedItems = new Item[]{
new ItemImpl("c01", "分类01", "p01", "SPU01", "k01", "SKU01", (1 + r.nextInt(9)) * 1000),
new ItemImpl("c01", "分类01", "p01", "SPU01", "k01", "SKU01", (1 + r.nextInt(9)) * 1000),
new ItemImpl("c01", "分类01", "p01", "SPU01", "k02", "SKU02", (1 + r.nextInt(9)) * 1000),
new ItemImpl("c01", "分类01", "p02", "SPU02", "k03", "SKU03", (1 + r.nextInt(9)) * 1000),
new ItemImpl("c02", "分类02", "p03", "SPU03", "k04", "SKU04", (1 + r.nextInt(9)) * 1000),
new ItemImpl("c03", "分类03", "p04", "SPU04", "k05", "SKU05", (1 + r.nextInt(9)) * 1000),
new ItemImpl("c04", "分类04", "p05", "SPU05", "k06", "SKU06", (1 + r.nextInt(9)) * 1000),
new ItemImpl("c05", "分类05", "p06", "SPU06", "k07", "SKU07", (1 + r.nextInt(9)) * 1000),
new ItemImpl("c06", "分类06", "p07", "SPU07", "k08", "SKU08", (1 + r.nextInt(9)) * 1000),
new ItemImpl("c07", "分类07", "p08", "SPU08", "k09", "SKU09", (1 + r.nextInt(9)) * 1000),
new ItemImpl("c08", "分类08", "p09", "SPU09", "t10", "SKU10", (1 + r.nextInt(9)) * 1000)
};
return Arrays.stream(selectedItems).collect(Collectors.toList());
}
void _logBestMatch(BestMatch bestMatch){
//System.out.println(JSON.toJSONString(bestMatch, SerializerFeature.PrettyFormat));
if (bestMatch == null) {
System.out.println("no match");
return;
}
System.out.println("matches:[");
for(Match m : bestMatch.getMatches()){
System.out.println("\tmatch of "+m.getRule()+":[");
for (Item t : m.getItems()) {
System.out.println("\t\t" + ((ItemImpl) t).toString());
}
System.out.println("\t]");
}
System.out.println("]");
System.out.printf("sum price:%d \t\tsum discount: %d\n", bestMatch.totalPrice(), bestMatch.totalDiscount());
System.out.println("left:[");
for (Item t : bestMatch.left()) {
System.out.println("\t" + ((ItemImpl) t).toString());
}
System.out.println("]");
System.out.println("suggestion:");
System.out.println(bestMatch.getSuggestion());
}
@Test
public void bestMatch() {
Rule r1 = Builder.rule().simplex()
.range("[#cc01]")
.predict(P.COUNT)
.expected(2)
.endRule()
.promotion("-200")
.build();
Rule r2 = Builder.rule().simplex()
.addRange(R.CATEGORY, "c01")
.predict(P.COUNT)
.expected(3)
.endRule()
.promotion("-300")
.build();
Rule r3 = Builder.rule().simplex()
.addRangeAll()
.predict(P.COUNT)
.expected(6)
.endRule()
.promotion("-10%")
.build();
List<Item> items = _getSelectedItems();
List<Rule> rules = Arrays.asList(r1, r2);
BestMatch bestMatch = Strategy.bestMatch(rules, items);
Assert.assertEquals(2, bestMatch.getMatches().size());
Assert.assertEquals(r1, bestMatch.getMatches().get(0).getRule());
//System.out.println("best:");
//_logBestMatch(bestMatch);
BestMatch bestMatch1 = Strategy.bestChoice(rules, items, MatchType.OneRule);
Assert.assertEquals(bestMatch.getMatches().get(0).getRule(),bestMatch1.getMatches().get(0).getRule());
Assert.assertEquals(bestMatch.totalDiscount(),bestMatch1.totalDiscount());
BestMatch bestOfOnce = Strategy.bestOfOnlyOnceDiscount(rules, items);
//System.out.println("best of only once discount:");
//_logBestMatch(bestOfOnce);
bestMatch1 = Strategy.bestChoice(rules, items,MatchType.OneTime);
Assert.assertEquals(bestOfOnce.getMatches().get(0).getRule(),bestMatch1.getMatches().get(0).getRule());
Assert.assertEquals(bestOfOnce.totalDiscount(),bestMatch1.totalDiscount());
// 5 tickets matched
items.add(new ItemImpl("c01", "分类01", "p02", "SPU02", "k03", "SKU03", 4000));
//BestMatch bestOfMulti = Strategy.bestOfMultiRuleApply(rules,tickets);
BestMatch bestOfMulti = Strategy.bestChoice(rules, items, MatchType.MultiRule);
Assert.assertEquals(2,bestOfMulti.getMatches().size());
Assert.assertEquals(5,bestOfMulti.chosen().size());
Assert.assertEquals(-500,bestOfMulti.totalDiscount());
//System.out.println("best of multi-rule apply:");
//_logBestMatch(bestOfMulti);
// 6 tickets matched
items.add(new ItemImpl("c01", "分类01", "p02", "SPU02", "k03", "SKU03", 4000));
bestOfMulti = Strategy.bestChoice(rules, items,MatchType.MultiRule);
Assert.assertEquals(6,bestOfMulti.chosen().size());
Assert.assertEquals(-600,bestOfMulti.totalDiscount());
//System.out.println("best of multi-rule apply:");
//_logBestMatch(bestOfMulti);
// 7 tickets matched
items.add(new ItemImpl("c01", "分类01", "p02", "SPU02", "k03", "SKU03", 4000));
bestOfMulti = Strategy.bestChoice(rules, items,MatchType.MultiRule);
Assert.assertEquals(3,bestOfMulti.getMatches().size());
Assert.assertEquals(7,bestOfMulti.chosen().size());
Assert.assertEquals(-700,bestOfMulti.totalDiscount());
System.out.println("best of multi-rule apply:");
_logBestMatch(bestOfMulti);
// 7 tickets matched
Rule r4 = Builder.rule().simplex().addRange(R.SPU,"p02")
.predict(P.COUNT).expected(4).endRule()
.promotion("-2000").build();
rules = Arrays.asList(r1,r2,r3,r4);
bestOfMulti = Strategy.bestChoice(rules, items,MatchType.MultiRule);
//Assert.assertEquals(3,bestOfMulti.getMatches().size());
Assert.assertEquals(14,bestOfMulti.chosen().size());
Assert.assertEquals(-400-300-2000-500-600-700-800-900-200-300,bestOfMulti.totalDiscount());
System.out.println("best of multi-rule apply:");
_logBestMatch(bestOfMulti);
r3.setPromotion("-100");
bestOfMulti = Strategy.bestChoice(rules, items,MatchType.MultiRule);
_logBestMatch(bestOfMulti);
}
@Test
public void testSum() {
Rule r1 = Builder.rule()
.simplex()
.addRange(R.CATEGORY, "c01")
.predict(P.SUM)
.expected(8000)
.endRule()
.promotion("-900")
.build();
List<Item> selectedItems = _getSelectedItems();
BestMatch bestMatch = Strategy.bestMatch(Arrays.asList(r1), selectedItems);
Assert.assertEquals(1, bestMatch.getMatches().size());
//选出20,20,30,40中的20,20,40
Assert.assertEquals(8000, bestMatch.totalPrice());
_logBestMatch(bestMatch);
Rule r2 = Builder.rule()
.simplex()
.addRangeAll()
.predict(P.SUM)
.expected(8000)
.endRule()
.promotion("-800")
.build();
bestMatch = Strategy.bestMatch(Arrays.asList(r1, r2), selectedItems);
Assert.assertEquals(r2, bestMatch.getMatches().get(0).getRule());
_logBestMatch(bestMatch);//选出的是$.sum(8000),且有6组
BestMatch bestOfOnce = Strategy.bestOfOnlyOnceDiscount(Arrays.asList(r1, r2), selectedItems);
System.out.println("best of only once discount:");
_logBestMatch(bestOfOnce);//选出的是[#cc01].sum(8000),因为只算一组的话,这一条规则优惠90,比$这一条多10
}
@Test
public void testSumOfRandomItems() {
Rule r1 = Builder.rule()
.simplex()
.addRange(R.CATEGORY, "c01")
.predict(P.SUM)
.expected(8000)
.endRule()
.promotion("-800")
.build();
List<Item> selectedItems = _getRandomPriceItems();
BestMatch bestMatch = Strategy.bestMatch(Arrays.asList(r1), selectedItems);
_logBestMatch(bestMatch);
Rule r2 = Builder.rule()
.simplex()
.addRangeAll()
.predict(P.SUM)
.expected(8000)
.endRule()
.promotion("-800")
.build();
bestMatch = Strategy.bestMatch(Arrays.asList(r1, r2), selectedItems);
_logBestMatch(bestMatch);
}
@Test
public void testComposite() {
Rule and = Builder.rule()
.and().simplex()
.range("[#cc01]")
.predict(P.COUNT)
.expected(2)
.end()
.sameRange()
.predict(P.SUM)
.expected(8000)
.end()
.endRule()
.promotion("-800")
.build();
System.out.println(and);
List<Item> items = _getSelectedItems();
List<Rule> rules = Arrays.asList(and);
BestMatch bestMatch = Strategy.bestMatch(rules, items);
_logBestMatch(bestMatch);
Assert.assertEquals(1,bestMatch.getMatches().size());
Assert.assertEquals(3,bestMatch.chosen().size());
Rule or = Builder
.rule()
.or()
.addRule(and.getCondition())
.simplex()
.addRangeAll()
.predict(P.SUM)
.expected(8000)
.end()
.end()
.endRule()
.promotion("-800")
.build();
System.out.println(or);
rules = Arrays.asList(or);
bestMatch = Strategy.bestMatch(rules, items);
_logBestMatch(bestMatch);
Assert.assertEquals(6,bestMatch.getMatches().size());
Assert.assertEquals(11,bestMatch.chosen().size());
}
@Test
public void testOnce() {//总共9个商品,100块的2张,120块的6张,0.5块的1张
Rule r = Interpreter.parseString("[#k6246d389d1812e77f772d1db].sum(15000)&~.countCate(1) -> -2000/15000").asRule();
List<Item> items = Arrays.asList(
new ItemImpl("6246d311d1812e77f772b1fe", "分类01", "6246d321d1812e77f772b61c", "SPU01", "6246d389d1812e77f772d1d6", "SKU01", 10000),
new ItemImpl("6246d311d1812e77f772b1fe", "分类01", "6246d321d1812e77f772b61c", "SPU01", "6246d389d1812e77f772d1d6", "SKU01", 10000),
new ItemImpl("6246d311d1812e77f772b1fe", "分类01", "6246d321d1812e77f772b61c", "SPU01", "6246d389d1812e77f772d1db", "SKU02", 19000),
new ItemImpl("6246d311d1812e77f772b1fe", "分类01", "6246d321d1812e77f772b61c", "SPU01", "6246d389d1812e77f772d1db", "SKU02", 19000)
);
List<Rule> rules = Arrays.asList(r);
BestMatch result = Strategy.bestOfOnlyOnceDiscount(rules, items);
System.out.println(result.totalDiscount());//should be -2000
result = Strategy.bestMatch(rules, items);
System.out.println(result.totalDiscount()); //should be -4000
}
@Test
public void test4DiscountingAlgorithm() {
//规则是100块的和120块的总共要6张,并且两种商品都要有
String ruleString = "[#k01#k02].count(6)&~.countCate(2) -> -50%";
Rule r = Interpreter.parseString(ruleString).asRule();
List<Item> items = Arrays.asList(
new ItemImpl("01", "分类01", "01", "SPU01", "01", "SKU01", 10000),
new ItemImpl("01", "分类01", "01", "SPU01", "01", "SKU01", 10000),
new ItemImpl("02", "分类02", "02", "SPU01", "02", "SKU01", 121200),
new ItemImpl("02", "分类02", "02", "SPU01", "02", "SKU02", 121200),
new ItemImpl("02", "分类02", "02", "SPU01", "02", "SKU02", 121200),
new ItemImpl("02", "分类02", "02", "SPU01", "02", "SKU02", 121200),
new ItemImpl("02", "分类02", "02", "SPU01", "02", "SKU02", 121200),
new ItemImpl("02", "分类02", "02", "SPU01", "02", "SKU02", 121200),
new ItemImpl("02", "分类02", "02", "SPU01", "03", "SKU03", 50)
);
List<Rule> rules = Arrays.asList(r);
int expected = 0, actual = 0;
//为了做规则推荐的运算,规则本身算折扣的方法里,
// 并没有判定规则是否已达成,所以调用前需做check()
if (r.check(items)) {
//第1种,rule.discountFilteredItems(tickets)
//计算的是规则范围内的这部分商品的折扣
//expected = tickets.stream().filter(r.getFilter()).map(t -> t.getPriceByFen()).reduce(0, (i1, i2) -> i1 + i2) / -2;
expected = items.stream().filter(r.getFilter()).map(t -> t.getPrice()).reduce(0, Integer::sum) / -2;
actual = r.discountFilteredItems(items);
System.out.println(expected);
Assert.assertEquals(expected, actual);
//第2种,rule.discount(tickets)
//计算的是所有商品应用折扣
//expected = tickets.stream().map(t -> t.getPriceByFen()).reduce(0, (i1, i2) -> i1 + i2) / -2;
expected = items.stream().map(t -> t.getPrice()).reduce(0, Integer::sum) / -2;
actual = r.discount(items);
System.out.println(expected);
Assert.assertEquals(expected, actual);
}
//第3种,Strategy.bestMath()
//非比率折扣,计算的是用最低成本达成规则匹配所需要的商品
//expected = (tickets.get(0).getPriceByFen() * 1 + tickets.get(2).getPriceByFen() * 5) / -2;
expected = (10000*2 + 121200 * 6)/-2;
actual = Strategy.bestMatch(rules, items).totalDiscount();
System.out.println(expected);
Assert.assertEquals(expected, actual);
//第4种,Strategy.bestOfOnlyOnceDiscount()
//计算达成规则所需的最少张数,但是是最高价格的商品
//expected = (tickets.get(0).getPriceByFen() * 1 + tickets.get(2).getPriceByFen() * 5) / -2;
BestMatch match = Strategy.bestOfOnlyOnceDiscount(rules, items);
actual = match.totalDiscount();
System.out.println(expected);
Assert.assertEquals(expected, actual);
System.out.println(match.left());
}
@Test
public void test_oneSKU() {
String ruleString2 = "[#k01#k02].oneSKU(2) -> -50%",
ruleString6 = "[#k01#k02].oneSKU(6) -> -50%",
ruleString7 = "$.oneSKU(7) -> -50%";
Rule rule2 = Interpreter.parseString(ruleString2).asRule(),
rule6 = Interpreter.parseString(ruleString6).asRule(),
rule7 = Interpreter.parseString(ruleString7).asRule();
List<Item> items = Arrays.asList(
new ItemImpl("01", "01", "01", "01", "01", "01", 10000),
new ItemImpl("01", "01", "01", "01", "01", "01", 10000),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "03", "03", 50)
);
Assert.assertTrue(rule2.check(items));
Assert.assertEquals((10000 * 2 + 121200 * 6 + 50) / -2, rule2.discount(items));//01,02,03
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, rule2.discountFilteredItems(items));//01,02
Assert.assertTrue(rule6.check(items));
Assert.assertEquals((10000 * 2 + 121200 * 6 + 50) / -2, rule6.discount(items));//01,02,03
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, rule6.discountFilteredItems(items));//01,02
BestMatch match = Strategy.bestMatch(Collections.singletonList(rule6), items);
//Assert.assertEquals(121200 * 6 / -2, match.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule6), items);
//Assert.assertEquals(121200 * 6 / -2, match.totalDiscount());//-2 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
Assert.assertTrue(!rule7.check(items)); //dont match
match = Strategy.bestMatch(Collections.singletonList(rule2), items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//01 * 2,02 * 6
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule2), items);
//Assert.assertEquals((121200 * 2) / -2, match.totalDiscount());//02 * 2
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
List<Rule> rules = Arrays.asList(rule2,rule6,rule7);
match = Strategy.bestMatch(rules, items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//matches rule2, gets 4 match groups
match = Strategy.bestOfOnlyOnceDiscount(rules, items);
//Assert.assertEquals((121200 * 6) / -2, match.totalDiscount());//matches rule6, gets 1 match group
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
}
@Test
public void testoneSKUSum() {
String ruleString2 = "[#k01#k02].oneSKUSum(20000) -> -50%",
ruleString6 = "[#k01#k02].oneSKUSum(727200) -> -50%",
ruleString7 = "$.oneSKUSum(727201) -> -50%";
Rule rule2 = Interpreter.parseString(ruleString2).asRule(),
rule6 = Interpreter.parseString(ruleString6).asRule(),
rule7 = Interpreter.parseString(ruleString7).asRule();
List<Item> items = Arrays.asList(
new ItemImpl("01", "01", "01", "01", "01", "01", 10000),
new ItemImpl("01", "01", "01", "01", "01", "01", 10000),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "02", "02", 121200),
new ItemImpl("02", "02", "02", "02", "03", "03", 50)
);
Assert.assertTrue(rule2.check(items));
Assert.assertEquals((10000 * 2 + 121200 * 6 + 50) / -2, rule2.discount(items));//01,02,03
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, rule2.discountFilteredItems(items));//01,02
Assert.assertTrue(rule6.check(items));
Assert.assertEquals((10000 * 2 + 121200 * 6 + 50) / -2, rule6.discount(items));//01,02,03
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, rule6.discountFilteredItems(items));//01,02
Assert.assertTrue(!rule7.check(items)); //dont match
//#region deprecated api
BestMatch match = Strategy.bestMatch(Collections.singletonList(rule6), items);
//Assert.assertEquals(121200 * 6 / -2, match.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule6), items);
//Assert.assertEquals(121200 * 6 / -2, match.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
match = Strategy.bestMatch(Collections.singletonList(rule2), items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//01 * 2,02 * 6
match = Strategy.bestOfOnlyOnceDiscount(Collections.singletonList(rule2), items);
//Assert.assertEquals(121200 / -2, match.totalDiscount());//02 * 2
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
List<Rule> rules = Arrays.asList(rule2,rule6,rule7);
match = Strategy.bestMatch(rules, items);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, match.totalDiscount());//matches rule2, gets 4 match groups
match = Strategy.bestOfOnlyOnceDiscount(rules, items);
//Assert.assertEquals((121200 * 6) / -2, match.totalDiscount());//matches rule6, gets 1 match group
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
//#endregion
//#region new api
BestMatch best = Strategy.bestChoice(Collections.singletonList(rule6), items,MatchType.OneRule);
//Assert.assertEquals(121200 * 6 / -2, best.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
best = Strategy.bestChoice(Collections.singletonList(rule6), items,MatchType.OneTime);
//Assert.assertEquals(121200 * 6 / -2, best.totalDiscount());//02 * 6
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
best = Strategy.bestChoice(Collections.singletonList(rule2), items,MatchType.OneRule);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, best.totalDiscount());//01 * 2,02 * 6
best = Strategy.bestChoice(Collections.singletonList(rule2), items, MatchType.OneTime);
//Assert.assertEquals(121200 / -2, best.totalDiscount());//02 * 1
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
rules = Arrays.asList(rule2,rule6,rule7);
best = Strategy.bestChoice(rules, items,MatchType.OneRule);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, best.totalDiscount());//matches rule2, gets 7 match groups
best = Strategy.bestChoice(rules, items, MatchType.OneTime);
//Assert.assertEquals((121200 * 6) / -2, best.totalDiscount());//matches rule6, gets 1 match group
Assert.assertEquals((121200 * 6 +10000*2) / -2, match.totalDiscount());//02 * 6 + 01 *2
best = Strategy.bestChoice(rules, items,MatchType.MultiRule);
Assert.assertEquals((10000 * 2 + 121200 * 6) / -2, best.totalDiscount());
Rule rule8 = Interpreter.parseString("[#k01#k02#k03].oneSKUSum(727200) -> -60%").asRule();
rules=Arrays.asList(rule2,rule6,rule7,rule8);
best = Strategy.bestChoice(rules, items,MatchType.MultiRule);
Assert.assertEquals((10000 * 2 + 121200 * 6 +50) * 6 / -10 , best.totalDiscount());
//#endregion
}
@Test
public void testDiscountPerPrice(){
List<Item> items = Arrays.asList(
new ItemImpl("01", "01", "01", "01", "01", "01", 39000),
new ItemImpl("01", "01", "01", "01", "02", "01", 11000),
new ItemImpl("02", "02", "02", "02", "03", "02", 11000)
);
Rule rule1 = Interpreter.parseString("$.count(3)->-7000/15000").asRule(),
rule2 = Interpreter.parseString("$.count(1)->-1000/10000").asRule(),
rule3 = Interpreter.parseString("$.sum(15000)->-7000/15000").asRule();
List<Rule> rules = Arrays.asList(rule1,rule2); | BestMatch bestMatch = Strategy.bestChoice(rules, items,MatchType.MultiRule, MatchGroup.CrossedMatch); | 2 | 2023-10-28 09:03:45+00:00 | 8k |
llllllxy/tiny-jdbc-boot-starter | src/main/java/org/tinycloud/jdbc/support/IObjectSupport.java | [
{
"identifier": "Criteria",
"path": "src/main/java/org/tinycloud/jdbc/criteria/Criteria.java",
"snippet": "public class Criteria extends AbstractCriteria {\n\n public <R> Criteria lt(String field, R value) {\n String condition = \" AND \" + field + \" < \" + \"?\";\n conditions.add(cond... | import org.springframework.util.CollectionUtils;
import org.tinycloud.jdbc.criteria.Criteria;
import org.tinycloud.jdbc.criteria.LambdaCriteria;
import org.tinycloud.jdbc.page.Page;
import java.util.Collection;
import java.util.List; | 7,023 | package org.tinycloud.jdbc.support;
/**
* <p>
* 对象操作接口,传入要执行的实例,操纵数据库,执行增、删、改、查操作,
* 前提是传入的实例中用@Table指定了数据库表,用@Column指定了表字段
* 对象操作只支持对单表的增、删、改、查。多表查询和存储过程等请使用sql操作接口或JdbcTemplate原生接口
* </p>
*
* @author liuxingyu01
* @since 2023-07-28-16:49
**/
public interface IObjectSupport<T, ID> {
/**
* 持久化插入给定的实例(默认忽略null值)
*
* @param entity 实例
* @return int 受影响的行数
*/
int insert(T entity);
/**
* 持久化插入给定的实例
*
* @param entity 实例
* @param ignoreNulls 是否忽略null值,true忽略,false不忽略
* @return int 受影响的行数
*/
int insert(T entity, boolean ignoreNulls);
/**
* 持久化插入给定的实例,并且返回自增主键
*
* @param entity 实例
* @return Integer 返回主键
*/
Long insertReturnAutoIncrement(T entity);
/**
* 持久化更新给定的实例(默认忽略null值),根据主键值更新
*
* @param entity 实例
* @return int 受影响的行数
*/
int updateById(T entity);
/**
* 持久化更新给定的实例,根据主键值更新
*
* @param entity 实例
* @param ignoreNulls 是否忽略null值,true忽略,false不忽略
* @return int 受影响的行数
*/
int updateById(T entity, boolean ignoreNulls);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param criteria 条件构造器
* @return int 受影响的行数
*/
int update(T entity, boolean ignoreNulls, Criteria criteria);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param lambdaCriteria 条件构造器(lambda版)
* @return int 受影响的行数
*/ | package org.tinycloud.jdbc.support;
/**
* <p>
* 对象操作接口,传入要执行的实例,操纵数据库,执行增、删、改、查操作,
* 前提是传入的实例中用@Table指定了数据库表,用@Column指定了表字段
* 对象操作只支持对单表的增、删、改、查。多表查询和存储过程等请使用sql操作接口或JdbcTemplate原生接口
* </p>
*
* @author liuxingyu01
* @since 2023-07-28-16:49
**/
public interface IObjectSupport<T, ID> {
/**
* 持久化插入给定的实例(默认忽略null值)
*
* @param entity 实例
* @return int 受影响的行数
*/
int insert(T entity);
/**
* 持久化插入给定的实例
*
* @param entity 实例
* @param ignoreNulls 是否忽略null值,true忽略,false不忽略
* @return int 受影响的行数
*/
int insert(T entity, boolean ignoreNulls);
/**
* 持久化插入给定的实例,并且返回自增主键
*
* @param entity 实例
* @return Integer 返回主键
*/
Long insertReturnAutoIncrement(T entity);
/**
* 持久化更新给定的实例(默认忽略null值),根据主键值更新
*
* @param entity 实例
* @return int 受影响的行数
*/
int updateById(T entity);
/**
* 持久化更新给定的实例,根据主键值更新
*
* @param entity 实例
* @param ignoreNulls 是否忽略null值,true忽略,false不忽略
* @return int 受影响的行数
*/
int updateById(T entity, boolean ignoreNulls);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param criteria 条件构造器
* @return int 受影响的行数
*/
int update(T entity, boolean ignoreNulls, Criteria criteria);
/**
* 持久化更新给定的实例(默认忽略null值)
*
* @param lambdaCriteria 条件构造器(lambda版)
* @return int 受影响的行数
*/ | int update(T entity, boolean ignoreNulls, LambdaCriteria lambdaCriteria); | 1 | 2023-10-25 14:44:59+00:00 | 8k |
Angular2Guy/AIDocumentLibraryChat | backend/src/main/java/ch/xxx/aidoclibchat/adapter/client/ImportRestClient.java | [
{
"identifier": "ImportClient",
"path": "backend/src/main/java/ch/xxx/aidoclibchat/domain/client/ImportClient.java",
"snippet": "public interface ImportClient {\n\tList<Artist> importArtists();\n\tList<Museum> importMuseums();\n\tList<MuseumHours> importMuseumHours();\n\tList<Work> importWorks();\n\tLis... | import java.io.IOException;
import java.util.List;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import ch.xxx.aidoclibchat.domain.client.ImportClient;
import ch.xxx.aidoclibchat.domain.model.dto.ArtistDto;
import ch.xxx.aidoclibchat.domain.model.dto.MuseumDto;
import ch.xxx.aidoclibchat.domain.model.dto.MuseumHoursDto;
import ch.xxx.aidoclibchat.domain.model.dto.SubjectDto;
import ch.xxx.aidoclibchat.domain.model.dto.WorkDto;
import ch.xxx.aidoclibchat.domain.model.dto.WorkLinkDto;
import ch.xxx.aidoclibchat.domain.model.entity.Artist;
import ch.xxx.aidoclibchat.domain.model.entity.Museum;
import ch.xxx.aidoclibchat.domain.model.entity.MuseumHours;
import ch.xxx.aidoclibchat.domain.model.entity.Subject;
import ch.xxx.aidoclibchat.domain.model.entity.Work;
import ch.xxx.aidoclibchat.domain.model.entity.WorkLink;
import ch.xxx.aidoclibchat.usecase.mapping.TableMapper; | 5,629 | /**
* Copyright 2023 Sven Loesekann
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 ch.xxx.aidoclibchat.adapter.client;
@Component
public class ImportRestClient implements ImportClient {
private final CsvMapper csvMapper;
private final TableMapper tableMapper;
public ImportRestClient(TableMapper tableMapper) {
this.tableMapper = tableMapper;
this.csvMapper = new CsvMapper();
this.csvMapper.registerModule(new JavaTimeModule());
}
@Override
public List<Artist> importArtists() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/artist.csv")
.retrieve().body(String.class);
return this.mapString(result, ArtistDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
private <T> List<T> mapString(String result, Class<T> myClass) {
List<T> zipcodes = List.of();
try {
zipcodes = this.csvMapper.readerFor(myClass).with(CsvSchema.builder().setUseHeader(true).build())
.<T>readValues(result).readAll();
} catch (IOException e) {
throw new RuntimeException(e);
}
return zipcodes;
}
@Override
public List<Museum> importMuseums() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/museum.csv")
.retrieve().body(String.class);
return this.mapString(result, MuseumDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
@Override
public List<MuseumHours> importMuseumHours() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/museum_hours.csv")
.retrieve().body(String.class);
return this.mapString(result, MuseumHoursDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
@Override
public List<Work> importWorks() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/work.csv")
.retrieve().body(String.class);
return this.mapString(result, WorkDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
@Override | /**
* Copyright 2023 Sven Loesekann
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 ch.xxx.aidoclibchat.adapter.client;
@Component
public class ImportRestClient implements ImportClient {
private final CsvMapper csvMapper;
private final TableMapper tableMapper;
public ImportRestClient(TableMapper tableMapper) {
this.tableMapper = tableMapper;
this.csvMapper = new CsvMapper();
this.csvMapper.registerModule(new JavaTimeModule());
}
@Override
public List<Artist> importArtists() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/artist.csv")
.retrieve().body(String.class);
return this.mapString(result, ArtistDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
private <T> List<T> mapString(String result, Class<T> myClass) {
List<T> zipcodes = List.of();
try {
zipcodes = this.csvMapper.readerFor(myClass).with(CsvSchema.builder().setUseHeader(true).build())
.<T>readValues(result).readAll();
} catch (IOException e) {
throw new RuntimeException(e);
}
return zipcodes;
}
@Override
public List<Museum> importMuseums() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/museum.csv")
.retrieve().body(String.class);
return this.mapString(result, MuseumDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
@Override
public List<MuseumHours> importMuseumHours() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/museum_hours.csv")
.retrieve().body(String.class);
return this.mapString(result, MuseumHoursDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
@Override
public List<Work> importWorks() {
RestClient restClient = RestClient.create();
String result = restClient.get().uri(
"https://raw.githubusercontent.com/Angular2Guy/AIDocumentLibraryChat/master/museumDataset/work.csv")
.retrieve().body(String.class);
return this.mapString(result, WorkDto.class).stream().map(myDto -> this.tableMapper.map(myDto)).toList();
}
@Override | public List<Subject> importSubjects() { | 10 | 2023-10-25 19:05:07+00:00 | 8k |
Fusion-Flux/Portal-Cubed-Rewrite | src/main/java/io/github/fusionflux/portalcubed/content/button/FloorButtonBlock.java | [
{
"identifier": "PortalCubedBlocks",
"path": "src/main/java/io/github/fusionflux/portalcubed/content/PortalCubedBlocks.java",
"snippet": "public class PortalCubedBlocks {\n\tpublic static final RotatedPillarBlock TEST_BLOCK = REGISTRAR.blocks.create(\"test_block\", RotatedPillarBlock::new)\n\t\t\t.copyF... | import java.util.HashMap;
import java.util.Map;
import java.util.function.Predicate;
import org.jetbrains.annotations.Nullable;
import io.github.fusionflux.portalcubed.content.PortalCubedBlocks;
import io.github.fusionflux.portalcubed.content.PortalCubedSounds;
import io.github.fusionflux.portalcubed.data.tags.PortalCubedEntityTags;
import io.github.fusionflux.portalcubed.framework.block.AbstractMultiBlock;
import io.github.fusionflux.portalcubed.framework.util.VoxelShaper;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.sounds.SoundEvent;
import net.minecraft.util.RandomSource;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntitySelector;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.gameevent.GameEvent;
import net.minecraft.world.phys.AABB;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.CollisionContext;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape; | 6,417 | public FloorButtonBlock(Properties properties, VoxelShaper[][] shapes, VoxelShape buttonShape, SoundEvent pressSound, SoundEvent releaseSound) {
this(properties, shapes, buttonShape, entity -> entity instanceof LivingEntity || entity.getType().is(PortalCubedEntityTags.PRESSES_FLOOR_BUTTONS), pressSound, releaseSound);
}
public FloorButtonBlock(Properties properties, SoundEvent pressSound, SoundEvent releaseSound) {
this(properties, new VoxelShaper[][]{
new VoxelShaper[]{
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(4, 1, 4, 16, 3, 16)), Direction.UP),
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(0, 1, 4, 12, 3, 16)), Direction.UP)
},
new VoxelShaper[]{
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(4, 1, 0, 16, 3, 12)), Direction.UP),
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(0, 1, 0, 12, 3, 12)), Direction.UP)
}
}, box(7.5, 7.5, 3, 16, 16, 4), pressSound, releaseSound);
}
public FloorButtonBlock(Properties properties) {
this(properties, PortalCubedSounds.FLOOR_BUTTON_PRESS, PortalCubedSounds.FLOOR_BUTTON_RELEASE);
}
public AABB getButtonBounds(Direction direction) {
return buttonBounds.computeIfAbsent(direction, blah -> {
var baseButtonBounds = buttonBounds.get(Direction.SOUTH);
var min = new Vec3(baseButtonBounds.minX, baseButtonBounds.minY, baseButtonBounds.minZ);
var max = new Vec3(baseButtonBounds.maxX, baseButtonBounds.maxY, baseButtonBounds.maxZ);
if (direction.getAxisDirection() == Direction.AxisDirection.NEGATIVE) {
min = VoxelShaper.rotate(min.subtract(1, 0, .5), 180, Direction.Axis.Y).add(1, 0, .5);
max = VoxelShaper.rotate(max.subtract(1, 0, .5), 180, Direction.Axis.Y).add(1, 0, .5);
}
var rotatedBounds = switch (direction.getAxis()) {
case Y -> new AABB(min.x, min.z, min.y, max.x, max.z, max.y);
case X -> new AABB(min.z, min.y, min.x, max.z, max.y, max.x);
case Z -> new AABB(min.x, min.y, min.z, max.x, max.y, max.z);
};
return rotatedBounds;
});
}
public void toggle(BlockState state, Level level, BlockPos pos, @Nullable Entity entity, boolean currentState) {
for (BlockPos quadrantPos : quadrantIterator(pos, state, level)) {
var quadrantState = level.getBlockState(quadrantPos);
if (!quadrantState.is(this)) return;
level.setBlock(quadrantPos, quadrantState.setValue(ACTIVE, !currentState), UPDATE_ALL);
}
SoundEvent toggleSound;
if (currentState) {
level.gameEvent(entity, GameEvent.BLOCK_DEACTIVATE, pos);
toggleSound = releaseSound;
} else {
level.scheduleTick(pos, this, PRESSED_TIME);
level.gameEvent(entity, GameEvent.BLOCK_ACTIVATE, pos);
toggleSound = pressSound;
}
playSoundAtCenter(toggleSound, 0, 0, -.5, 1f, 1f, pos, state, level);
}
@Override
public SizeProperties sizeProperties() {
return SIZE_PROPERTIES;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(ACTIVE);
}
@Override
public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) {
int y = getY(state);
int x = getX(state);
var facing = state.getValue(FACING);
var quadrantShape = switch (facing) {
case NORTH, EAST -> shapes[y == 1 ? 0 : 1][x == 1 ? 0 : 1];
case DOWN, WEST, SOUTH -> shapes[y == 1 ? 0 : 1][x];
default -> shapes[y][x];
};
return quadrantShape.get(facing);
}
@Override
public VoxelShape getOcclusionShape(BlockState state, BlockGetter level, BlockPos pos) {
return Shapes.empty();
}
@Override
public int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction direction) {
return state.getValue(ACTIVE) ? 15 : 0;
}
@Override
public boolean isSignalSource(BlockState state) {
return true;
}
@Override
public void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) {
if (level.getEntitiesOfClass(Entity.class, getButtonBounds(state.getValue(FACING)).move(pos), entityPredicate).size() > 0) {
level.scheduleTick(pos, this, PRESSED_TIME);
} else if (state.getValue(ACTIVE)) {
toggle(state, level, pos, null, true);
}
}
@Override
public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) {
if (!level.isClientSide) {
var originPos = getOriginPos(pos, state);
boolean entityPressing = entityPredicate.test(entity) && getButtonBounds(state.getValue(FACING)).move(originPos).intersects(entity.getBoundingBox());
if (entityPressing && !state.getValue(ACTIVE))
toggle(state, level, originPos, entity, false);
}
}
@Override
public String getDescriptionId() { | package io.github.fusionflux.portalcubed.content.button;
public class FloorButtonBlock extends AbstractMultiBlock {
public static final SizeProperties SIZE_PROPERTIES = SizeProperties.create(2, 2, 1);
public static final BooleanProperty ACTIVE = BooleanProperty.create("active");
public static final int PRESSED_TIME = 5;
public static int easterEggTrigger = 0;
public final VoxelShaper[][] shapes;
public final Map<Direction, AABB> buttonBounds = new HashMap<>();
public final Predicate<? super Entity> entityPredicate;
public final SoundEvent pressSound;
public final SoundEvent releaseSound;
public FloorButtonBlock(
Properties properties,
VoxelShaper[][] shapes,
VoxelShape buttonShape,
Predicate<? super Entity> entityPredicate,
SoundEvent pressSound,
SoundEvent releaseSound
) {
super(properties);
this.shapes = shapes;
this.buttonBounds.put(Direction.SOUTH, new AABB(
buttonShape.min(Direction.Axis.X) * 2,
buttonShape.min(Direction.Axis.Y) * 2,
buttonShape.min(Direction.Axis.Z),
buttonShape.max(Direction.Axis.X) * 2,
buttonShape.max(Direction.Axis.Y) * 2,
buttonShape.max(Direction.Axis.Z)
).move(-buttonShape.min(Direction.Axis.X), -buttonShape.min(Direction.Axis.Y), 0));
for (Direction direction : Direction.values()) getButtonBounds(direction);
this.entityPredicate = EntitySelector.NO_SPECTATORS.and(entity -> !entity.isIgnoringBlockTriggers()).and(entityPredicate);
this.pressSound = pressSound;
this.releaseSound = releaseSound;
this.registerDefaultState(this.stateDefinition.any().setValue(ACTIVE, false));
}
public FloorButtonBlock(Properties properties, VoxelShaper[][] shapes, VoxelShape buttonShape, SoundEvent pressSound, SoundEvent releaseSound) {
this(properties, shapes, buttonShape, entity -> entity instanceof LivingEntity || entity.getType().is(PortalCubedEntityTags.PRESSES_FLOOR_BUTTONS), pressSound, releaseSound);
}
public FloorButtonBlock(Properties properties, SoundEvent pressSound, SoundEvent releaseSound) {
this(properties, new VoxelShaper[][]{
new VoxelShaper[]{
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(4, 1, 4, 16, 3, 16)), Direction.UP),
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(0, 1, 4, 12, 3, 16)), Direction.UP)
},
new VoxelShaper[]{
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(4, 1, 0, 16, 3, 12)), Direction.UP),
VoxelShaper.forDirectional(Shapes.or(box(0, 0, 0, 16, 1, 16), box(0, 1, 0, 12, 3, 12)), Direction.UP)
}
}, box(7.5, 7.5, 3, 16, 16, 4), pressSound, releaseSound);
}
public FloorButtonBlock(Properties properties) {
this(properties, PortalCubedSounds.FLOOR_BUTTON_PRESS, PortalCubedSounds.FLOOR_BUTTON_RELEASE);
}
public AABB getButtonBounds(Direction direction) {
return buttonBounds.computeIfAbsent(direction, blah -> {
var baseButtonBounds = buttonBounds.get(Direction.SOUTH);
var min = new Vec3(baseButtonBounds.minX, baseButtonBounds.minY, baseButtonBounds.minZ);
var max = new Vec3(baseButtonBounds.maxX, baseButtonBounds.maxY, baseButtonBounds.maxZ);
if (direction.getAxisDirection() == Direction.AxisDirection.NEGATIVE) {
min = VoxelShaper.rotate(min.subtract(1, 0, .5), 180, Direction.Axis.Y).add(1, 0, .5);
max = VoxelShaper.rotate(max.subtract(1, 0, .5), 180, Direction.Axis.Y).add(1, 0, .5);
}
var rotatedBounds = switch (direction.getAxis()) {
case Y -> new AABB(min.x, min.z, min.y, max.x, max.z, max.y);
case X -> new AABB(min.z, min.y, min.x, max.z, max.y, max.x);
case Z -> new AABB(min.x, min.y, min.z, max.x, max.y, max.z);
};
return rotatedBounds;
});
}
public void toggle(BlockState state, Level level, BlockPos pos, @Nullable Entity entity, boolean currentState) {
for (BlockPos quadrantPos : quadrantIterator(pos, state, level)) {
var quadrantState = level.getBlockState(quadrantPos);
if (!quadrantState.is(this)) return;
level.setBlock(quadrantPos, quadrantState.setValue(ACTIVE, !currentState), UPDATE_ALL);
}
SoundEvent toggleSound;
if (currentState) {
level.gameEvent(entity, GameEvent.BLOCK_DEACTIVATE, pos);
toggleSound = releaseSound;
} else {
level.scheduleTick(pos, this, PRESSED_TIME);
level.gameEvent(entity, GameEvent.BLOCK_ACTIVATE, pos);
toggleSound = pressSound;
}
playSoundAtCenter(toggleSound, 0, 0, -.5, 1f, 1f, pos, state, level);
}
@Override
public SizeProperties sizeProperties() {
return SIZE_PROPERTIES;
}
@Override
protected void createBlockStateDefinition(StateDefinition.Builder<Block, BlockState> builder) {
super.createBlockStateDefinition(builder);
builder.add(ACTIVE);
}
@Override
public VoxelShape getShape(BlockState state, BlockGetter level, BlockPos pos, CollisionContext context) {
int y = getY(state);
int x = getX(state);
var facing = state.getValue(FACING);
var quadrantShape = switch (facing) {
case NORTH, EAST -> shapes[y == 1 ? 0 : 1][x == 1 ? 0 : 1];
case DOWN, WEST, SOUTH -> shapes[y == 1 ? 0 : 1][x];
default -> shapes[y][x];
};
return quadrantShape.get(facing);
}
@Override
public VoxelShape getOcclusionShape(BlockState state, BlockGetter level, BlockPos pos) {
return Shapes.empty();
}
@Override
public int getSignal(BlockState state, BlockGetter level, BlockPos pos, Direction direction) {
return state.getValue(ACTIVE) ? 15 : 0;
}
@Override
public boolean isSignalSource(BlockState state) {
return true;
}
@Override
public void tick(BlockState state, ServerLevel level, BlockPos pos, RandomSource random) {
if (level.getEntitiesOfClass(Entity.class, getButtonBounds(state.getValue(FACING)).move(pos), entityPredicate).size() > 0) {
level.scheduleTick(pos, this, PRESSED_TIME);
} else if (state.getValue(ACTIVE)) {
toggle(state, level, pos, null, true);
}
}
@Override
public void entityInside(BlockState state, Level level, BlockPos pos, Entity entity) {
if (!level.isClientSide) {
var originPos = getOriginPos(pos, state);
boolean entityPressing = entityPredicate.test(entity) && getButtonBounds(state.getValue(FACING)).move(originPos).intersects(entity.getBoundingBox());
if (entityPressing && !state.getValue(ACTIVE))
toggle(state, level, originPos, entity, false);
}
}
@Override
public String getDescriptionId() { | boolean hasEasterEgg = this == PortalCubedBlocks.FLOOR_BUTTON_BLOCK || this == PortalCubedBlocks.PORTAL_1_FLOOR_BUTTON_BLOCK; | 0 | 2023-10-25 05:32:39+00:00 | 8k |
ansforge/SAMU-Hub-Modeles | src/test/java/com/hubsante/model/builders/ReferenceWrapperBuilderTest.java | [
{
"identifier": "DistributionElement",
"path": "src/main/java/com/hubsante/model/common/DistributionElement.java",
"snippet": "@JsonPropertyOrder({DistributionElement.JSON_PROPERTY_MESSAGE_ID,\n DistributionElement.JSON_PROPERTY_SENDER,\n DistributionElement.JSON_PR... | import com.hubsante.model.common.DistributionElement;
import com.hubsante.model.common.Recipient;
import com.hubsante.model.common.ReferenceWrapper;
import com.hubsante.model.edxl.DistributionKind;
import com.hubsante.model.edxl.EdxlMessage;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows; | 4,887 | /**
* Copyright © 2023-2024 Agence du Numerique en Sante (ANS)
*
* 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.hubsante.model.builders;
public class ReferenceWrapperBuilderTest {
private final String DISTRIBUTION_ID = "id-12345";
private final String SENDER_ID = "sender-x";
private final String RECIPIENT_ID = "recipient-y";
/*
* Test the builder with a RC-REF built from builders
* first we build a RC-DE
* then we build a RC-REF from the RC-DE
* then we build an EDXL Message from the RC-REF
*/
@Test
@DisplayName("should build an EDXL Message from a built RC-REF")
public void shouldBuildEdxlFromRcRef() {
Recipient recipient = new Recipient().name(RECIPIENT_ID).URI("hubex:" + RECIPIENT_ID);
List<Recipient> recipientList = Stream.of(recipient).collect(Collectors.toList());
| /**
* Copyright © 2023-2024 Agence du Numerique en Sante (ANS)
*
* 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.hubsante.model.builders;
public class ReferenceWrapperBuilderTest {
private final String DISTRIBUTION_ID = "id-12345";
private final String SENDER_ID = "sender-x";
private final String RECIPIENT_ID = "recipient-y";
/*
* Test the builder with a RC-REF built from builders
* first we build a RC-DE
* then we build a RC-REF from the RC-DE
* then we build an EDXL Message from the RC-REF
*/
@Test
@DisplayName("should build an EDXL Message from a built RC-REF")
public void shouldBuildEdxlFromRcRef() {
Recipient recipient = new Recipient().name(RECIPIENT_ID).URI("hubex:" + RECIPIENT_ID);
List<Recipient> recipientList = Stream.of(recipient).collect(Collectors.toList());
| DistributionElement distributionElement = new DistributionElementBuilder(DISTRIBUTION_ID, SENDER_ID, recipientList) | 0 | 2023-10-25 14:24:31+00:00 | 8k |
yaroslav318/shop-telegram-bot | telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/commands/CartCommandHandler.java | [
{
"identifier": "CommandHandler",
"path": "telegram-bot/src/main/java/ua/ivanzaitsev/bot/handlers/CommandHandler.java",
"snippet": "public interface CommandHandler extends Handler {\n\n void executeCommand(AbsSender absSender, Update update, Long chatId) throws TelegramApiException;\n\n}"
},
{
... | import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.methods.updatingmessages.EditMessageText;
import org.telegram.telegrambots.meta.api.objects.CallbackQuery;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.InlineKeyboardMarkup;
import org.telegram.telegrambots.meta.api.objects.replykeyboard.buttons.InlineKeyboardButton;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;
import ua.ivanzaitsev.bot.handlers.CommandHandler;
import ua.ivanzaitsev.bot.handlers.UpdateHandler;
import ua.ivanzaitsev.bot.handlers.commands.registries.CommandHandlerRegistry;
import ua.ivanzaitsev.bot.models.domain.Button;
import ua.ivanzaitsev.bot.models.domain.CartItem;
import ua.ivanzaitsev.bot.models.domain.ClientOrder;
import ua.ivanzaitsev.bot.models.domain.Command;
import ua.ivanzaitsev.bot.models.domain.MessagePlaceholder;
import ua.ivanzaitsev.bot.models.entities.Client;
import ua.ivanzaitsev.bot.models.entities.Message;
import ua.ivanzaitsev.bot.models.entities.Product;
import ua.ivanzaitsev.bot.repositories.CartRepository;
import ua.ivanzaitsev.bot.repositories.ClientCommandStateRepository;
import ua.ivanzaitsev.bot.repositories.ClientOrderStateRepository;
import ua.ivanzaitsev.bot.repositories.ClientRepository;
import ua.ivanzaitsev.bot.services.MessageService; | 5,221 | package ua.ivanzaitsev.bot.handlers.commands;
public class CartCommandHandler implements CommandHandler, UpdateHandler {
private static final int MAX_QUANTITY_PER_PRODUCT = 50;
private static final String PRODUCT_QUANTITY_CALLBACK = "cart=product-quantity";
private static final String CURRENT_PAGE_CALLBACK = "cart=current-page";
private static final String DELETE_PRODUCT_CALLBACK = "cart=delete-product";
private static final String MINUS_PRODUCT_CALLBACK = "cart=minus-product";
private static final String PLUS_PRODUCT_CALLBACK = "cart=plus-product";
private static final String PREVIOUS_PRODUCT_CALLBACK = "cart=previous-product";
private static final String NEXT_PRODUCT_CALLBACK = "cart=next-product";
private static final String PROCESS_ORDER_CALLBACK = "cart=process-order";
private static final Set<String> CALLBACKS = Set.of(DELETE_PRODUCT_CALLBACK, MINUS_PRODUCT_CALLBACK,
PLUS_PRODUCT_CALLBACK, PREVIOUS_PRODUCT_CALLBACK, NEXT_PRODUCT_CALLBACK, PROCESS_ORDER_CALLBACK);
private final CommandHandlerRegistry commandHandlerRegistry;
private final ClientCommandStateRepository clientCommandStateRepository;
private final ClientOrderStateRepository clientOrderStateRepository;
private final CartRepository cartRepository;
private final ClientRepository clientRepository;
private final MessageService messageService;
public CartCommandHandler(
CommandHandlerRegistry commandHandlerRegistry,
ClientCommandStateRepository clientCommandStateRepository,
ClientOrderStateRepository clientOrderStateRepository,
CartRepository cartRepository,
ClientRepository clientRepository,
MessageService messageService) {
this.commandHandlerRegistry = commandHandlerRegistry;
this.clientCommandStateRepository = clientCommandStateRepository;
this.clientOrderStateRepository = clientOrderStateRepository;
this.cartRepository = cartRepository;
this.clientRepository = clientRepository;
this.messageService = messageService;
}
@Override | package ua.ivanzaitsev.bot.handlers.commands;
public class CartCommandHandler implements CommandHandler, UpdateHandler {
private static final int MAX_QUANTITY_PER_PRODUCT = 50;
private static final String PRODUCT_QUANTITY_CALLBACK = "cart=product-quantity";
private static final String CURRENT_PAGE_CALLBACK = "cart=current-page";
private static final String DELETE_PRODUCT_CALLBACK = "cart=delete-product";
private static final String MINUS_PRODUCT_CALLBACK = "cart=minus-product";
private static final String PLUS_PRODUCT_CALLBACK = "cart=plus-product";
private static final String PREVIOUS_PRODUCT_CALLBACK = "cart=previous-product";
private static final String NEXT_PRODUCT_CALLBACK = "cart=next-product";
private static final String PROCESS_ORDER_CALLBACK = "cart=process-order";
private static final Set<String> CALLBACKS = Set.of(DELETE_PRODUCT_CALLBACK, MINUS_PRODUCT_CALLBACK,
PLUS_PRODUCT_CALLBACK, PREVIOUS_PRODUCT_CALLBACK, NEXT_PRODUCT_CALLBACK, PROCESS_ORDER_CALLBACK);
private final CommandHandlerRegistry commandHandlerRegistry;
private final ClientCommandStateRepository clientCommandStateRepository;
private final ClientOrderStateRepository clientOrderStateRepository;
private final CartRepository cartRepository;
private final ClientRepository clientRepository;
private final MessageService messageService;
public CartCommandHandler(
CommandHandlerRegistry commandHandlerRegistry,
ClientCommandStateRepository clientCommandStateRepository,
ClientOrderStateRepository clientOrderStateRepository,
CartRepository cartRepository,
ClientRepository clientRepository,
MessageService messageService) {
this.commandHandlerRegistry = commandHandlerRegistry;
this.clientCommandStateRepository = clientCommandStateRepository;
this.clientOrderStateRepository = clientOrderStateRepository;
this.cartRepository = cartRepository;
this.clientRepository = clientRepository;
this.messageService = messageService;
}
@Override | public Command getCommand() { | 6 | 2023-10-29 15:49:41+00:00 | 8k |
MikiP98/HumilityAFM | src/main/java/io/github/mikip98/helpers/WoodenMosaicHelper.java | [
{
"identifier": "HumilityAFM",
"path": "src/main/java/io/github/mikip98/HumilityAFM.java",
"snippet": "public class HumilityAFM implements ModInitializer {\n\t// This logger is used to write text to the console and the log file.\n\t// It is considered best practice to use your mod id as the logger's nam... | import io.github.mikip98.HumilityAFM;
import io.github.mikip98.config.ModConfig;
import net.fabricmc.fabric.api.item.v1.FabricItemSettings;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.registry.FlammableBlockRegistry;
import net.minecraft.block.Block;
import net.minecraft.item.BlockItem;
import net.minecraft.item.Item;
import net.minecraft.registry.Registries;
import net.minecraft.registry.Registry;
import net.minecraft.sound.BlockSoundGroup;
import net.minecraft.util.Identifier; | 5,411 | package io.github.mikip98.helpers;
public class WoodenMosaicHelper {
public WoodenMosaicHelper() {
throw new IllegalStateException("Utility class, do not instantiate!\nUse \"init()\" and \"registerWoodenMosaicVariants()\" instead!");
}
private static final float WoodenMosaicStrength = 3.0f * ModConfig.mosaicsAndTilesStrengthMultiplayer; //1.5f
private static final FabricBlockSettings WoodenMosaicSettings = FabricBlockSettings.create().strength(WoodenMosaicStrength).requiresTool().sounds(BlockSoundGroup.WOOD);
public static String[] woodenMosaicVariantsNames;
public static Block[] woodenMosaicVariants;
public static Item[] woodenMosaicItemVariants;
public static void init() {
//Create wooden mosaic variants
String[] woodTypes = MainHelper.vanillaWoodTypes;
short woodenMosaicVariantsCount = (short) (woodTypes.length * (woodTypes.length-1));
woodenMosaicVariantsNames = new String[woodenMosaicVariantsCount];
woodenMosaicVariants = new Block[woodenMosaicVariantsCount];
woodenMosaicItemVariants = new Item[woodenMosaicVariantsCount];
short i = 0;
for (String woodType1 : woodTypes) {
for (String woodType2 : woodTypes) {
if (woodType1.equals(woodType2)) {
continue;
}
String woodenMosaicVariantName = woodType1 + "_" + woodType2;
woodenMosaicVariantsNames[i] = woodenMosaicVariantName;
//LOGGER.info("Creating wooden mosaic variant: " + woodenMosaicVariantsNames[i]);
// Create wooden mosaic variant
woodenMosaicVariants[i] = new Block(WoodenMosaicSettings);
// Create wooden mosaic variant item
woodenMosaicItemVariants[i] = new BlockItem(woodenMosaicVariants[i], new FabricItemSettings());
i++;
}
}
}
public static void registerWoodenMosaicVariants() {
//Register wooden mosaic variants
short i = 0;
for (String woodenMosaicVariantName : woodenMosaicVariantsNames) {
//LOGGER.info("Registering wooden mosaic variant: " + woodenMosaicVariantName);
// Register wooden mosaic variant | package io.github.mikip98.helpers;
public class WoodenMosaicHelper {
public WoodenMosaicHelper() {
throw new IllegalStateException("Utility class, do not instantiate!\nUse \"init()\" and \"registerWoodenMosaicVariants()\" instead!");
}
private static final float WoodenMosaicStrength = 3.0f * ModConfig.mosaicsAndTilesStrengthMultiplayer; //1.5f
private static final FabricBlockSettings WoodenMosaicSettings = FabricBlockSettings.create().strength(WoodenMosaicStrength).requiresTool().sounds(BlockSoundGroup.WOOD);
public static String[] woodenMosaicVariantsNames;
public static Block[] woodenMosaicVariants;
public static Item[] woodenMosaicItemVariants;
public static void init() {
//Create wooden mosaic variants
String[] woodTypes = MainHelper.vanillaWoodTypes;
short woodenMosaicVariantsCount = (short) (woodTypes.length * (woodTypes.length-1));
woodenMosaicVariantsNames = new String[woodenMosaicVariantsCount];
woodenMosaicVariants = new Block[woodenMosaicVariantsCount];
woodenMosaicItemVariants = new Item[woodenMosaicVariantsCount];
short i = 0;
for (String woodType1 : woodTypes) {
for (String woodType2 : woodTypes) {
if (woodType1.equals(woodType2)) {
continue;
}
String woodenMosaicVariantName = woodType1 + "_" + woodType2;
woodenMosaicVariantsNames[i] = woodenMosaicVariantName;
//LOGGER.info("Creating wooden mosaic variant: " + woodenMosaicVariantsNames[i]);
// Create wooden mosaic variant
woodenMosaicVariants[i] = new Block(WoodenMosaicSettings);
// Create wooden mosaic variant item
woodenMosaicItemVariants[i] = new BlockItem(woodenMosaicVariants[i], new FabricItemSettings());
i++;
}
}
}
public static void registerWoodenMosaicVariants() {
//Register wooden mosaic variants
short i = 0;
for (String woodenMosaicVariantName : woodenMosaicVariantsNames) {
//LOGGER.info("Registering wooden mosaic variant: " + woodenMosaicVariantName);
// Register wooden mosaic variant | Registry.register(Registries.BLOCK, new Identifier(HumilityAFM.MOD_ID, "wooden_mosaic_" + woodenMosaicVariantName), woodenMosaicVariants[i]); | 0 | 2023-10-30 12:11:22+00:00 | 8k |
admin4j/admin4j-dict | dict-provider-sql/src/main/java/com/admin4j/dict/provider/sql/autoconfigure/SqlProviderAutoconfigure.java | [
{
"identifier": "SqlDictManager",
"path": "dict-provider-sql/src/main/java/com/admin4j/dict/provider/sql/SqlDictManager.java",
"snippet": "public interface SqlDictManager {\n\n /**\n * 获取字典显示值\n *\n * @param dictType\n * @param code\n * @param codeFiled\n * @param labelFiled\n... | import com.admin4j.dict.provider.sql.SqlDictManager;
import com.admin4j.dict.provider.sql.SqlDictProperties;
import com.admin4j.dict.provider.sql.SqlDictProvider;
import com.admin4j.dict.provider.sql.SqlDictService;
import com.admin4j.dict.provider.sql.impl.JdbcSqlDictManager;
import com.admin4j.dict.provider.sql.impl.MybatisSqlDictManager;
import com.admin4j.dict.provider.sql.impl.PropertiesSqlDictService;
import com.admin4j.dict.provider.sql.impl.mapper.SqlDictMapper;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.mapper.MapperFactoryBean;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.core.JdbcTemplate; | 4,944 | package com.admin4j.dict.provider.sql.autoconfigure;
/**
* @author andanyang
* @since 2022/10/25 16:55
*/
@AutoConfigureOrder(value = Integer.MAX_VALUE)
@EnableConfigurationProperties(SqlDictProperties.class)
public class SqlProviderAutoconfigure {
@Bean
@ConditionalOnClass(name = "org.mybatis.spring.annotation.MapperScan")
public MapperFactoryBean<SqlDictMapper> sqlDictMapper(SqlSessionFactory sqlSessionFactory) {
MapperFactoryBean<SqlDictMapper> sqlDictMapperMapperFactoryBean = new MapperFactoryBean<>(SqlDictMapper.class);
sqlDictMapperMapperFactoryBean.setSqlSessionFactory(sqlSessionFactory);
return sqlDictMapperMapperFactoryBean;
}
@Bean
@ConditionalOnClass(name = "org.mybatis.spring.annotation.MapperScan")
@ConditionalOnBean(SqlDictMapper.class)
public MybatisSqlDictManager mybatisSqlDictManager(SqlDictMapper sqlDictMapper) {
return new MybatisSqlDictManager(sqlDictMapper);
}
@Bean
@ConditionalOnBean({SqlDictManager.class})
@ConditionalOnMissingBean(SqlDictService.class)
public PropertiesSqlDictService propertiesSqlDictService(SqlDictManager sqlDictManager, SqlDictProperties sqlDictProperties) {
return new PropertiesSqlDictService(sqlDictProperties, sqlDictManager);
}
@Bean
@ConditionalOnBean(SqlDictManager.class)
public SqlDictProvider sqlDictProvider(SqlDictManager sqlDictManager, SqlDictService sqlDictService) {
return new SqlDictProvider(sqlDictManager, sqlDictService);
}
@Bean
@ConditionalOnClass(name = "org.springframework.jdbc.core.JdbcTemplate")
@ConditionalOnBean(name = {"jdbcTemplate"})
@ConditionalOnMissingBean(MybatisSqlDictManager.class) | package com.admin4j.dict.provider.sql.autoconfigure;
/**
* @author andanyang
* @since 2022/10/25 16:55
*/
@AutoConfigureOrder(value = Integer.MAX_VALUE)
@EnableConfigurationProperties(SqlDictProperties.class)
public class SqlProviderAutoconfigure {
@Bean
@ConditionalOnClass(name = "org.mybatis.spring.annotation.MapperScan")
public MapperFactoryBean<SqlDictMapper> sqlDictMapper(SqlSessionFactory sqlSessionFactory) {
MapperFactoryBean<SqlDictMapper> sqlDictMapperMapperFactoryBean = new MapperFactoryBean<>(SqlDictMapper.class);
sqlDictMapperMapperFactoryBean.setSqlSessionFactory(sqlSessionFactory);
return sqlDictMapperMapperFactoryBean;
}
@Bean
@ConditionalOnClass(name = "org.mybatis.spring.annotation.MapperScan")
@ConditionalOnBean(SqlDictMapper.class)
public MybatisSqlDictManager mybatisSqlDictManager(SqlDictMapper sqlDictMapper) {
return new MybatisSqlDictManager(sqlDictMapper);
}
@Bean
@ConditionalOnBean({SqlDictManager.class})
@ConditionalOnMissingBean(SqlDictService.class)
public PropertiesSqlDictService propertiesSqlDictService(SqlDictManager sqlDictManager, SqlDictProperties sqlDictProperties) {
return new PropertiesSqlDictService(sqlDictProperties, sqlDictManager);
}
@Bean
@ConditionalOnBean(SqlDictManager.class)
public SqlDictProvider sqlDictProvider(SqlDictManager sqlDictManager, SqlDictService sqlDictService) {
return new SqlDictProvider(sqlDictManager, sqlDictService);
}
@Bean
@ConditionalOnClass(name = "org.springframework.jdbc.core.JdbcTemplate")
@ConditionalOnBean(name = {"jdbcTemplate"})
@ConditionalOnMissingBean(MybatisSqlDictManager.class) | public JdbcSqlDictManager jdbcSqlDictManager(JdbcTemplate jdbcTemplate) { | 4 | 2023-10-26 08:36:17+00:00 | 8k |
Nolij/Zume | src/main/java/dev/nolij/zume/ForgeZumeBootstrapper.java | [
{
"identifier": "Zume",
"path": "common/src/main/java/dev/nolij/zume/common/Zume.java",
"snippet": "public class Zume {\n\t\n\tpublic static final String MOD_ID = \"zume\";\n\tpublic static final Logger LOGGER = LogManager.getLogger(MOD_ID);\n\tpublic static final String CONFIG_FILE_NAME = MOD_ID + \".j... | import dev.nolij.zume.common.Constants;
import dev.nolij.zume.common.Zume;
import dev.nolij.zume.lexforge.LexZume;
import dev.nolij.zume.lexforge18.LexZume18;
import dev.nolij.zume.lexforge16.LexZume16;
import dev.nolij.zume.vintage.VintageZume;
import net.minecraftforge.fml.common.Mod; | 4,317 | package dev.nolij.zume;
@Mod(
value = Zume.MOD_ID,
modid = Zume.MOD_ID,
name = Constants.MOD_NAME,
version = Constants.MOD_VERSION,
acceptedMinecraftVersions = Constants.VINTAGE_VERSION_RANGE,
guiFactory = "dev.nolij.zume.vintage.VintageConfigProvider")
public class ForgeZumeBootstrapper {
public ForgeZumeBootstrapper() {
if (Zume.ZUME_VARIANT == null)
throw new AssertionError("""
Mixins did not load! Zume requires Mixins in order to work properly.
Please install one of the following mixin loaders:
14.4 - 16.0: MixinBootstrap
8.9 - 12.2: MixinBooter >= 5.0
7.10 - 12.2: UniMixins >= 0.1.15""");
switch (Zume.ZUME_VARIANT) {
case LEXFORGE -> new LexZume();
case LEXFORGE18 -> new LexZume18();
case LEXFORGE16 -> new LexZume16(); | package dev.nolij.zume;
@Mod(
value = Zume.MOD_ID,
modid = Zume.MOD_ID,
name = Constants.MOD_NAME,
version = Constants.MOD_VERSION,
acceptedMinecraftVersions = Constants.VINTAGE_VERSION_RANGE,
guiFactory = "dev.nolij.zume.vintage.VintageConfigProvider")
public class ForgeZumeBootstrapper {
public ForgeZumeBootstrapper() {
if (Zume.ZUME_VARIANT == null)
throw new AssertionError("""
Mixins did not load! Zume requires Mixins in order to work properly.
Please install one of the following mixin loaders:
14.4 - 16.0: MixinBootstrap
8.9 - 12.2: MixinBooter >= 5.0
7.10 - 12.2: UniMixins >= 0.1.15""");
switch (Zume.ZUME_VARIANT) {
case LEXFORGE -> new LexZume();
case LEXFORGE18 -> new LexZume18();
case LEXFORGE16 -> new LexZume16(); | case VINTAGE_FORGE -> new VintageZume(); | 4 | 2023-10-25 21:00:22+00:00 | 8k |
sanxiaoshitou/tower-boot | tower-boot-redis/src/main/java/com/hxl/redis/ExecuteRedisAutoConfiguration.java | [
{
"identifier": "CustomRedisProperties",
"path": "tower-boot-redis/src/main/java/com/hxl/redis/config/CustomRedisProperties.java",
"snippet": "@Data\n@ConfigurationProperties(prefix = \"spring.redis\")\npublic class CustomRedisProperties {\n\n /**\n * redis key前缀,一般用项目名做区分,数据隔离\n */\n priv... | import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxl.redis.config.CustomRedisProperties;
import com.hxl.redis.load.DefaultRedisServiceImpl;
import com.hxl.redis.load.RedisService;
import com.hxl.redis.serializer.KeyStringSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import javax.annotation.PostConstruct; | 4,237 | package com.hxl.redis;
/**
* @Author hxl
* @description
* @Date 2023-06-14 17:17
**/
@Slf4j
@EnableCaching
@Configuration
@EnableConfigurationProperties(CustomRedisProperties.class)
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class ExecuteRedisAutoConfiguration {
@Autowired
private RedisProperties redisProperties;
@PostConstruct
public void init() {
log.info("enabled Redis ,ip: {}", redisProperties.getHost());
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory,
ObjectMapper objectMapper, KeyStringSerializer keyStringSerializer) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
//key序列化方式
RedisSerializer<String> defalutSerializer = template.getStringSerializer();
//值序列化方式
RedisSerializer<Object> jsonRedisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
//设置key 的序列化方式
template.setKeySerializer(keyStringSerializer);
template.setHashKeySerializer(keyStringSerializer);
//设置值 的序列化方式
template.setValueSerializer(jsonRedisSerializer);
template.setHashValueSerializer(jsonRedisSerializer);
//设置默认的序列化方式
template.setDefaultSerializer(defalutSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
public KeyStringSerializer keyStringSerializer() {
return new KeyStringSerializer();
}
@Bean | package com.hxl.redis;
/**
* @Author hxl
* @description
* @Date 2023-06-14 17:17
**/
@Slf4j
@EnableCaching
@Configuration
@EnableConfigurationProperties(CustomRedisProperties.class)
@AutoConfigureBefore(RedisAutoConfiguration.class)
public class ExecuteRedisAutoConfiguration {
@Autowired
private RedisProperties redisProperties;
@PostConstruct
public void init() {
log.info("enabled Redis ,ip: {}", redisProperties.getHost());
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory,
ObjectMapper objectMapper, KeyStringSerializer keyStringSerializer) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
//key序列化方式
RedisSerializer<String> defalutSerializer = template.getStringSerializer();
//值序列化方式
RedisSerializer<Object> jsonRedisSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
//设置key 的序列化方式
template.setKeySerializer(keyStringSerializer);
template.setHashKeySerializer(keyStringSerializer);
//设置值 的序列化方式
template.setValueSerializer(jsonRedisSerializer);
template.setHashValueSerializer(jsonRedisSerializer);
//设置默认的序列化方式
template.setDefaultSerializer(defalutSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
public KeyStringSerializer keyStringSerializer() {
return new KeyStringSerializer();
}
@Bean | public RedisService redisService(ObjectMapper objectMapper, RedisTemplate<String, Object> redisTemplate) { | 2 | 2023-10-30 06:30:41+00:00 | 8k |
simply-kel/AlinLib | src/main/java/ru/kelcuprum/alinlib/gui/components/sliders/SliderPercent.java | [
{
"identifier": "Colors",
"path": "src/main/java/ru/kelcuprum/alinlib/Colors.java",
"snippet": "public class Colors {\r\n // @YonKaGor OC Colors\r\n // Uhh\r\n public static Integer SEADRIVE = 0xFF79c738;\r\n // Circus Hop\r\n public static Integer CLOWNFISH = 0xFFf1ae31;\r\n // You'll... | import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiGraphics;
import net.minecraft.client.gui.components.AbstractSliderButton;
import net.minecraft.network.chat.Component;
import ru.kelcuprum.alinlib.Colors;
import ru.kelcuprum.alinlib.config.Config;
import ru.kelcuprum.alinlib.config.Localization;
import ru.kelcuprum.alinlib.gui.InterfaceUtils;
| 4,717 | package ru.kelcuprum.alinlib.gui.components.sliders;
public class SliderPercent extends AbstractSliderButton {
private final InterfaceUtils.DesignType type;
public final double defaultConfig;
public final Config config;
public final String typeConfig;
public final String buttonMessage;
Component volumeState;
public SliderPercent(int x, int y, int width, int height, Config config, String typeConfig, int defaultConfig, Component component) {
this(x, y, width, height, InterfaceUtils.DesignType.ALINA, config, typeConfig, defaultConfig, component);
}
public SliderPercent(int x, int y, int width, int height, InterfaceUtils.DesignType type, Config config, String typeConfig, double defaultConfig, Component component) {
super(x, y, width, height, component, config.getNumber(typeConfig, defaultConfig).doubleValue());
this.type = type;
this.config = config;
this.typeConfig = typeConfig;
this.defaultConfig = defaultConfig;
this.buttonMessage = component.getString();
}
public void setActive(boolean active){
this.active = active;
}
@Override
public void setX(int x) {
super.setX(x);
}
@Override
public void setY(int y) {
super.setY(y);
}
@Override
public void setPosition(int x, int y) {
super.setPosition(x, y);
}
@Override
public void renderWidget(GuiGraphics guiGraphics, int i, int j, float tick) {
this.type.renderSliderBackground(guiGraphics, getX(), getY(), getWidth(), getHeight(), this.active, this.isHoveredOrFocused(), Colors.SEADRIVE, this.value, this);
| package ru.kelcuprum.alinlib.gui.components.sliders;
public class SliderPercent extends AbstractSliderButton {
private final InterfaceUtils.DesignType type;
public final double defaultConfig;
public final Config config;
public final String typeConfig;
public final String buttonMessage;
Component volumeState;
public SliderPercent(int x, int y, int width, int height, Config config, String typeConfig, int defaultConfig, Component component) {
this(x, y, width, height, InterfaceUtils.DesignType.ALINA, config, typeConfig, defaultConfig, component);
}
public SliderPercent(int x, int y, int width, int height, InterfaceUtils.DesignType type, Config config, String typeConfig, double defaultConfig, Component component) {
super(x, y, width, height, component, config.getNumber(typeConfig, defaultConfig).doubleValue());
this.type = type;
this.config = config;
this.typeConfig = typeConfig;
this.defaultConfig = defaultConfig;
this.buttonMessage = component.getString();
}
public void setActive(boolean active){
this.active = active;
}
@Override
public void setX(int x) {
super.setX(x);
}
@Override
public void setY(int y) {
super.setY(y);
}
@Override
public void setPosition(int x, int y) {
super.setPosition(x, y);
}
@Override
public void renderWidget(GuiGraphics guiGraphics, int i, int j, float tick) {
this.type.renderSliderBackground(guiGraphics, getX(), getY(), getWidth(), getHeight(), this.active, this.isHoveredOrFocused(), Colors.SEADRIVE, this.value, this);
| volumeState = Component.translatable(Localization.getRounding(this.value * 100, true)+"%");
| 2 | 2023-10-29 13:30:26+00:00 | 8k |
sergei-nazarov/friend-s_letter | src/main/java/com/example/friendsletter/controllers/AuthorizationController.java | [
{
"identifier": "User",
"path": "src/main/java/com/example/friendsletter/data/User.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\n@Entity\n@Table(name = \"users\")\n@ToString\npublic class User implements UserDetails {\n @Id\n @GeneratedValue(strategy = GenerationTyp... | import com.example.friendsletter.data.User;
import com.example.friendsletter.data.UserDto;
import com.example.friendsletter.errors.UserUpdateException;
import com.example.friendsletter.services.CustomUserDetailsService;
import com.example.friendsletter.services.LetterService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextHolderStrategy;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.Locale; | 3,879 | package com.example.friendsletter.controllers;
@Controller
@Slf4j
public class AuthorizationController { | package com.example.friendsletter.controllers;
@Controller
@Slf4j
public class AuthorizationController { | private final CustomUserDetailsService userService; | 3 | 2023-10-31 09:53:27+00:00 | 8k |
footcricket05/Whisp | src/chat/Client.java | [
{
"identifier": "CaptureView",
"path": "src/GUI/CaptureView.java",
"snippet": "public class CaptureView extends javax.swing.JDialog {\n \n private String ipMachine;\n private int portMachine;\n private String clientName;\n\n /**\n * Creates new form CaptureView\n */\n public Ca... | import GUI.CaptureView;
import GUI.ChatView;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger; | 4,707 | package chat;
/**
*
* @author dvcarrillo
*/
public class Client {
// Properties
private String clientName;
// Socket
private Socket clientSocket ;
// Streams
private InputStream inputStream;
private OutputStream outputStream;
private DataInputStream inData;
private DataOutputStream outData;
private boolean option = true;
private ChatView chatView;
public Client(ChatView chatView) {
this.chatView = chatView;
}
public String getUsername() {
return clientName;
}
public void SetConnection(String ip, int port) {
try {
clientSocket = new Socket(ip, port);
Thread th1 = new Thread(new Runnable() {
@Override
public void run() {
while (option) {
ListenData(chatView);
}
}
});
th1.start();
System.out.println("Successfully connected to " + ip + ":" + port);
} catch (IOException ex) {
System.err.println("ERROR: connection error");
System.exit(0);
}
}
public void SendMessage(String msg) {
try {
outputStream = clientSocket.getOutputStream();
outData = new DataOutputStream(outputStream);
outData.writeUTF(msg);
outData.flush();
} catch (IOException ex) {
System.err.println("ERROR: error sending data");
}
}
public void ListenData(ChatView chatView) {
try {
inputStream = clientSocket.getInputStream();
inData = new DataInputStream(inputStream);
chatView.AddRemoteMessage(inData.readUTF());
} catch (IOException ex) {
System.err.println("ERROR: error listening data");
}
}
public void CloseConnection() {
try {
outData.close();
inData.close();
clientSocket.close();
} catch (IOException ex) {
System.err.println("ERROR: error closing connection");
}
}
public void SetClientProperties(String name) {
clientName = name;
}
public static void main(String [] args) {
ChatView chatView = new ChatView();
Client cli = new Client(chatView);
| package chat;
/**
*
* @author dvcarrillo
*/
public class Client {
// Properties
private String clientName;
// Socket
private Socket clientSocket ;
// Streams
private InputStream inputStream;
private OutputStream outputStream;
private DataInputStream inData;
private DataOutputStream outData;
private boolean option = true;
private ChatView chatView;
public Client(ChatView chatView) {
this.chatView = chatView;
}
public String getUsername() {
return clientName;
}
public void SetConnection(String ip, int port) {
try {
clientSocket = new Socket(ip, port);
Thread th1 = new Thread(new Runnable() {
@Override
public void run() {
while (option) {
ListenData(chatView);
}
}
});
th1.start();
System.out.println("Successfully connected to " + ip + ":" + port);
} catch (IOException ex) {
System.err.println("ERROR: connection error");
System.exit(0);
}
}
public void SendMessage(String msg) {
try {
outputStream = clientSocket.getOutputStream();
outData = new DataOutputStream(outputStream);
outData.writeUTF(msg);
outData.flush();
} catch (IOException ex) {
System.err.println("ERROR: error sending data");
}
}
public void ListenData(ChatView chatView) {
try {
inputStream = clientSocket.getInputStream();
inData = new DataInputStream(inputStream);
chatView.AddRemoteMessage(inData.readUTF());
} catch (IOException ex) {
System.err.println("ERROR: error listening data");
}
}
public void CloseConnection() {
try {
outData.close();
inData.close();
clientSocket.close();
} catch (IOException ex) {
System.err.println("ERROR: error closing connection");
}
}
public void SetClientProperties(String name) {
clientName = name;
}
public static void main(String [] args) {
ChatView chatView = new ChatView();
Client cli = new Client(chatView);
| CaptureView captureView = new CaptureView(chatView, true); | 0 | 2023-10-31 07:52:11+00:00 | 8k |
naraazi/TerminalChess | src/chess/pieces/Pawn.java | [
{
"identifier": "Board",
"path": "src/boardgame/Board.java",
"snippet": "public class Board {\n private final Integer rows;\n private final Integer columns;\n private final Piece[][] pieces;\n\n public Board(Integer rows, Integer columns) {\n if (rows < 1 || columns < 1) {\n ... | import boardgame.Board;
import boardgame.Position;
import chess.ChessMatch;
import chess.ChessPiece;
import chess.Color; | 4,428 | package chess.pieces;
public class Pawn extends ChessPiece {
private final ChessMatch chessMatch;
public Pawn(Board board, Color color, ChessMatch chessMatch) {
super(board, color);
this.chessMatch = chessMatch;
}
@Override
public boolean[][] possibleMoves() {
boolean[][] mat = new boolean[getBoard().getRows()][getBoard().getColumns()]; | package chess.pieces;
public class Pawn extends ChessPiece {
private final ChessMatch chessMatch;
public Pawn(Board board, Color color, ChessMatch chessMatch) {
super(board, color);
this.chessMatch = chessMatch;
}
@Override
public boolean[][] possibleMoves() {
boolean[][] mat = new boolean[getBoard().getRows()][getBoard().getColumns()]; | Position p = new Position(0, 0); | 1 | 2023-10-26 19:27:08+00:00 | 8k |
llllllxy/tiny-security-boot-starter | src/main/java/org/tinycloud/security/provider/AbstractAuthProvider.java | [
{
"identifier": "AuthProperties",
"path": "src/main/java/org/tinycloud/security/AuthProperties.java",
"snippet": "@ConfigurationProperties(prefix = \"tiny-security\")\npublic class AuthProperties {\n\n private String storeType = \"redis\";\n\n private String tokenName = \"token\";\n\n private I... | import org.tinycloud.security.AuthProperties;
import org.tinycloud.security.util.AuthUtil;
import org.tinycloud.security.util.CookieUtil;
import javax.servlet.http.HttpServletRequest; | 4,264 | package org.tinycloud.security.provider;
public abstract class AbstractAuthProvider implements AuthProvider {
protected abstract AuthProperties getAuthProperties();
/**
* 获取token
* @return
*/
@Override
public String getToken() {
String token = AuthUtil.getToken(this.getAuthProperties().getTokenName());
return token;
}
/**
* 获取token
* @param request HttpServletRequest
* @return
*/
@Override
public String getToken(HttpServletRequest request) {
String token = AuthUtil.getToken(request, this.getAuthProperties().getTokenName());
return token;
}
/**
* 执行登录操作
*
* @param loginId 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等等
*/
@Override
public String login(Object loginId) {
String token = this.createToken(loginId);
// 设置 Cookie,通过 Cookie 上下文返回给前端 | package org.tinycloud.security.provider;
public abstract class AbstractAuthProvider implements AuthProvider {
protected abstract AuthProperties getAuthProperties();
/**
* 获取token
* @return
*/
@Override
public String getToken() {
String token = AuthUtil.getToken(this.getAuthProperties().getTokenName());
return token;
}
/**
* 获取token
* @param request HttpServletRequest
* @return
*/
@Override
public String getToken(HttpServletRequest request) {
String token = AuthUtil.getToken(request, this.getAuthProperties().getTokenName());
return token;
}
/**
* 执行登录操作
*
* @param loginId 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等等
*/
@Override
public String login(Object loginId) {
String token = this.createToken(loginId);
// 设置 Cookie,通过 Cookie 上下文返回给前端 | CookieUtil.setCookie(AuthUtil.getResponse(), this.getAuthProperties().getTokenName(), token); | 2 | 2023-10-26 08:13:08+00:00 | 8k |
0-Gixty-0/Grupp-11-OOPP | sailinggame/src/main/java/com/group11/application/SailingGameApplication.java | [
{
"identifier": "AControllerInterpretor",
"path": "sailinggame/src/main/java/com/group11/controller/AControllerInterpretor.java",
"snippet": "public abstract class AControllerInterpretor{\n\n private GlobalKeyListener globalKeyListener;\n\n protected AControllerInterpretor() {\n this.global... | import com.group11.controller.AControllerInterpretor;
import com.group11.controller.KeyboardInterpretor;
import com.group11.model.modelinitialization.AModelInitializer;
import com.group11.model.modelinitialization.IGameLoop;
import com.group11.model.modelinitialization.SailingGameLoop;
import com.group11.model.modelinitialization.SailingGameModel;
import com.group11.view.uicomponents.AppFrame; | 4,452 | package com.group11.application;
/**
* A class containing logic specific to the SailingGame application. The idea of our project was to make the source
* code as extendable as possible, therefore, if you wanted to create a new game you would only need to change this class.
*/
public class SailingGameApplication extends AApplication {
private static final int WINDOWWITH = 1100;
private static final int WINDOWHEIGHT = 1000;
private static final int MAPWIDTH = 65;
private static final int MAPHEIGHT = 30;
IGameLoop gameLoop;
AModelInitializer model; | package com.group11.application;
/**
* A class containing logic specific to the SailingGame application. The idea of our project was to make the source
* code as extendable as possible, therefore, if you wanted to create a new game you would only need to change this class.
*/
public class SailingGameApplication extends AApplication {
private static final int WINDOWWITH = 1100;
private static final int WINDOWHEIGHT = 1000;
private static final int MAPWIDTH = 65;
private static final int MAPHEIGHT = 30;
IGameLoop gameLoop;
AModelInitializer model; | AControllerInterpretor keyBoardInterpretor; | 0 | 2023-10-31 11:40:56+00:00 | 8k |
MattiDragon/JsonPatcher | src/main/java/io/github/mattidragon/jsonpatcher/patch/Patcher.java | [
{
"identifier": "JsonPatcher",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/JsonPatcher.java",
"snippet": "public class JsonPatcher implements ModInitializer {\n private static final Set<String> SUPPORTED_VERSIONS = new HashSet<>(Set.of(\"1\"));\n public static final String MOD_ID = \"... | import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.stream.JsonWriter;
import io.github.mattidragon.jsonpatcher.JsonPatcher;
import io.github.mattidragon.jsonpatcher.config.Config;
import io.github.mattidragon.jsonpatcher.lang.runtime.EvaluationContext;
import io.github.mattidragon.jsonpatcher.lang.runtime.EvaluationException;
import io.github.mattidragon.jsonpatcher.lang.runtime.Value;
import io.github.mattidragon.jsonpatcher.lang.runtime.stdlib.LibraryBuilder;
import io.github.mattidragon.jsonpatcher.metapatch.MetapatchLibrary;
import io.github.mattidragon.jsonpatcher.misc.DumpManager;
import io.github.mattidragon.jsonpatcher.misc.GsonConverter;
import io.github.mattidragon.jsonpatcher.misc.MetaPatchPackAccess;
import io.github.mattidragon.jsonpatcher.misc.ReloadDescription;
import net.minecraft.resource.InputSupplier;
import net.minecraft.resource.ResourceManager;
import net.minecraft.text.Text;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import net.minecraft.util.JsonHelper;
import org.apache.commons.lang3.mutable.MutableObject;
import org.jetbrains.annotations.Nullable;
import java.io.*;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.concurrent.*;
import java.util.function.Consumer; | 3,988 | package io.github.mattidragon.jsonpatcher.patch;
public class Patcher {
private static final ExecutorService PATCHING_EXECUTOR = new ThreadPoolExecutor(0,
Integer.MAX_VALUE,
5,
TimeUnit.SECONDS,
new SynchronousQueue<>(),
new ThreadFactoryBuilder().setNameFormat("JsonPatch Patcher (%s)").build());
private static final Gson GSON = new Gson();
private final ReloadDescription description;
private final PatchStorage patches;
public Patcher(ReloadDescription description, PatchStorage patches) {
this.description = description;
this.patches = patches;
}
private boolean hasPatches(Identifier id) {
return patches.hasPatches(id);
}
private JsonElement applyPatches(JsonElement json, Identifier id) {
var errors = new ArrayList<Exception>();
var activeJson = new MutableObject<>(JsonHelper.asObject(json, "patched file"));
try {
for (var patch : patches.getPatches(id)) {
var root = GsonConverter.fromGson(activeJson.getValue());
var timeBeforePatch = System.nanoTime();
var success = runPatch(patch, PATCHING_EXECUTOR, errors::add, patches, root, Settings.builder()
.target(id.toString())
.build());
var timeAfterPatch = System.nanoTime();
JsonPatcher.RELOAD_LOGGER.debug("Patched {} with {} in {}ms", id, patch.id(), (timeAfterPatch - timeBeforePatch) / 1e6);
if (success) {
activeJson.setValue(GsonConverter.toGson(root));
}
}
} catch (RuntimeException e) {
errors.add(e);
}
if (!errors.isEmpty()) {
errors.forEach(error -> JsonPatcher.RELOAD_LOGGER.error("Error while patching {}", id, error));
var message = "Encountered %s error(s) while patching %s. See logs/jsonpatch.log for details".formatted(errors.size(), id);
description.errorConsumer().accept(Text.literal(message).formatted(Formatting.RED));
if (Config.MANAGER.get().abortOnFailure()) {
throw new PatchingException(message);
} else {
JsonPatcher.MAIN_LOGGER.error(message);
}
}
return activeJson.getValue();
}
/**
* Runs a patch with proper error handling.
* @param patch The patch to run.
* @param executor An executor to run the patch on, required to run on another thread for timeout to work
* @param errorConsumer A consumer the receives errors from the patch.
* Errors are either {@link EvaluationException EvaluationExceptions} for errors within the patch,
* or {@link RuntimeException RuntimeExceptions} for timeouts and other errors not from the patch itself
* @param patchStorage A patch storage for resolution of libraries
* @param root The root object for the patch context, will be modified
* @return {@code true} if the patch completed successfully. If {@code false} the {@code errorConsumer} should have received an error.
*/
public static boolean runPatch(Patch patch, Executor executor, Consumer<RuntimeException> errorConsumer, PatchStorage patchStorage, Value.ObjectValue root, Settings settings) {
try {
var context = buildContext(patch.id(), patchStorage, root, settings);
CompletableFuture.runAsync(() -> patch.program().execute(context), executor)
.get(Config.MANAGER.get().patchTimeoutMillis(), TimeUnit.MILLISECONDS);
return true;
} catch (ExecutionException e) {
if (e.getCause() instanceof EvaluationException cause) {
errorConsumer.accept(cause);
} else if (e.getCause() instanceof StackOverflowError cause) {
errorConsumer.accept(new PatchingException("Stack overflow while applying patch %s".formatted(patch.id()), cause));
} else {
errorConsumer.accept(new RuntimeException("Unexpected error while applying patch %s".formatted(patch.id()), e));
}
} catch (InterruptedException e) {
errorConsumer.accept(new PatchingException("Async error while applying patch %s".formatted(patch.id()), e));
} catch (TimeoutException e) {
errorConsumer.accept(new PatchingException("Timeout while applying patch %s. Check for infinite loops and increase the timeout in the config.".formatted(patch.id()), e));
}
return false;
}
private static EvaluationContext buildContext(Identifier patchId, EvaluationContext.LibraryLocator libraryLocator, Value.ObjectValue root, Settings settings) {
var builder = EvaluationContext.builder();
builder.root(root);
builder.libraryLocator(libraryLocator);
builder.debugConsumer(value -> JsonPatcher.RELOAD_LOGGER.info("Debug from {}: {}", patchId, value));
builder.variable("_isLibrary", settings.isLibrary());
builder.variable("_target", settings.targetAsValue());
builder.variable("_isMetapatch", settings.isMetaPatch());
if (settings.isMetaPatch()) {
builder.variable("metapatch", new LibraryBuilder(MetapatchLibrary.class, settings.metaPatchLibrary).build());
}
return builder.build();
}
public InputSupplier<InputStream> patchInputStream(Identifier id, InputSupplier<InputStream> stream) {
if (!hasPatches(id)) return stream;
try {
JsonPatcher.RELOAD_LOGGER.debug("Patching {}", id);
var json = GSON.fromJson(new InputStreamReader(stream.get()), JsonElement.class);
json = applyPatches(json, id);
var out = new ByteArrayOutputStream();
var writer = new OutputStreamWriter(out);
GSON.toJson(json, new JsonWriter(writer));
writer.close();
DumpManager.dumpIfEnabled(id, description, json);
return () -> new ByteArrayInputStream(out.toByteArray());
} catch (JsonParseException | IOException e) {
JsonPatcher.RELOAD_LOGGER.error("Failed to patch json at {}", id, e);
if (Config.MANAGER.get().abortOnFailure()) {
throw new RuntimeException("Failed to patch json at %s".formatted(id), e);
}
return stream;
}
}
public void runMetaPatches(ResourceManager manager, Executor executor) { | package io.github.mattidragon.jsonpatcher.patch;
public class Patcher {
private static final ExecutorService PATCHING_EXECUTOR = new ThreadPoolExecutor(0,
Integer.MAX_VALUE,
5,
TimeUnit.SECONDS,
new SynchronousQueue<>(),
new ThreadFactoryBuilder().setNameFormat("JsonPatch Patcher (%s)").build());
private static final Gson GSON = new Gson();
private final ReloadDescription description;
private final PatchStorage patches;
public Patcher(ReloadDescription description, PatchStorage patches) {
this.description = description;
this.patches = patches;
}
private boolean hasPatches(Identifier id) {
return patches.hasPatches(id);
}
private JsonElement applyPatches(JsonElement json, Identifier id) {
var errors = new ArrayList<Exception>();
var activeJson = new MutableObject<>(JsonHelper.asObject(json, "patched file"));
try {
for (var patch : patches.getPatches(id)) {
var root = GsonConverter.fromGson(activeJson.getValue());
var timeBeforePatch = System.nanoTime();
var success = runPatch(patch, PATCHING_EXECUTOR, errors::add, patches, root, Settings.builder()
.target(id.toString())
.build());
var timeAfterPatch = System.nanoTime();
JsonPatcher.RELOAD_LOGGER.debug("Patched {} with {} in {}ms", id, patch.id(), (timeAfterPatch - timeBeforePatch) / 1e6);
if (success) {
activeJson.setValue(GsonConverter.toGson(root));
}
}
} catch (RuntimeException e) {
errors.add(e);
}
if (!errors.isEmpty()) {
errors.forEach(error -> JsonPatcher.RELOAD_LOGGER.error("Error while patching {}", id, error));
var message = "Encountered %s error(s) while patching %s. See logs/jsonpatch.log for details".formatted(errors.size(), id);
description.errorConsumer().accept(Text.literal(message).formatted(Formatting.RED));
if (Config.MANAGER.get().abortOnFailure()) {
throw new PatchingException(message);
} else {
JsonPatcher.MAIN_LOGGER.error(message);
}
}
return activeJson.getValue();
}
/**
* Runs a patch with proper error handling.
* @param patch The patch to run.
* @param executor An executor to run the patch on, required to run on another thread for timeout to work
* @param errorConsumer A consumer the receives errors from the patch.
* Errors are either {@link EvaluationException EvaluationExceptions} for errors within the patch,
* or {@link RuntimeException RuntimeExceptions} for timeouts and other errors not from the patch itself
* @param patchStorage A patch storage for resolution of libraries
* @param root The root object for the patch context, will be modified
* @return {@code true} if the patch completed successfully. If {@code false} the {@code errorConsumer} should have received an error.
*/
public static boolean runPatch(Patch patch, Executor executor, Consumer<RuntimeException> errorConsumer, PatchStorage patchStorage, Value.ObjectValue root, Settings settings) {
try {
var context = buildContext(patch.id(), patchStorage, root, settings);
CompletableFuture.runAsync(() -> patch.program().execute(context), executor)
.get(Config.MANAGER.get().patchTimeoutMillis(), TimeUnit.MILLISECONDS);
return true;
} catch (ExecutionException e) {
if (e.getCause() instanceof EvaluationException cause) {
errorConsumer.accept(cause);
} else if (e.getCause() instanceof StackOverflowError cause) {
errorConsumer.accept(new PatchingException("Stack overflow while applying patch %s".formatted(patch.id()), cause));
} else {
errorConsumer.accept(new RuntimeException("Unexpected error while applying patch %s".formatted(patch.id()), e));
}
} catch (InterruptedException e) {
errorConsumer.accept(new PatchingException("Async error while applying patch %s".formatted(patch.id()), e));
} catch (TimeoutException e) {
errorConsumer.accept(new PatchingException("Timeout while applying patch %s. Check for infinite loops and increase the timeout in the config.".formatted(patch.id()), e));
}
return false;
}
private static EvaluationContext buildContext(Identifier patchId, EvaluationContext.LibraryLocator libraryLocator, Value.ObjectValue root, Settings settings) {
var builder = EvaluationContext.builder();
builder.root(root);
builder.libraryLocator(libraryLocator);
builder.debugConsumer(value -> JsonPatcher.RELOAD_LOGGER.info("Debug from {}: {}", patchId, value));
builder.variable("_isLibrary", settings.isLibrary());
builder.variable("_target", settings.targetAsValue());
builder.variable("_isMetapatch", settings.isMetaPatch());
if (settings.isMetaPatch()) {
builder.variable("metapatch", new LibraryBuilder(MetapatchLibrary.class, settings.metaPatchLibrary).build());
}
return builder.build();
}
public InputSupplier<InputStream> patchInputStream(Identifier id, InputSupplier<InputStream> stream) {
if (!hasPatches(id)) return stream;
try {
JsonPatcher.RELOAD_LOGGER.debug("Patching {}", id);
var json = GSON.fromJson(new InputStreamReader(stream.get()), JsonElement.class);
json = applyPatches(json, id);
var out = new ByteArrayOutputStream();
var writer = new OutputStreamWriter(out);
GSON.toJson(json, new JsonWriter(writer));
writer.close();
DumpManager.dumpIfEnabled(id, description, json);
return () -> new ByteArrayInputStream(out.toByteArray());
} catch (JsonParseException | IOException e) {
JsonPatcher.RELOAD_LOGGER.error("Failed to patch json at {}", id, e);
if (Config.MANAGER.get().abortOnFailure()) {
throw new RuntimeException("Failed to patch json at %s".formatted(id), e);
}
return stream;
}
}
public void runMetaPatches(ResourceManager manager, Executor executor) { | if (!(manager instanceof MetaPatchPackAccess packAccess)) { | 4 | 2023-10-30 14:09:36+00:00 | 8k |
Abbas-Rizvi/p2p-social | src/main/backend/blockchain/PrivateMsg.java | [
{
"identifier": "KeyGen",
"path": "src/main/backend/crypt/KeyGen.java",
"snippet": "public class KeyGen implements Serializable {\n\n private static final long serialVersionUID = 123456789L;\n\n private static final String RSA = \"RSA\";\n\n private KeyPair kp;\n\n // Generating public & pri... | import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Base64;
import javax.crypto.Cipher;
import backend.crypt.KeyGen;
import network.NTPTimeService;
import network.PeersDatabase; | 3,835 | package backend.blockchain;
public class PrivateMsg implements Block {
private static final long serialVersionUID = 123456789L;
private NTPTimeService timeService; // for contacting time server
// header includes recipient, sender, time, msgtype
public BlockHeader header;
private String prevHash;
private String hash;
private String storedSignature; // sig encoded as string Base64
private String data;
private String sender;
private String recipient;
// ######################
// constructor
// ######################
public PrivateMsg(String previousHash, String data, BlockHeader header, PrivateKey privKey) {
this.header = header;
this.prevHash = previousHash;
this.hash = currentHash();
this.storedSignature = signBlock(privKey);
this.data = encrypt(data, privKey, header.getRecipient());
}
// ######################
// header functions
// ######################
@Override
public void genHeader(String recipientString, String msgType, String sender) {
header = new BlockHeader(
timeService.getNTPDate().getTime(),
recipientString,
msgType,
sender);
}
@Override
public BlockHeader readHeader() {
return header;
}
// ######################
// Block functions
// ######################
// encrypt message to sender
private String encrypt(String data, PrivateKey privKey, String recipient) {
// find user public key in string format
PeersDatabase db = new PeersDatabase();
String recipientPubKeyStr = db.lookupPublicKeyByName(recipient);
// convert string to a public key object | package backend.blockchain;
public class PrivateMsg implements Block {
private static final long serialVersionUID = 123456789L;
private NTPTimeService timeService; // for contacting time server
// header includes recipient, sender, time, msgtype
public BlockHeader header;
private String prevHash;
private String hash;
private String storedSignature; // sig encoded as string Base64
private String data;
private String sender;
private String recipient;
// ######################
// constructor
// ######################
public PrivateMsg(String previousHash, String data, BlockHeader header, PrivateKey privKey) {
this.header = header;
this.prevHash = previousHash;
this.hash = currentHash();
this.storedSignature = signBlock(privKey);
this.data = encrypt(data, privKey, header.getRecipient());
}
// ######################
// header functions
// ######################
@Override
public void genHeader(String recipientString, String msgType, String sender) {
header = new BlockHeader(
timeService.getNTPDate().getTime(),
recipientString,
msgType,
sender);
}
@Override
public BlockHeader readHeader() {
return header;
}
// ######################
// Block functions
// ######################
// encrypt message to sender
private String encrypt(String data, PrivateKey privKey, String recipient) {
// find user public key in string format
PeersDatabase db = new PeersDatabase();
String recipientPubKeyStr = db.lookupPublicKeyByName(recipient);
// convert string to a public key object | KeyGen keys = new KeyGen(); | 0 | 2023-10-28 06:29:00+00:00 | 8k |
nailuj1992/OracionesCatolicas | app/src/main/java/com/prayers/app/activity/rosary/RosaryApostlesCreedActivity.java | [
{
"identifier": "AbstractClosableActivity",
"path": "app/src/main/java/com/prayers/app/activity/AbstractClosableActivity.java",
"snippet": "public abstract class AbstractClosableActivity extends AbstractActivity {\n\n private Button btnHome;\n\n /**\n * Prepare all view fields.\n */\n p... | import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.prayers.app.activity.AbstractClosableActivity;
import com.prayers.app.activity.R;
import com.prayers.app.constants.GeneralConstants;
import com.prayers.app.constants.RedirectionConstants;
import com.prayers.app.mapper.RosaryMapper;
import com.prayers.app.model.rosary.Mysteries;
import com.prayers.app.utils.FieldsUtils;
import com.prayers.app.utils.RedirectionUtils; | 7,099 | package com.prayers.app.activity.rosary;
public class RosaryApostlesCreedActivity extends AbstractClosableActivity {
private Mysteries selectedMysteries;
private ImageView imgMysteriesBackground;
private TextView txtApostlesCreed1;
private TextView txtApostlesCreed2;
private Button btnPrev;
private Button btnNext;
@Override
public int getActivity() {
return R.layout.rosary_apostles_creed_activity;
}
@Override
public void prepareOthersActivity() {
imgMysteriesBackground = (ImageView) findViewById(R.id.rosary_mysteries_background);
txtApostlesCreed1 = (TextView) findViewById(R.id.txt_apostles_creed_1);
FieldsUtils.justifyText(txtApostlesCreed1);
txtApostlesCreed2 = (TextView) findViewById(R.id.txt_apostles_creed_2);
FieldsUtils.justifyText(txtApostlesCreed2);
btnPrev = (Button) findViewById(R.id.btn_prev);
btnPrev.setOnClickListener(v -> backAction());
btnNext = (Button) findViewById(R.id.btn_next);
btnNext.setOnClickListener(v -> nextAction());
}
@Override
public void updateViewState() {
try {
selectedMysteries = (Mysteries) getIntent().getExtras().getSerializable(RedirectionConstants.SELECTED_MYSTERIES);
RosaryMapper.changeImageForRosary(this, selectedMysteries, imgMysteriesBackground);
} catch (Exception ex) {
// TODO Log exception
}
}
@Override
public void backAction() {
Bundle bundle = new Bundle();
bundle.putSerializable(RedirectionConstants.SELECTED_MYSTERIES, selectedMysteries);
RedirectionUtils.redirectToAnotherActivityWithExtras(this, bundle, RosaryBeginActivity.class);
}
@Override
public void nextAction() {
Bundle bundle = new Bundle();
bundle.putSerializable(RedirectionConstants.SELECTED_MYSTERIES, selectedMysteries); | package com.prayers.app.activity.rosary;
public class RosaryApostlesCreedActivity extends AbstractClosableActivity {
private Mysteries selectedMysteries;
private ImageView imgMysteriesBackground;
private TextView txtApostlesCreed1;
private TextView txtApostlesCreed2;
private Button btnPrev;
private Button btnNext;
@Override
public int getActivity() {
return R.layout.rosary_apostles_creed_activity;
}
@Override
public void prepareOthersActivity() {
imgMysteriesBackground = (ImageView) findViewById(R.id.rosary_mysteries_background);
txtApostlesCreed1 = (TextView) findViewById(R.id.txt_apostles_creed_1);
FieldsUtils.justifyText(txtApostlesCreed1);
txtApostlesCreed2 = (TextView) findViewById(R.id.txt_apostles_creed_2);
FieldsUtils.justifyText(txtApostlesCreed2);
btnPrev = (Button) findViewById(R.id.btn_prev);
btnPrev.setOnClickListener(v -> backAction());
btnNext = (Button) findViewById(R.id.btn_next);
btnNext.setOnClickListener(v -> nextAction());
}
@Override
public void updateViewState() {
try {
selectedMysteries = (Mysteries) getIntent().getExtras().getSerializable(RedirectionConstants.SELECTED_MYSTERIES);
RosaryMapper.changeImageForRosary(this, selectedMysteries, imgMysteriesBackground);
} catch (Exception ex) {
// TODO Log exception
}
}
@Override
public void backAction() {
Bundle bundle = new Bundle();
bundle.putSerializable(RedirectionConstants.SELECTED_MYSTERIES, selectedMysteries);
RedirectionUtils.redirectToAnotherActivityWithExtras(this, bundle, RosaryBeginActivity.class);
}
@Override
public void nextAction() {
Bundle bundle = new Bundle();
bundle.putSerializable(RedirectionConstants.SELECTED_MYSTERIES, selectedMysteries); | bundle.putInt(RedirectionConstants.SELECTED_MYSTERY, GeneralConstants.FIRST_MYSTERY); | 1 | 2023-10-25 17:17:47+00:00 | 8k |
LeoK99/swtw45WS21_reupload | src/main/java/com/buschmais/Application.java | [
{
"identifier": "ADR",
"path": "backup/java/com/buschmais/adr/ADR.java",
"snippet": "@Document\n@Data\npublic final class ADR {\n\n\t@Getter(AccessLevel.PRIVATE)\n\t@Setter(AccessLevel.PRIVATE)\n\t@EqualsExclude\n\t@Id\n\tprivate String id;\n\n\t@Setter(AccessLevel.PRIVATE)\n\t@DBRef\n\tprivate ADRConta... | import com.buschmais.backend.adr.ADR;
import com.buschmais.backend.adr.ADRContainer;
import com.buschmais.backend.adr.ADRContainerRepository;
import com.buschmais.backend.adr.dataAccess.ADRDao;
import com.buschmais.backend.adr.status.ADRStatusApproved;
import com.buschmais.backend.adr.status.ADRStatusProposed;
import com.buschmais.backend.adr.status.ADRStatusSuperseded;
import com.buschmais.backend.adrAccess.AccessGroup;
import com.buschmais.backend.adrAccess.AccessRights;
import com.buschmais.backend.adrAccess.dataAccess.ADRAccessDao;
import com.buschmais.backend.users.User;
import com.buschmais.backend.users.dataAccess.UserDao;
import com.buschmais.backend.voting.ADRReview;
import com.buschmais.backend.voting.UserIsNotInvitedException;
import com.buschmais.backend.voting.VoteType;
import com.vaadin.flow.component.dependency.NpmPackage;
import com.vaadin.flow.component.page.AppShellConfigurator;
import com.vaadin.flow.component.page.Push;
import com.vaadin.flow.server.PWA;
import com.vaadin.flow.theme.Theme;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import java.util.Set; | 6,330 | package com.buschmais;
/**
* The entry point of the Spring Boot application.
*
* Use the @PWA annotation make the application installable on phones, tablets
* and some desktop browsers.
*
*/
@SpringBootApplication
@Theme(value = "swt21w45")
@PWA(name = "swt21w45", shortName = "swt21w45", offlineResources = {"images/logo.png"})
@NpmPackage(value = "line-awesome", version = "1.3.0")
@Push
@EnableMongoRepositories
public class Application extends SpringBootServletInitializer implements AppShellConfigurator, CommandLineRunner {
@Autowired
UserDao userRepo;
@Autowired
ADRDao adrRepo;
@Autowired
ADRAccessDao accessDao;
@Autowired
ADRContainerRepository adrContainerRepository;
public static ADRContainer root = new ADRContainer("root"); //just for testing this will be removed later
public static void main(String[] args) {
/*LaunchUtil.launchBrowserInDevelopmentMode(*/SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) {
userRepo.deleteAll();
adrRepo.deleteAll();
accessDao.deleteAll();
//ADRContainer root
root = adrContainerRepository.save(root);
/* User */ | package com.buschmais;
/**
* The entry point of the Spring Boot application.
*
* Use the @PWA annotation make the application installable on phones, tablets
* and some desktop browsers.
*
*/
@SpringBootApplication
@Theme(value = "swt21w45")
@PWA(name = "swt21w45", shortName = "swt21w45", offlineResources = {"images/logo.png"})
@NpmPackage(value = "line-awesome", version = "1.3.0")
@Push
@EnableMongoRepositories
public class Application extends SpringBootServletInitializer implements AppShellConfigurator, CommandLineRunner {
@Autowired
UserDao userRepo;
@Autowired
ADRDao adrRepo;
@Autowired
ADRAccessDao accessDao;
@Autowired
ADRContainerRepository adrContainerRepository;
public static ADRContainer root = new ADRContainer("root"); //just for testing this will be removed later
public static void main(String[] args) {
/*LaunchUtil.launchBrowserInDevelopmentMode(*/SpringApplication.run(Application.class, args);
}
@Override
public void run(String... args) {
userRepo.deleteAll();
adrRepo.deleteAll();
accessDao.deleteAll();
//ADRContainer root
root = adrContainerRepository.save(root);
/* User */ | User frode = new User("Frode", "frodemeier"); | 10 | 2023-10-25 15:18:06+00:00 | 8k |
MultiDuels/MultiDuels | common/src/main/java/dev/kafein/multiduels/common/menu/AbstractMenu.java | [
{
"identifier": "InventoryComponent",
"path": "common/src/main/java/dev/kafein/multiduels/common/components/InventoryComponent.java",
"snippet": "public interface InventoryComponent {\n View open(@NotNull PlayerComponent player);\n\n void close(@NotNull PlayerComponent player);\n\n void addItem... | import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import dev.kafein.multiduels.common.components.InventoryComponent;
import dev.kafein.multiduels.common.components.ItemComponent;
import dev.kafein.multiduels.common.components.PlayerComponent;
import dev.kafein.multiduels.common.menu.action.ClickAction;
import dev.kafein.multiduels.common.menu.action.ClickActionCollection;
import dev.kafein.multiduels.common.menu.button.Button;
import dev.kafein.multiduels.common.menu.button.ClickHandler;
import dev.kafein.multiduels.common.menu.misc.ClickResult;
import dev.kafein.multiduels.common.menu.misc.OpenCause;
import dev.kafein.multiduels.common.menu.misc.contexts.ClickContext;
import dev.kafein.multiduels.common.menu.misc.contexts.OpenContext;
import dev.kafein.multiduels.common.menu.view.Viewer;
import dev.kafein.multiduels.common.menu.view.ViewersHolder;
import ninja.leaping.configurate.ConfigurationNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*; | 4,944 | /*
* MIT License
*
* Copyright (c) 2023 Kafein
*
* 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 dev.kafein.multiduels.common.menu;
abstract class AbstractMenu implements Menu {
private final MenuProperties properties;
private final InventoryComponent.Factory inventoryFactory;
private final ItemComponent.Factory itemFactory;
private final Set<Button> buttons;
private final ClickActionCollection clickActions;
private final ViewersHolder viewers;
protected AbstractMenu(MenuProperties properties, InventoryComponent.Factory inventoryFactory, ItemComponent.Factory itemFactory) {
this.properties = properties;
this.inventoryFactory = inventoryFactory;
this.itemFactory = itemFactory;
this.buttons = properties.getNode() == null ? Sets.newHashSet() : loadButtonsFromNode();
this.clickActions = new ClickActionCollection();
this.viewers = ViewersHolder.create();
}
protected AbstractMenu(MenuProperties properties, InventoryComponent.Factory inventoryFactory, ItemComponent.Factory itemFactory, Set<Button> buttons) {
this.properties = properties;
this.inventoryFactory = inventoryFactory;
this.itemFactory = itemFactory;
this.buttons = buttons;
this.clickActions = new ClickActionCollection();
this.viewers = ViewersHolder.create();
}
@Override
public Viewer open(@NotNull PlayerComponent player) {
return open(player, 0);
}
@Override
public Viewer open(@NotNull PlayerComponent player, int page) { | /*
* MIT License
*
* Copyright (c) 2023 Kafein
*
* 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 dev.kafein.multiduels.common.menu;
abstract class AbstractMenu implements Menu {
private final MenuProperties properties;
private final InventoryComponent.Factory inventoryFactory;
private final ItemComponent.Factory itemFactory;
private final Set<Button> buttons;
private final ClickActionCollection clickActions;
private final ViewersHolder viewers;
protected AbstractMenu(MenuProperties properties, InventoryComponent.Factory inventoryFactory, ItemComponent.Factory itemFactory) {
this.properties = properties;
this.inventoryFactory = inventoryFactory;
this.itemFactory = itemFactory;
this.buttons = properties.getNode() == null ? Sets.newHashSet() : loadButtonsFromNode();
this.clickActions = new ClickActionCollection();
this.viewers = ViewersHolder.create();
}
protected AbstractMenu(MenuProperties properties, InventoryComponent.Factory inventoryFactory, ItemComponent.Factory itemFactory, Set<Button> buttons) {
this.properties = properties;
this.inventoryFactory = inventoryFactory;
this.itemFactory = itemFactory;
this.buttons = buttons;
this.clickActions = new ClickActionCollection();
this.viewers = ViewersHolder.create();
}
@Override
public Viewer open(@NotNull PlayerComponent player) {
return open(player, 0);
}
@Override
public Viewer open(@NotNull PlayerComponent player, int page) { | return open(player, page, OpenCause.OPEN); | 8 | 2023-10-31 10:55:38+00:00 | 8k |
aerospike/graph-synth | graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/Generator.java | [
{
"identifier": "GraphSchemaParser",
"path": "graph-synth/src/main/java/com/aerospike/graph/synth/emitter/generator/schema/GraphSchemaParser.java",
"snippet": "public interface GraphSchemaParser {\n GraphSchema parse();\n}"
},
{
"identifier": "GraphSchema",
"path": "graph-synth/src/main/j... | import com.aerospike.graph.synth.emitter.generator.schema.GraphSchemaParser;
import com.aerospike.graph.synth.emitter.generator.schema.definition.GraphSchema;
import com.aerospike.graph.synth.emitter.generator.schema.definition.VertexSchema;
import com.aerospike.graph.synth.emitter.generator.schema.seralization.YAMLSchemaParser;
import com.aerospike.graph.synth.process.tasks.generator.Generate;
import com.aerospike.movement.config.core.ConfigurationBase;
import com.aerospike.movement.emitter.core.Emitable;
import com.aerospike.movement.emitter.core.Emitter;
import com.aerospike.movement.runtime.core.Runtime;
import com.aerospike.movement.runtime.core.driver.OutputIdDriver;
import com.aerospike.movement.runtime.core.driver.WorkChunkDriver;
import com.aerospike.movement.runtime.core.local.Loadable;
import com.aerospike.movement.test.mock.output.MockOutput;
import com.aerospike.movement.util.core.configuration.ConfigurationUtil;
import com.aerospike.movement.util.core.error.ErrorUtil;
import com.aerospike.movement.util.core.iterator.ext.IteratorUtils;
import com.aerospike.movement.util.core.runtime.RuntimeUtil;
import com.aerospike.graph.synth.util.generator.SchemaUtil;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.MapConfiguration;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream; | 3,815 | /*
* @author Grant Haywood <grant.haywood@aerospike.com>
* Developed May 2023 - Oct 2023
* Copyright (c) 2023 Aerospike Inc.
*/
package com.aerospike.graph.synth.emitter.generator;
/**
* @author Grant Haywood (<a href="http://iowntheinter.net">http://iowntheinter.net</a>)
*/
public class Generator extends Loadable implements Emitter {
@Override
public void init(final Configuration config) {
}
// Configuration first.
public static class Config extends ConfigurationBase {
public static final Config INSTANCE = new Config();
private Config() {
super();
}
@Override
public Map<String, String> defaultConfigMap(final Map<String, Object> config) {
return DEFAULTS;
}
@Override
public List<String> getKeys() {
return ConfigurationUtil.getKeysFromClass(Config.Keys.class);
}
public static class Keys {
public static final String SCALE_FACTOR = "generator.scaleFactor";
public static final String CHANCE_TO_JOIN = "generator.chanceToJoin";
public static final String SCHEMA_PARSER = "generator.schemaGraphParser";
}
private static final Map<String, String> DEFAULTS = new HashMap<>() {{
put(Generate.Config.Keys.EMITTER, Generator.class.getName());
put(Keys.SCALE_FACTOR, "100");
put(Keys.SCHEMA_PARSER, YAMLSchemaParser.class.getName());
}};
}
private final Configuration config;
//Static variables
//...
//Final class variables
private final OutputIdDriver outputIdDriver;
private final Long scaleFactor; | /*
* @author Grant Haywood <grant.haywood@aerospike.com>
* Developed May 2023 - Oct 2023
* Copyright (c) 2023 Aerospike Inc.
*/
package com.aerospike.graph.synth.emitter.generator;
/**
* @author Grant Haywood (<a href="http://iowntheinter.net">http://iowntheinter.net</a>)
*/
public class Generator extends Loadable implements Emitter {
@Override
public void init(final Configuration config) {
}
// Configuration first.
public static class Config extends ConfigurationBase {
public static final Config INSTANCE = new Config();
private Config() {
super();
}
@Override
public Map<String, String> defaultConfigMap(final Map<String, Object> config) {
return DEFAULTS;
}
@Override
public List<String> getKeys() {
return ConfigurationUtil.getKeysFromClass(Config.Keys.class);
}
public static class Keys {
public static final String SCALE_FACTOR = "generator.scaleFactor";
public static final String CHANCE_TO_JOIN = "generator.chanceToJoin";
public static final String SCHEMA_PARSER = "generator.schemaGraphParser";
}
private static final Map<String, String> DEFAULTS = new HashMap<>() {{
put(Generate.Config.Keys.EMITTER, Generator.class.getName());
put(Keys.SCALE_FACTOR, "100");
put(Keys.SCHEMA_PARSER, YAMLSchemaParser.class.getName());
}};
}
private final Configuration config;
//Static variables
//...
//Final class variables
private final OutputIdDriver outputIdDriver;
private final Long scaleFactor; | private final Map<String, VertexSchema> rootVertexSchemas; | 2 | 2023-10-27 22:54:12+00:00 | 8k |
StarDevelopmentLLC/StarMCLib | src/main/java/com/stardevllc/starmclib/item/material/BookItemBuilder.java | [
{
"identifier": "ColorUtils",
"path": "src/main/java/com/stardevllc/starmclib/color/ColorUtils.java",
"snippet": "public final class ColorUtils {\n private static final char[] COLOR_SYMBOLS = {'&', '~', '`', '!', '@', '$', '%', '^', '*', '?'};\n public static final Pattern COLOR_CODE_PATTERN = Pat... | import com.cryptomorin.xseries.XMaterial;
import com.stardevllc.starmclib.color.ColorUtils;
import com.stardevllc.starmclib.item.ItemBuilder;
import net.md_5.bungee.api.chat.BaseComponent;
import net.md_5.bungee.api.chat.TextComponent;
import net.md_5.bungee.chat.ComponentSerializer;
import org.bukkit.Material;
import org.bukkit.attribute.Attribute;
import org.bukkit.attribute.AttributeModifier;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
import java.util.LinkedList;
import java.util.List; | 7,077 | package com.stardevllc.starmclib.item.material;
public class BookItemBuilder extends ItemBuilder {
private String author;
private List<BaseComponent[]> pages = new LinkedList<>();
private BookMeta.Generation generation = BookMeta.Generation.ORIGINAL;
private String title;
public BookItemBuilder(XMaterial material) {
super(material);
}
protected BookItemBuilder() {
}
protected static BookItemBuilder createFromItemStack(ItemStack itemStack) {
BookItemBuilder itemBuilder = new BookItemBuilder();
BookMeta itemMeta = (BookMeta) itemStack.getItemMeta();
itemBuilder.setPagesComponents(itemMeta.spigot().getPages()).author(itemMeta.getAuthor()).title(itemMeta.getTitle()).generation(itemMeta.getGeneration());
return itemBuilder;
}
protected static BookItemBuilder createFromConfig(ConfigurationSection section) {
BookItemBuilder builder = new BookItemBuilder();
builder.title(section.getString("title"));
builder.author(section.getString("author"));
builder.generation(BookMeta.Generation.valueOf(section.getString("generation")));
ConfigurationSection pagesSection = section.getConfigurationSection("pages");
if (pagesSection != null) {
for (String key : pagesSection.getKeys(false)) {
builder.addPage(ComponentSerializer.parse(pagesSection.getString(key)));
}
}
return builder;
}
@Override
public void saveToConfig(ConfigurationSection section) {
super.saveToConfig(section);
section.set("author", this.author);
section.set("title", this.title);
section.set("generation", this.generation.name());
for (int i = 0; i < pages.size(); i++) {
section.set("pages." + i, ComponentSerializer.toString(pages.get(i)));
}
}
public BookItemBuilder addPage(String page) { | package com.stardevllc.starmclib.item.material;
public class BookItemBuilder extends ItemBuilder {
private String author;
private List<BaseComponent[]> pages = new LinkedList<>();
private BookMeta.Generation generation = BookMeta.Generation.ORIGINAL;
private String title;
public BookItemBuilder(XMaterial material) {
super(material);
}
protected BookItemBuilder() {
}
protected static BookItemBuilder createFromItemStack(ItemStack itemStack) {
BookItemBuilder itemBuilder = new BookItemBuilder();
BookMeta itemMeta = (BookMeta) itemStack.getItemMeta();
itemBuilder.setPagesComponents(itemMeta.spigot().getPages()).author(itemMeta.getAuthor()).title(itemMeta.getTitle()).generation(itemMeta.getGeneration());
return itemBuilder;
}
protected static BookItemBuilder createFromConfig(ConfigurationSection section) {
BookItemBuilder builder = new BookItemBuilder();
builder.title(section.getString("title"));
builder.author(section.getString("author"));
builder.generation(BookMeta.Generation.valueOf(section.getString("generation")));
ConfigurationSection pagesSection = section.getConfigurationSection("pages");
if (pagesSection != null) {
for (String key : pagesSection.getKeys(false)) {
builder.addPage(ComponentSerializer.parse(pagesSection.getString(key)));
}
}
return builder;
}
@Override
public void saveToConfig(ConfigurationSection section) {
super.saveToConfig(section);
section.set("author", this.author);
section.set("title", this.title);
section.set("generation", this.generation.name());
for (int i = 0; i < pages.size(); i++) {
section.set("pages." + i, ComponentSerializer.toString(pages.get(i)));
}
}
public BookItemBuilder addPage(String page) { | this.pages.add(TextComponent.fromLegacyText(ColorUtils.color(page))); | 0 | 2023-10-31 12:53:19+00:00 | 8k |
Java-Game-Engine-Merger/Libgdx-Processing | framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/ui/TMUIPlugin.java | [
{
"identifier": "TMModelManager",
"path": "framework0003/framework0003-textmate/src/main/java/org/eclipse/tm4e/ui/internal/model/TMModelManager.java",
"snippet": "public final class TMModelManager implements ITMModelManager{\n public static final TMModelManager INSTANCE=new TMModelManager();\n private... | import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.Status;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.tm4e.ui.internal.model.TMModelManager;
import org.eclipse.tm4e.ui.internal.snippets.SnippetManager;
import org.eclipse.tm4e.ui.internal.themes.ThemeManager;
import org.eclipse.tm4e.ui.model.ITMModelManager;
import org.eclipse.tm4e.ui.snippets.ISnippetManager;
import org.eclipse.tm4e.ui.themes.ColorManager;
import org.eclipse.tm4e.ui.themes.IThemeManager;
import org.osgi.framework.BundleContext;
import pama1234.gdx.textmate.annotation.DeprecatedJface; | 3,715 | package org.eclipse.tm4e.ui;
// import org.eclipse.ui.plugin.AbstractUIPlugin;
// @Deprecated("别动这个")
@DeprecatedJface
public class TMUIPlugin{
// extends AbstractUIPlugin{
// The plug-in ID
public static final String PLUGIN_ID="org.eclipse.tm4e.ui"; //$NON-NLS-1$
private static final String TRACE_ID=PLUGIN_ID+"/trace"; //$NON-NLS-1$
// The shared instance
@Nullable
private static volatile TMUIPlugin plugin;
public static void log(final IStatus status) {
final var p=plugin;
if(p!=null) {
// p.getLog().log(status);
}else {
System.out.println(status);
}
}
public static void logError(final Exception ex) {
log(new Status(IStatus.ERROR,PLUGIN_ID,ex.getMessage(),ex));
}
public static void logTrace(final String message) {
if(isLogTraceEnabled()) {
log(new Status(IStatus.INFO,PLUGIN_ID,message));
}
}
public static boolean isLogTraceEnabled() {
return Boolean.parseBoolean(Platform.getDebugOption(TRACE_ID));
}
// @Override
public void start(@Nullable final BundleContext context) throws Exception {
// super.start(context);
plugin=this;
if(isLogTraceEnabled()) {
// if the trace option is enabled publish all TM4E CORE JDK logging output to the Eclipse Error Log
final var tm4eCorePluginId="org.eclipse.tm4e.core";
final var tm4eCoreLogger=Logger.getLogger(tm4eCorePluginId);
tm4eCoreLogger.setLevel(Level.FINEST);
tm4eCoreLogger.addHandler(new Handler() {
@Override
public void publish(@Nullable final LogRecord entry) {
if(entry!=null) {
log(new Status(toSeverity(entry.getLevel()),tm4eCorePluginId,
entry.getParameters()==null||entry.getParameters().length==0
?entry.getMessage()
:java.text.MessageFormat.format(entry.getMessage(),entry.getParameters())));
}
}
private int toSeverity(final Level level) {
if(level.intValue()>=Level.SEVERE.intValue()) {
return IStatus.ERROR;
}
if(level.intValue()>=Level.WARNING.intValue()) {
return IStatus.WARNING;
}
return IStatus.INFO;
}
@Override
public void flush() {
// nothing to do
}
@Override
public void close() throws SecurityException {
// nothing to do
}
});
}
}
// @Override
public void stop(@Nullable final BundleContext context) throws Exception {
ColorManager.getInstance().dispose();
plugin=null;
// super.stop(context);
}
@Nullable
public static TMUIPlugin getDefault() {
return plugin;
}
public static ITMModelManager getTMModelManager() {
return TMModelManager.INSTANCE;
}
public static IThemeManager getThemeManager() {
return ThemeManager.getInstance();
}
public static ISnippetManager getSnippetManager() { | package org.eclipse.tm4e.ui;
// import org.eclipse.ui.plugin.AbstractUIPlugin;
// @Deprecated("别动这个")
@DeprecatedJface
public class TMUIPlugin{
// extends AbstractUIPlugin{
// The plug-in ID
public static final String PLUGIN_ID="org.eclipse.tm4e.ui"; //$NON-NLS-1$
private static final String TRACE_ID=PLUGIN_ID+"/trace"; //$NON-NLS-1$
// The shared instance
@Nullable
private static volatile TMUIPlugin plugin;
public static void log(final IStatus status) {
final var p=plugin;
if(p!=null) {
// p.getLog().log(status);
}else {
System.out.println(status);
}
}
public static void logError(final Exception ex) {
log(new Status(IStatus.ERROR,PLUGIN_ID,ex.getMessage(),ex));
}
public static void logTrace(final String message) {
if(isLogTraceEnabled()) {
log(new Status(IStatus.INFO,PLUGIN_ID,message));
}
}
public static boolean isLogTraceEnabled() {
return Boolean.parseBoolean(Platform.getDebugOption(TRACE_ID));
}
// @Override
public void start(@Nullable final BundleContext context) throws Exception {
// super.start(context);
plugin=this;
if(isLogTraceEnabled()) {
// if the trace option is enabled publish all TM4E CORE JDK logging output to the Eclipse Error Log
final var tm4eCorePluginId="org.eclipse.tm4e.core";
final var tm4eCoreLogger=Logger.getLogger(tm4eCorePluginId);
tm4eCoreLogger.setLevel(Level.FINEST);
tm4eCoreLogger.addHandler(new Handler() {
@Override
public void publish(@Nullable final LogRecord entry) {
if(entry!=null) {
log(new Status(toSeverity(entry.getLevel()),tm4eCorePluginId,
entry.getParameters()==null||entry.getParameters().length==0
?entry.getMessage()
:java.text.MessageFormat.format(entry.getMessage(),entry.getParameters())));
}
}
private int toSeverity(final Level level) {
if(level.intValue()>=Level.SEVERE.intValue()) {
return IStatus.ERROR;
}
if(level.intValue()>=Level.WARNING.intValue()) {
return IStatus.WARNING;
}
return IStatus.INFO;
}
@Override
public void flush() {
// nothing to do
}
@Override
public void close() throws SecurityException {
// nothing to do
}
});
}
}
// @Override
public void stop(@Nullable final BundleContext context) throws Exception {
ColorManager.getInstance().dispose();
plugin=null;
// super.stop(context);
}
@Nullable
public static TMUIPlugin getDefault() {
return plugin;
}
public static ITMModelManager getTMModelManager() {
return TMModelManager.INSTANCE;
}
public static IThemeManager getThemeManager() {
return ThemeManager.getInstance();
}
public static ISnippetManager getSnippetManager() { | return SnippetManager.getInstance(); | 1 | 2023-10-27 05:47:39+00:00 | 8k |
llllllxy/tinycloud | tinycloud-common/src/main/java/org/tinycloud/common/aspect/LimitAspect.java | [
{
"identifier": "LimitType",
"path": "tinycloud-common/src/main/java/org/tinycloud/common/consts/LimitType.java",
"snippet": "public enum LimitType {\n /**\n * 默认策略全局限流\n */\n DEFAULT,\n\n /**\n * 根据请求者IP进行限流\n */\n IP\n}"
},
{
"identifier": "IpUtils",
"path": "ti... | import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.tinycloud.common.annotation.Limit;
import org.tinycloud.common.consts.LimitType;
import org.tinycloud.common.utils.IpUtils;
import org.tinycloud.common.utils.web.ServletUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List; | 4,542 | package org.tinycloud.common.aspect;
/**
* 接口限流处理切面处理类
*
* @author liuxingyu01
* @since 2022-03-13-13:47
**/
@Aspect
@Component
public class LimitAspect {
final static Logger log = LoggerFactory.getLogger(LimitAspect.class);
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 前置通知,判断是否超出限流次数
*
* @param point
*/
@Before("@annotation(limit)")
public void doBefore(JoinPoint point, Limit limit) {
try {
// 拼接key
String key = getCombineKey(limit, point);
// 判断是否超出限流次数
if (!redisLimit(key, limit.count(), limit.time())) {
throw new RuntimeException("访问过于频繁,请稍候再试");
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("接口限流异常,请稍候再试");
}
}
/**
* 根据限流类型拼接key
*/
public String getCombineKey(Limit limit, JoinPoint point) {
StringBuilder sb = new StringBuilder(limit.prefix() + ":");
// 按照IP限流
if (limit.type() == LimitType.IP) { | package org.tinycloud.common.aspect;
/**
* 接口限流处理切面处理类
*
* @author liuxingyu01
* @since 2022-03-13-13:47
**/
@Aspect
@Component
public class LimitAspect {
final static Logger log = LoggerFactory.getLogger(LimitAspect.class);
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 前置通知,判断是否超出限流次数
*
* @param point
*/
@Before("@annotation(limit)")
public void doBefore(JoinPoint point, Limit limit) {
try {
// 拼接key
String key = getCombineKey(limit, point);
// 判断是否超出限流次数
if (!redisLimit(key, limit.count(), limit.time())) {
throw new RuntimeException("访问过于频繁,请稍候再试");
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("接口限流异常,请稍候再试");
}
}
/**
* 根据限流类型拼接key
*/
public String getCombineKey(Limit limit, JoinPoint point) {
StringBuilder sb = new StringBuilder(limit.prefix() + ":");
// 按照IP限流
if (limit.type() == LimitType.IP) { | sb.append(IpUtils.getIpAddr(ServletUtils.getRequest())).append(":"); | 2 | 2023-10-28 02:05:15+00:00 | 8k |
Daudeuf/GLauncher | src/main/java/fr/glauncher/ui/Launcher.java | [
{
"identifier": "Controller",
"path": "src/main/java/fr/glauncher/Controller.java",
"snippet": "public class Controller\n{\n\tpublic static final PackInfos pack;\n\n\tstatic {\n\t\ttry {\n\t\t\tpack = PackInfos.create(\"https://raw.githubusercontent.com/Daudeuf/GLauncher/master/modpack_info.json\");\n\t... | import fr.glauncher.Controller;
import fr.glauncher.ui.panels.Launch;
import fr.glauncher.ui.panels.Login;
import javax.swing.*;
import java.awt.*; | 3,726 | package fr.glauncher.ui;
public class Launcher extends JFrame
{
private final JPanel panelSwitch;
private final JPanel panelLaunch;
private final JPanel panelLogin;
private final CardLayout crdLyt;
public Launcher(Controller ctrl)
{
Image icon = getToolkit().getImage( getClass().getResource("/icon.png") );
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = ((int) screenSize.getWidth() - 1024) / 2;
int y = ((int) screenSize.getHeight() - 512) / 2;
this.setLocation(x, y);
this.setSize(1024, 512);
this.setTitle("G Launcher");
this.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
this.setResizable( false );
this.setIconImage( icon );
this.crdLyt = new CardLayout();
this.panelSwitch = new JPanel ( this.crdLyt ); | package fr.glauncher.ui;
public class Launcher extends JFrame
{
private final JPanel panelSwitch;
private final JPanel panelLaunch;
private final JPanel panelLogin;
private final CardLayout crdLyt;
public Launcher(Controller ctrl)
{
Image icon = getToolkit().getImage( getClass().getResource("/icon.png") );
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = ((int) screenSize.getWidth() - 1024) / 2;
int y = ((int) screenSize.getHeight() - 512) / 2;
this.setLocation(x, y);
this.setSize(1024, 512);
this.setTitle("G Launcher");
this.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
this.setResizable( false );
this.setIconImage( icon );
this.crdLyt = new CardLayout();
this.panelSwitch = new JPanel ( this.crdLyt ); | this.panelLaunch = new Launch (ctrl); | 1 | 2023-10-28 15:35:30+00:00 | 8k |
oehf/xds-registry-to-fhir | src/main/java/org/openehealth/app/xdstofhir/registry/query/StoredQueryVistorImpl.java | [
{
"identifier": "URI_URN",
"path": "src/main/java/org/openehealth/app/xdstofhir/registry/common/MappingSupport.java",
"snippet": "public static final String URI_URN = \"urn:ietf:rfc:3986\";"
},
{
"identifier": "assignDefaultVersioning",
"path": "src/main/java/org/openehealth/app/xdstofhir/re... | import static org.openehealth.app.xdstofhir.registry.common.MappingSupport.URI_URN;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.assignDefaultVersioning;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.buildIdentifierQuery;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.entryUuidFrom;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.map;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.mapPatientIdToQuery;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.mapStatus;
import static org.openehealth.app.xdstofhir.registry.query.StoredQueryMapper.urnIdentifierList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.StreamSupport;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.gclient.IQuery;
import ca.uhn.fhir.rest.gclient.TokenClientParam;
import ca.uhn.fhir.util.BundleUtil;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.hl7.fhir.instance.model.api.IBaseBundle;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.DocumentReference;
import org.hl7.fhir.r4.model.DomainResource;
import org.hl7.fhir.r4.model.ListResource;
import org.openehealth.app.xdstofhir.registry.common.MappingSupport;
import org.openehealth.app.xdstofhir.registry.common.fhir.MhdFolder;
import org.openehealth.app.xdstofhir.registry.common.fhir.MhdSubmissionSet;
import org.openehealth.ipf.commons.core.URN;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.Association;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.AssociationLabel;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.AssociationType;
import org.openehealth.ipf.commons.ihe.xds.core.metadata.ObjectReference;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsByReferenceIdQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindDocumentsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindFoldersQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.FindSubmissionSetsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetAllQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetAssociationsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetDocumentsAndAssociationsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetDocumentsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetFolderAndContentsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetFoldersForDocumentQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetFoldersQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetRelatedDocumentsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetSubmissionSetAndContentsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.requests.query.GetSubmissionSetsQuery;
import org.openehealth.ipf.commons.ihe.xds.core.responses.ErrorCode;
import org.openehealth.ipf.commons.ihe.xds.core.responses.ErrorInfo;
import org.openehealth.ipf.commons.ihe.xds.core.responses.QueryResponse;
import org.openehealth.ipf.commons.ihe.xds.core.responses.Severity;
import org.openehealth.ipf.commons.ihe.xds.core.responses.Status; | 3,691 | package org.openehealth.app.xdstofhir.registry.query;
/**
* Implement ITI-18 queries using IPF visitor pattern.
*
* The XDS queries will be mapped to a FHIR query.
*
*
*/
@RequiredArgsConstructor
public class StoredQueryVistorImpl extends AbstractStoredQueryVisitor {
/*
* Hapi currently ignore "_list" parameter, workaround here with "_has" reverse chain search
* https://github.com/hapifhir/hapi-fhir/issues/3761
*/
private static final String HAS_LIST_ITEM_IDENTIFIER = "_has:List:item:identifier";
private final IGenericClient client;
private final StoredQueryProcessor queryProcessor;
private final boolean isObjectRefResult;
@Getter
private final QueryResponse response = new QueryResponse(Status.SUCCESS);
@Override
public void visit(FindDocumentsQuery query) {
IQuery<Bundle> documentFhirQuery = prepareQuery(query);
mapDocuments(buildResultForDocuments(documentFhirQuery));
}
@Override
public void visit(GetDocumentsQuery query) {
var documentFhirQuery = initDocumentQuery();
var identifier = buildIdentifierQuery(query, DocumentReference.IDENTIFIER);
documentFhirQuery.where(identifier);
mapDocuments(buildResultForDocuments(documentFhirQuery));
}
@Override
public void visit(FindFoldersQuery query) {
var folderFhirQuery = initFolderQuery();
mapPatientIdToQuery(query, folderFhirQuery); | package org.openehealth.app.xdstofhir.registry.query;
/**
* Implement ITI-18 queries using IPF visitor pattern.
*
* The XDS queries will be mapped to a FHIR query.
*
*
*/
@RequiredArgsConstructor
public class StoredQueryVistorImpl extends AbstractStoredQueryVisitor {
/*
* Hapi currently ignore "_list" parameter, workaround here with "_has" reverse chain search
* https://github.com/hapifhir/hapi-fhir/issues/3761
*/
private static final String HAS_LIST_ITEM_IDENTIFIER = "_has:List:item:identifier";
private final IGenericClient client;
private final StoredQueryProcessor queryProcessor;
private final boolean isObjectRefResult;
@Getter
private final QueryResponse response = new QueryResponse(Status.SUCCESS);
@Override
public void visit(FindDocumentsQuery query) {
IQuery<Bundle> documentFhirQuery = prepareQuery(query);
mapDocuments(buildResultForDocuments(documentFhirQuery));
}
@Override
public void visit(GetDocumentsQuery query) {
var documentFhirQuery = initDocumentQuery();
var identifier = buildIdentifierQuery(query, DocumentReference.IDENTIFIER);
documentFhirQuery.where(identifier);
mapDocuments(buildResultForDocuments(documentFhirQuery));
}
@Override
public void visit(FindFoldersQuery query) {
var folderFhirQuery = initFolderQuery();
mapPatientIdToQuery(query, folderFhirQuery); | map(query.getLastUpdateTime(), ListResource.DATE, folderFhirQuery); | 4 | 2023-10-30 18:58:31+00:00 | 8k |
danielbatres/orthodontic-dentistry-clinical-management | src/com/view/createAsistente/NewAsistenteInformation.java | [
{
"identifier": "ChoosedPalette",
"path": "src/com/context/ChoosedPalette.java",
"snippet": "public class ChoosedPalette {\r\n private static final Palette DARK_PALETTE = new Palette(Color.decode(\"#0B0D16\"),\r\n Color.decode(\"#FFFFFF\"),\r\n Color.decode(\"#4562FF\"),\r\n Colo... | import com.context.ChoosedPalette;
import com.k33ptoo.components.KGradientPanel;
import com.model.AsistenteModel;
import com.utils.Tools;
import com.view.createPacient.NewContext;
import java.time.LocalDateTime;
import java.util.ArrayList;
import javax.swing.JTextField; | 6,462 | package com.view.createAsistente;
/**
*
* @author Daniel Batres
* @version 1.0.0
* @since 23/09/22
*/
public class NewAsistenteInformation extends NewContext {
ArrayList<JTextField> deleteIngresa = new ArrayList<>();
ArrayList<JTextField> deleteDate = new ArrayList<>();
ArrayList<JTextField> dayAndMonth = new ArrayList<>();
ArrayList<KGradientPanel> contenedoresFechaNacimiento = new ArrayList<>();
ArrayList<JTextField> camposFechaNacimiento = new ArrayList<>();
/**
* Creates new form NewAsistenteInformation
*/
public NewAsistenteInformation() {
initComponents();
styleMyComponentBaby();
}
public AsistenteModel devolverDatos() {
AsistenteModel asistente = new AsistenteModel();
asistente.setEstadoActividad("activo");
asistente.setEspecialidad("asistente");
asistente.setEdad(Integer.parseInt(textField6.getText()));
asistente.setDiaNacimiento(Integer.parseInt(textField2.getText()));
asistente.setMesNacimiento(Integer.parseInt(textField3.getText()));
asistente.setAnnioNacimiento(Integer.parseInt(textField4.getText()));
asistente.setNombres(emptyMessage(textField1.getText()));
asistente.setApellidos(emptyMessage(textField5.getText()));
asistente.setGenero(generoCombo.getSelectedItem().toString());
asistente.setTelefonoCelular(emptyMessage(textField9.getText()));
asistente.setTelefonoCasa(emptyMessage(textField10.getText()));
asistente.setDireccion(emptyMessage(textField11.getText()));
asistente.setDepartamento(comboDepartamento.getSelectedItem().toString());
asistente.setMunicipio(emptyMessage(textField12.getText()));
asistente.setDiaCreacion(LocalDateTime.now().getDayOfMonth());
asistente.setMesCreacion(LocalDateTime.now().getMonthValue());
asistente.setAnnioCreacion(LocalDateTime.now().getYear());
asistente.setCorreoElectronico(textField7.getText());
asistente.setContrasena(textField8.getText());
asistente.setHoraCreacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter));
asistente.setDiaModificacion(LocalDateTime.now().getDayOfMonth());
asistente.setMesModificacion(LocalDateTime.now().getMonthValue());
asistente.setAnnioModificacion(LocalDateTime.now().getYear());
asistente.setHoraModificacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter));
asistente.setPaletaPreferencia("light");
return asistente;
}
@Override
public void addTitlesAndSubtitles() {
TITLES_AND_SUBTITLES.add(title1);
TITLES_AND_SUBTITLES.add(title2);
TITLES_AND_SUBTITLES.add(title3);
TITLES_AND_SUBTITLES.add(title4);
TITLES_AND_SUBTITLES.add(title5);
TITLES_AND_SUBTITLES.add(title6);
TITLES_AND_SUBTITLES.add(title7);
TITLES_AND_SUBTITLES.add(title9);
TITLES_AND_SUBTITLES.add(title10);
TITLES_AND_SUBTITLES.add(title11);
TITLES_AND_SUBTITLES.add(title12);
TITLES_AND_SUBTITLES.add(title13);
TITLES_AND_SUBTITLES.add(title14);
TITLES_AND_SUBTITLES.add(title15);
}
@Override
public void addPlainText() {
PLAIN_TEXT.add(text1);
}
@Override
public void addContainers() {
CONTAINERS.add(container1);
CONTAINERS.add(container2);
CONTAINERS.add(container4);
CONTAINERS.add(container5);
CONTAINERS.add(container6);
CONTAINERS.add(container7);
CONTAINERS.add(container8);
CONTAINERS.add(container9);
CONTAINERS.add(container10);
CONTAINERS.add(container11);
CONTAINERS.add(container12);
CONTAINERS.add(container13);
}
@Override
public void addTextFields() {
TEXTFIELDS.add(textField1);
TEXTFIELDS.add(textField2);
TEXTFIELDS.add(textField3);
TEXTFIELDS.add(textField4);
TEXTFIELDS.add(textField5);
TEXTFIELDS.add(textField6);
TEXTFIELDS.add(textField7);
TEXTFIELDS.add(textField8);
TEXTFIELDS.add(textField9);
TEXTFIELDS.add(textField10);
TEXTFIELDS.add(textField11);
TEXTFIELDS.add(textField12);
}
@Override
public void initStyles() {
styles();
camposFechaNacimiento.add(textField2);
camposFechaNacimiento.add(textField3);
camposFechaNacimiento.add(textField4);
contenedoresFechaNacimiento.add(container2);
contenedoresFechaNacimiento.add(container4);
contenedoresFechaNacimiento.add(container5);
camposTexto.add(textField1);
camposTexto.add(textField5);
camposTexto.add(textField7);
camposTexto.add(textField8);
containersTexto.add(container1);
containersTexto.add(container7);
containersTexto.add(container9);
containersTexto.add(container6);
advertenciasTexto.add(advertenciaNombre);
advertenciasTexto.add(advertenciaApellidos);
advertenciasTexto.add(advertenciaCorreo);
advertenciasTexto.add(advertenciaContrasena);
addItemsDepartamento();
}
private void styles() {
informationIcon.setSize(50, 50);
direccionIcon.setSize(50, 50); | package com.view.createAsistente;
/**
*
* @author Daniel Batres
* @version 1.0.0
* @since 23/09/22
*/
public class NewAsistenteInformation extends NewContext {
ArrayList<JTextField> deleteIngresa = new ArrayList<>();
ArrayList<JTextField> deleteDate = new ArrayList<>();
ArrayList<JTextField> dayAndMonth = new ArrayList<>();
ArrayList<KGradientPanel> contenedoresFechaNacimiento = new ArrayList<>();
ArrayList<JTextField> camposFechaNacimiento = new ArrayList<>();
/**
* Creates new form NewAsistenteInformation
*/
public NewAsistenteInformation() {
initComponents();
styleMyComponentBaby();
}
public AsistenteModel devolverDatos() {
AsistenteModel asistente = new AsistenteModel();
asistente.setEstadoActividad("activo");
asistente.setEspecialidad("asistente");
asistente.setEdad(Integer.parseInt(textField6.getText()));
asistente.setDiaNacimiento(Integer.parseInt(textField2.getText()));
asistente.setMesNacimiento(Integer.parseInt(textField3.getText()));
asistente.setAnnioNacimiento(Integer.parseInt(textField4.getText()));
asistente.setNombres(emptyMessage(textField1.getText()));
asistente.setApellidos(emptyMessage(textField5.getText()));
asistente.setGenero(generoCombo.getSelectedItem().toString());
asistente.setTelefonoCelular(emptyMessage(textField9.getText()));
asistente.setTelefonoCasa(emptyMessage(textField10.getText()));
asistente.setDireccion(emptyMessage(textField11.getText()));
asistente.setDepartamento(comboDepartamento.getSelectedItem().toString());
asistente.setMunicipio(emptyMessage(textField12.getText()));
asistente.setDiaCreacion(LocalDateTime.now().getDayOfMonth());
asistente.setMesCreacion(LocalDateTime.now().getMonthValue());
asistente.setAnnioCreacion(LocalDateTime.now().getYear());
asistente.setCorreoElectronico(textField7.getText());
asistente.setContrasena(textField8.getText());
asistente.setHoraCreacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter));
asistente.setDiaModificacion(LocalDateTime.now().getDayOfMonth());
asistente.setMesModificacion(LocalDateTime.now().getMonthValue());
asistente.setAnnioModificacion(LocalDateTime.now().getYear());
asistente.setHoraModificacion(String.valueOf(LocalDateTime.now().getHour()) + ":" + String.valueOf(LocalDateTime.now().getMinute()) + " " + NewContext.localTime.format(dateTimeFormatter));
asistente.setPaletaPreferencia("light");
return asistente;
}
@Override
public void addTitlesAndSubtitles() {
TITLES_AND_SUBTITLES.add(title1);
TITLES_AND_SUBTITLES.add(title2);
TITLES_AND_SUBTITLES.add(title3);
TITLES_AND_SUBTITLES.add(title4);
TITLES_AND_SUBTITLES.add(title5);
TITLES_AND_SUBTITLES.add(title6);
TITLES_AND_SUBTITLES.add(title7);
TITLES_AND_SUBTITLES.add(title9);
TITLES_AND_SUBTITLES.add(title10);
TITLES_AND_SUBTITLES.add(title11);
TITLES_AND_SUBTITLES.add(title12);
TITLES_AND_SUBTITLES.add(title13);
TITLES_AND_SUBTITLES.add(title14);
TITLES_AND_SUBTITLES.add(title15);
}
@Override
public void addPlainText() {
PLAIN_TEXT.add(text1);
}
@Override
public void addContainers() {
CONTAINERS.add(container1);
CONTAINERS.add(container2);
CONTAINERS.add(container4);
CONTAINERS.add(container5);
CONTAINERS.add(container6);
CONTAINERS.add(container7);
CONTAINERS.add(container8);
CONTAINERS.add(container9);
CONTAINERS.add(container10);
CONTAINERS.add(container11);
CONTAINERS.add(container12);
CONTAINERS.add(container13);
}
@Override
public void addTextFields() {
TEXTFIELDS.add(textField1);
TEXTFIELDS.add(textField2);
TEXTFIELDS.add(textField3);
TEXTFIELDS.add(textField4);
TEXTFIELDS.add(textField5);
TEXTFIELDS.add(textField6);
TEXTFIELDS.add(textField7);
TEXTFIELDS.add(textField8);
TEXTFIELDS.add(textField9);
TEXTFIELDS.add(textField10);
TEXTFIELDS.add(textField11);
TEXTFIELDS.add(textField12);
}
@Override
public void initStyles() {
styles();
camposFechaNacimiento.add(textField2);
camposFechaNacimiento.add(textField3);
camposFechaNacimiento.add(textField4);
contenedoresFechaNacimiento.add(container2);
contenedoresFechaNacimiento.add(container4);
contenedoresFechaNacimiento.add(container5);
camposTexto.add(textField1);
camposTexto.add(textField5);
camposTexto.add(textField7);
camposTexto.add(textField8);
containersTexto.add(container1);
containersTexto.add(container7);
containersTexto.add(container9);
containersTexto.add(container6);
advertenciasTexto.add(advertenciaNombre);
advertenciasTexto.add(advertenciaApellidos);
advertenciasTexto.add(advertenciaCorreo);
advertenciasTexto.add(advertenciaContrasena);
addItemsDepartamento();
}
private void styles() {
informationIcon.setSize(50, 50);
direccionIcon.setSize(50, 50); | Tools.setImageLabel(informationIcon, "src/com/assets/usuario.png", 30, 30, ChoosedPalette.getWhite()); | 2 | 2023-10-26 19:35:40+00:00 | 8k |
ddoubest/mini-spring | src/com/minis/web/AnnotationConfigWebApplicationContext.java | [
{
"identifier": "ConfigurableListableBeanFactory",
"path": "src/com/minis/beans/factory/ConfigurableListableBeanFactory.java",
"snippet": "public interface ConfigurableListableBeanFactory extends ConfigurableBeanFactory, ListableBeanFactory, AutowireCapableBeanFactory {\n}"
},
{
"identifier": "F... | import com.minis.beans.factory.ConfigurableListableBeanFactory;
import com.minis.beans.factory.FactoryAwareBeanPostProcessor;
import com.minis.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import com.minis.beans.factory.support.DefaultListableBeanFactory;
import com.minis.context.AbstractApplicationContext;
import com.minis.event.ApplicationListener;
import com.minis.event.ContextRefreshEvent;
import com.minis.event.SimpleApplicationEventPublisher;
import com.minis.exceptions.BeansException;
import com.minis.utils.ScanComponentHelper;
import javax.servlet.ServletContext;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List; | 3,779 | package com.minis.web;
public class AnnotationConfigWebApplicationContext extends AbstractApplicationContext implements WebApplicationContext {
private final DefaultListableBeanFactory beanFactory;
private ServletContext servletContext;
private WebApplicationContext parentWebApplicationContext;
public AnnotationConfigWebApplicationContext(String fileName) {
this(fileName, null);
}
public AnnotationConfigWebApplicationContext(String fileName, WebApplicationContext parentWebApplicationContext) {
this.parentWebApplicationContext = parentWebApplicationContext;
this.servletContext = parentWebApplicationContext.getServletContext();
this.beanFactory = new DefaultListableBeanFactory();
this.beanFactory.setParentBeanFactory(this.parentWebApplicationContext.getBeanFactory());
URL xmlPath;
try {
xmlPath = getServletContext().getResource(fileName);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
List<String> packageNames = XmlScanComponentHelper.getNodeValue(xmlPath);
List<String> controllerNames = ScanComponentHelper.scanPackages(packageNames);
ScanComponentHelper.loadBeanDefinitions(beanFactory, controllerNames);
refresh();
}
@Override
public Object getBean(String beanName) throws BeansException {
Object result = super.getBean(beanName);
if (result == null) {
result = parentWebApplicationContext.getBean(beanName);
}
return result;
}
public WebApplicationContext getParentWebApplicationContext() {
return parentWebApplicationContext;
}
public void setParentWebApplicationContext(WebApplicationContext parentWebApplicationContext) {
this.parentWebApplicationContext = parentWebApplicationContext;
this.beanFactory.setParentBeanFactory(this.parentWebApplicationContext.getBeanFactory());
}
@Override
public ServletContext getServletContext() {
return this.servletContext;
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
@Override
public WebApplicationContext getParent() {
return parentWebApplicationContext;
}
@Override
public ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException {
return beanFactory;
}
@Override
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { | package com.minis.web;
public class AnnotationConfigWebApplicationContext extends AbstractApplicationContext implements WebApplicationContext {
private final DefaultListableBeanFactory beanFactory;
private ServletContext servletContext;
private WebApplicationContext parentWebApplicationContext;
public AnnotationConfigWebApplicationContext(String fileName) {
this(fileName, null);
}
public AnnotationConfigWebApplicationContext(String fileName, WebApplicationContext parentWebApplicationContext) {
this.parentWebApplicationContext = parentWebApplicationContext;
this.servletContext = parentWebApplicationContext.getServletContext();
this.beanFactory = new DefaultListableBeanFactory();
this.beanFactory.setParentBeanFactory(this.parentWebApplicationContext.getBeanFactory());
URL xmlPath;
try {
xmlPath = getServletContext().getResource(fileName);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
List<String> packageNames = XmlScanComponentHelper.getNodeValue(xmlPath);
List<String> controllerNames = ScanComponentHelper.scanPackages(packageNames);
ScanComponentHelper.loadBeanDefinitions(beanFactory, controllerNames);
refresh();
}
@Override
public Object getBean(String beanName) throws BeansException {
Object result = super.getBean(beanName);
if (result == null) {
result = parentWebApplicationContext.getBean(beanName);
}
return result;
}
public WebApplicationContext getParentWebApplicationContext() {
return parentWebApplicationContext;
}
public void setParentWebApplicationContext(WebApplicationContext parentWebApplicationContext) {
this.parentWebApplicationContext = parentWebApplicationContext;
this.beanFactory.setParentBeanFactory(this.parentWebApplicationContext.getBeanFactory());
}
@Override
public ServletContext getServletContext() {
return this.servletContext;
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
@Override
public WebApplicationContext getParent() {
return parentWebApplicationContext;
}
@Override
public ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException {
return beanFactory;
}
@Override
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { | beanFactory.addBeanPostProcessor(new AutowiredAnnotationBeanPostProcessor(this)); | 2 | 2023-10-30 12:36:32+00:00 | 8k |
xingduansuzhao-MC/ModTest | src/main/java/com/xdsz/test/util/RegistryHandler.java | [
{
"identifier": "Test",
"path": "src/main/java/com/xdsz/test/Test.java",
"snippet": "@Mod(\"test\")\npublic class Test\n{\n // Directly reference a log4j logger.\n public static final Logger LOGGER = LogManager.getLogger();//p15的private改为public,控制台能查看调试\n public static final String MOD_ID = \"t... | import com.xdsz.test.Test;
import com.xdsz.test.armor.ModArmorMaterial;
import com.xdsz.test.blocks.BlockItemBase;
import com.xdsz.test.blocks.SapphireOre;
import com.xdsz.test.entities.TestBearEntity;
import com.xdsz.test.fluids.TestFluids;
import com.xdsz.test.items.ItemBase;
import com.xdsz.test.items.PoisonApple;
import com.xdsz.test.blocks.SapphireBlock;
import com.xdsz.test.items.TestSpawnEgg;
import com.xdsz.test.tools.ModItemTier;
import net.minecraft.block.Block;
import net.minecraft.entity.EntityClassification;
import net.minecraft.entity.EntityType;
import net.minecraft.fluid.Fluid;
import net.minecraft.inventory.EquipmentSlotType;
import net.minecraft.item.*;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries; | 4,179 | package com.xdsz.test.util;
public class RegistryHandler {
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Test.MOD_ID);
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, Test.MOD_ID);
public static final DeferredRegister<Fluid> FLUIDS = DeferredRegister.create(ForgeRegistries.FLUIDS, Test.MOD_ID);
public static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, Test.MOD_ID);
public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITIES, Test.MOD_ID);
public static void init(){
ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus());
TestFluids.register(FMLJavaModLoadingContext.get().getModEventBus());
SOUND_EVENTS.register(FMLJavaModLoadingContext.get().getModEventBus());
ENTITY_TYPES.register(FMLJavaModLoadingContext.get().getModEventBus());
}
//物品
public static final RegistryObject<Item> SAPPHIRE = ITEMS.register("sapphire",ItemBase::new);
//方块(手持)
public static final RegistryObject<Block> SAPPHIRE_BLOCK = BLOCKS.register("sapphire_block",SapphireBlock::new);
public static final RegistryObject<Block> SAPPHIRE_ORE = BLOCKS.register("sapphire_ore", SapphireOre::new);
//方块(着地)
public static final RegistryObject<Item> SAPPHIRE_BLOCK_ITEM = ITEMS.register("sapphire_block",
() -> new BlockItemBase(SAPPHIRE_BLOCK.get()));
public static final RegistryObject<Item> SAPPHIRE_ORE_ITEM = ITEMS.register("sapphire_ore",
() -> new BlockItemBase(SAPPHIRE_ORE.get()));
//工具
public static final RegistryObject<SwordItem> SAPPHIRE_SWORD = ITEMS.register("sapphire_sword",
() -> new SwordItem(ModItemTier.SAPPHIRE, 50, 20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<AxeItem> SAPPHIRE_AXE = ITEMS.register("sapphire_axe",
() -> new AxeItem(ModItemTier.SAPPHIRE, 100,20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ShovelItem> SAPPHIRE_SHOVEL = ITEMS.register("sapphire_shovel",
() -> new ShovelItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<HoeItem> SAPPHIRE_HOE = ITEMS.register("sapphire_hoe",
() -> new HoeItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<PickaxeItem> SAPPHIRE_PICKAXE = ITEMS.register("sapphire_pickaxe",
() -> new PickaxeItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));
//盔甲
public static final RegistryObject<ArmorItem> SAPPHIRE_HELMET = ITEMS.register("sapphire_helmet",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.HEAD, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ArmorItem> SAPPHIRE_CHESTPLATE = ITEMS.register("sapphire_chestplate",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.CHEST, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ArmorItem> SAPPHIRE_LEGS = ITEMS.register("sapphire_leggings",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.LEGS, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ArmorItem> SAPPHIRE_BOOTS = ITEMS.register("sapphire_boots",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.FEET, new Item.Properties().group(Test.TAB)));
//毒苹果
public static final RegistryObject<PoisonApple> POISON_APPLE = ITEMS.register("poison_apple", PoisonApple::new);
//流体(桶)
public static final RegistryObject<Item> HONEYTEST_BUCKET = ITEMS.register("honeytest_bucket",
()->new BucketItem(()->TestFluids.HONEYTEST_FLUID.get(), new Item.Properties().maxStackSize(1).group(Test.TAB)));
//音乐
public static final RegistryObject<SoundEvent> CAI_XUKUN = SOUND_EVENTS.register("cai_xukun",
()->new SoundEvent(new ResourceLocation(Test.MOD_ID, "cai_xukun")));
public static final RegistryObject<Item> KUN_DISC = ITEMS.register("kun_disc",
()->new MusicDiscItem(1, () -> CAI_XUKUN.get(), new Item.Properties().maxStackSize(16).group(Test.TAB)));
//实体 | package com.xdsz.test.util;
public class RegistryHandler {
public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Test.MOD_ID);
public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, Test.MOD_ID);
public static final DeferredRegister<Fluid> FLUIDS = DeferredRegister.create(ForgeRegistries.FLUIDS, Test.MOD_ID);
public static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, Test.MOD_ID);
public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITIES, Test.MOD_ID);
public static void init(){
ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());
BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus());
TestFluids.register(FMLJavaModLoadingContext.get().getModEventBus());
SOUND_EVENTS.register(FMLJavaModLoadingContext.get().getModEventBus());
ENTITY_TYPES.register(FMLJavaModLoadingContext.get().getModEventBus());
}
//物品
public static final RegistryObject<Item> SAPPHIRE = ITEMS.register("sapphire",ItemBase::new);
//方块(手持)
public static final RegistryObject<Block> SAPPHIRE_BLOCK = BLOCKS.register("sapphire_block",SapphireBlock::new);
public static final RegistryObject<Block> SAPPHIRE_ORE = BLOCKS.register("sapphire_ore", SapphireOre::new);
//方块(着地)
public static final RegistryObject<Item> SAPPHIRE_BLOCK_ITEM = ITEMS.register("sapphire_block",
() -> new BlockItemBase(SAPPHIRE_BLOCK.get()));
public static final RegistryObject<Item> SAPPHIRE_ORE_ITEM = ITEMS.register("sapphire_ore",
() -> new BlockItemBase(SAPPHIRE_ORE.get()));
//工具
public static final RegistryObject<SwordItem> SAPPHIRE_SWORD = ITEMS.register("sapphire_sword",
() -> new SwordItem(ModItemTier.SAPPHIRE, 50, 20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<AxeItem> SAPPHIRE_AXE = ITEMS.register("sapphire_axe",
() -> new AxeItem(ModItemTier.SAPPHIRE, 100,20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ShovelItem> SAPPHIRE_SHOVEL = ITEMS.register("sapphire_shovel",
() -> new ShovelItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<HoeItem> SAPPHIRE_HOE = ITEMS.register("sapphire_hoe",
() -> new HoeItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<PickaxeItem> SAPPHIRE_PICKAXE = ITEMS.register("sapphire_pickaxe",
() -> new PickaxeItem(ModItemTier.SAPPHIRE, 0, 20.0F, new Item.Properties().group(Test.TAB)));
//盔甲
public static final RegistryObject<ArmorItem> SAPPHIRE_HELMET = ITEMS.register("sapphire_helmet",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.HEAD, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ArmorItem> SAPPHIRE_CHESTPLATE = ITEMS.register("sapphire_chestplate",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.CHEST, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ArmorItem> SAPPHIRE_LEGS = ITEMS.register("sapphire_leggings",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.LEGS, new Item.Properties().group(Test.TAB)));
public static final RegistryObject<ArmorItem> SAPPHIRE_BOOTS = ITEMS.register("sapphire_boots",
() -> new ArmorItem(ModArmorMaterial.SAPPHIRE, EquipmentSlotType.FEET, new Item.Properties().group(Test.TAB)));
//毒苹果
public static final RegistryObject<PoisonApple> POISON_APPLE = ITEMS.register("poison_apple", PoisonApple::new);
//流体(桶)
public static final RegistryObject<Item> HONEYTEST_BUCKET = ITEMS.register("honeytest_bucket",
()->new BucketItem(()->TestFluids.HONEYTEST_FLUID.get(), new Item.Properties().maxStackSize(1).group(Test.TAB)));
//音乐
public static final RegistryObject<SoundEvent> CAI_XUKUN = SOUND_EVENTS.register("cai_xukun",
()->new SoundEvent(new ResourceLocation(Test.MOD_ID, "cai_xukun")));
public static final RegistryObject<Item> KUN_DISC = ITEMS.register("kun_disc",
()->new MusicDiscItem(1, () -> CAI_XUKUN.get(), new Item.Properties().maxStackSize(16).group(Test.TAB)));
//实体 | public static final RegistryObject<EntityType<TestBearEntity>> TEST_BEAR = ENTITY_TYPES.register("test_bear", | 4 | 2023-10-28 05:14:07+00:00 | 8k |
SUFIAG/Weather-Application-Android | app/src/main/java/com/aniketjain/weatherapp/HomeActivity.java | [
{
"identifier": "getCityNameUsingNetwork",
"path": "app/src/main/java/com/aniketjain/weatherapp/location/CityFinder.java",
"snippet": "public static String getCityNameUsingNetwork(Context context, Location location) {\n String city = \"\";\n try {\n Geocoder geocoder = new Geocoder(context,... | import static com.aniketjain.weatherapp.location.CityFinder.getCityNameUsingNetwork;
import static com.aniketjain.weatherapp.location.CityFinder.setLongitudeLatitude;
import static com.aniketjain.weatherapp.network.InternetConnectivity.isInternetConnected;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.aniketjain.weatherapp.adapter.DaysAdapter;
import com.aniketjain.weatherapp.databinding.ActivityHomeBinding;
import com.aniketjain.weatherapp.location.LocationCord;
import com.aniketjain.weatherapp.toast.Toaster;
import com.aniketjain.weatherapp.update.UpdateUI;
import com.aniketjain.weatherapp.url.URL;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.play.core.appupdate.AppUpdateInfo;
import com.google.android.play.core.appupdate.AppUpdateManager;
import com.google.android.play.core.appupdate.AppUpdateManagerFactory;
import com.google.android.play.core.install.model.AppUpdateType;
import com.google.android.play.core.install.model.UpdateAvailability;
import com.google.android.play.core.tasks.Task;
import org.json.JSONException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Objects; | 3,681 | package com.aniketjain.weatherapp;
public class HomeActivity extends AppCompatActivity {
private final int WEATHER_FORECAST_APP_UPDATE_REQ_CODE = 101; // for app update
private static final int PERMISSION_CODE = 1; // for user location permission
private String name, updated_at, description, temperature, min_temperature, max_temperature, pressure, wind_speed, humidity;
private int condition;
private long update_time, sunset, sunrise;
private String city = "";
private final int REQUEST_CODE_EXTRA_INPUT = 101;
private ActivityHomeBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// binding
binding = ActivityHomeBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
// set navigation bar color
setNavigationBarColor();
//check for new app update
checkUpdate();
// set refresh color schemes
setRefreshLayoutColor();
// when user do search and refresh
listeners();
// getting data using internet connection
getDataUsingNetwork();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_EXTRA_INPUT) {
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> arrayList = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
binding.layout.cityEt.setText(Objects.requireNonNull(arrayList).get(0).toUpperCase());
searchCity(binding.layout.cityEt.getText().toString());
}
}
}
private void setNavigationBarColor() {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setNavigationBarColor(getResources().getColor(R.color.navBarColor));
}
}
private void setUpDaysRecyclerView() {
DaysAdapter daysAdapter = new DaysAdapter(this);
binding.dayRv.setLayoutManager(
new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
);
binding.dayRv.setAdapter(daysAdapter);
}
@SuppressLint("ClickableViewAccessibility")
private void listeners() {
binding.layout.mainLayout.setOnTouchListener((view, motionEvent) -> {
hideKeyboard(view);
return false;
});
binding.layout.searchBarIv.setOnClickListener(view -> searchCity(binding.layout.cityEt.getText().toString()));
binding.layout.searchBarIv.setOnTouchListener((view, motionEvent) -> {
hideKeyboard(view);
return false;
});
binding.layout.cityEt.setOnEditorActionListener((textView, i, keyEvent) -> {
if (i == EditorInfo.IME_ACTION_GO) {
searchCity(binding.layout.cityEt.getText().toString());
hideKeyboard(textView);
return true;
}
return false;
});
binding.layout.cityEt.setOnFocusChangeListener((view, b) -> {
if (!b) {
hideKeyboard(view);
}
});
binding.mainRefreshLayout.setOnRefreshListener(() -> {
checkConnection();
Log.i("refresh", "Refresh Done.");
binding.mainRefreshLayout.setRefreshing(false); //for the next time
});
//Mic Search
binding.layout.micSearchId.setOnClickListener(view -> {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, REQUEST_CODE_EXTRA_INPUT);
try {
//it was deprecated but still work
startActivityForResult(intent, REQUEST_CODE_EXTRA_INPUT);
} catch (Exception e) {
Log.d("Error Voice", "Mic Error: " + e);
}
});
}
private void setRefreshLayoutColor() {
binding.mainRefreshLayout.setProgressBackgroundColorSchemeColor(
getResources().getColor(R.color.textColor)
);
binding.mainRefreshLayout.setColorSchemeColors(
getResources().getColor(R.color.navBarColor)
);
}
private void searchCity(String cityName) {
if (cityName == null || cityName.isEmpty()) {
Toaster.errorToast(this, "Please enter the city name");
} else {
setLatitudeLongitudeUsingCity(cityName);
}
}
private void getDataUsingNetwork() {
FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
//check permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_CODE);
} else {
client.getLastLocation().addOnSuccessListener(location -> {
setLongitudeLatitude(location);
city = getCityNameUsingNetwork(this, location);
getTodayWeatherInfo(city);
});
}
}
private void setLatitudeLongitudeUsingCity(String cityName) { | package com.aniketjain.weatherapp;
public class HomeActivity extends AppCompatActivity {
private final int WEATHER_FORECAST_APP_UPDATE_REQ_CODE = 101; // for app update
private static final int PERMISSION_CODE = 1; // for user location permission
private String name, updated_at, description, temperature, min_temperature, max_temperature, pressure, wind_speed, humidity;
private int condition;
private long update_time, sunset, sunrise;
private String city = "";
private final int REQUEST_CODE_EXTRA_INPUT = 101;
private ActivityHomeBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// binding
binding = ActivityHomeBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
// set navigation bar color
setNavigationBarColor();
//check for new app update
checkUpdate();
// set refresh color schemes
setRefreshLayoutColor();
// when user do search and refresh
listeners();
// getting data using internet connection
getDataUsingNetwork();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_EXTRA_INPUT) {
if (resultCode == RESULT_OK && data != null) {
ArrayList<String> arrayList = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
binding.layout.cityEt.setText(Objects.requireNonNull(arrayList).get(0).toUpperCase());
searchCity(binding.layout.cityEt.getText().toString());
}
}
}
private void setNavigationBarColor() {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().setNavigationBarColor(getResources().getColor(R.color.navBarColor));
}
}
private void setUpDaysRecyclerView() {
DaysAdapter daysAdapter = new DaysAdapter(this);
binding.dayRv.setLayoutManager(
new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
);
binding.dayRv.setAdapter(daysAdapter);
}
@SuppressLint("ClickableViewAccessibility")
private void listeners() {
binding.layout.mainLayout.setOnTouchListener((view, motionEvent) -> {
hideKeyboard(view);
return false;
});
binding.layout.searchBarIv.setOnClickListener(view -> searchCity(binding.layout.cityEt.getText().toString()));
binding.layout.searchBarIv.setOnTouchListener((view, motionEvent) -> {
hideKeyboard(view);
return false;
});
binding.layout.cityEt.setOnEditorActionListener((textView, i, keyEvent) -> {
if (i == EditorInfo.IME_ACTION_GO) {
searchCity(binding.layout.cityEt.getText().toString());
hideKeyboard(textView);
return true;
}
return false;
});
binding.layout.cityEt.setOnFocusChangeListener((view, b) -> {
if (!b) {
hideKeyboard(view);
}
});
binding.mainRefreshLayout.setOnRefreshListener(() -> {
checkConnection();
Log.i("refresh", "Refresh Done.");
binding.mainRefreshLayout.setRefreshing(false); //for the next time
});
//Mic Search
binding.layout.micSearchId.setOnClickListener(view -> {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, REQUEST_CODE_EXTRA_INPUT);
try {
//it was deprecated but still work
startActivityForResult(intent, REQUEST_CODE_EXTRA_INPUT);
} catch (Exception e) {
Log.d("Error Voice", "Mic Error: " + e);
}
});
}
private void setRefreshLayoutColor() {
binding.mainRefreshLayout.setProgressBackgroundColorSchemeColor(
getResources().getColor(R.color.textColor)
);
binding.mainRefreshLayout.setColorSchemeColors(
getResources().getColor(R.color.navBarColor)
);
}
private void searchCity(String cityName) {
if (cityName == null || cityName.isEmpty()) {
Toaster.errorToast(this, "Please enter the city name");
} else {
setLatitudeLongitudeUsingCity(cityName);
}
}
private void getDataUsingNetwork() {
FusedLocationProviderClient client = LocationServices.getFusedLocationProviderClient(this);
//check permission
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_CODE);
} else {
client.getLastLocation().addOnSuccessListener(location -> {
setLongitudeLatitude(location);
city = getCityNameUsingNetwork(this, location);
getTodayWeatherInfo(city);
});
}
}
private void setLatitudeLongitudeUsingCity(String cityName) { | URL.setCity_url(cityName); | 7 | 2023-10-25 21:15:57+00:00 | 8k |
dawex/sigourney | trust-framework/verifiable-credentials-model/src/test/java/com/dawex/sigourney/trustframework/vc/model/v2210/dataproduct/DataProductVerifiableCredentialTest.java | [
{
"identifier": "FormatProvider",
"path": "trust-framework/verifiable-credentials-core/src/main/java/com/dawex/sigourney/trustframework/vc/core/jsonld/serialization/FormatProvider.java",
"snippet": "public interface FormatProvider {\n\n\t/**\n\t * Returns the format matching the specified format name\n\... | import com.dawex.sigourney.trustframework.vc.core.jsonld.serialization.FormatProvider;
import com.dawex.sigourney.trustframework.vc.model.shared.DefaultFormatProvider;
import com.dawex.sigourney.trustframework.vc.model.v2210.serialization.Format;
import com.dawex.sigourney.trustframework.vc.model.v2210.serialization.JacksonModuleFactory;
import com.dawex.sigourney.trustframework.vc.model.v2210.AbstractVerifiableCredentialTest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.junit.jupiter.api.Test;
import java.time.LocalDate;
import java.time.Month;
import java.time.ZoneOffset;
import java.util.List;
import static com.dawex.sigourney.trustframework.vc.model.utils.TestUtils.assertThatJsonListValue;
import static com.dawex.sigourney.trustframework.vc.model.utils.TestUtils.assertThatJsonStringValue; | 3,985 | package com.dawex.sigourney.trustframework.vc.model.v2210.dataproduct;
class DataProductVerifiableCredentialTest extends AbstractVerifiableCredentialTest {
@Test
void shouldGenerateValidVerifiableCredentialForDataProduct() throws JsonProcessingException {
// given
final var verifiableCredential = getDataProductVerifiableCredential();
// when
final String serializedVc = serializeVc(verifiableCredential);
// then
assertThatProofIsValid(serializedVc);
assertThatJsonListValue("$['@context']", serializedVc).hasSize(4);
assertThatJsonStringValue("$['@context'][0]['@base']", serializedVc).isEqualTo("https://dawex.com");
assertThatJsonStringValue("$['@context'][0]['dct']", serializedVc).isEqualTo("http://purl.org/dc/terms/");
assertThatJsonStringValue("$['@context'][1]", serializedVc).isEqualTo("https://www.w3.org/2018/credentials/v1");
assertThatJsonStringValue("$['@context'][2]", serializedVc).isEqualTo("https://w3id.org/security/suites/jws-2020/v1");
assertThatJsonStringValue("$['@context'][3]", serializedVc).isEqualTo(
"https://registry.lab.gaia-x.eu/development/api/trusted-shape-registry/v1/shapes/jsonld/trustframework#");
assertThatJsonStringValue("$['type']", serializedVc).isEqualTo("VerifiableCredential");
assertThatJsonStringValue("$['id']", serializedVc)
.isEqualTo(
"./api/secure/participant/organisations/62b570acb33e417edcb345ee/dataOfferings/62bab5ae84fd784b1541e8f3/verifiableCredential");
assertThatJsonStringValue("$['issuer']", serializedVc).isEqualTo("./organisations/62b570acb33e417ed-issuer");
assertThatJsonStringValue("$['issuanceDate']", serializedVc).isEqualTo("2022-08-04T00:00:00Z");
assertThatJsonStringValue("$['credentialSubject']['id']", serializedVc)
.isEqualTo("./dataOfferings/62bab5ae84fd784-dataproduct");
assertThatJsonStringValue("$['credentialSubject']['type']", serializedVc)
.isEqualTo("gx:ServiceOffering");
assertThatJsonStringValue("$['credentialSubject']['dct:title']", serializedVc)
.isEqualTo("Statistics of road accidents in France");
assertThatJsonStringValue("$['credentialSubject']['dct:description']", serializedVc)
.isEqualTo("This publication provides data on road accidents in France.");
assertThatJsonStringValue("$['credentialSubject']['dct:issued']", serializedVc).isEqualTo("2022-01-18T00:00:00Z");
assertThatJsonStringValue("$['credentialSubject']['gx:providedBy']['id']", serializedVc)
.isEqualTo("./organisations/62b570acb33e417-provider");
assertThatJsonListValue("$['credentialSubject']['gx:termsAndConditions']", serializedVc)
.hasSize(1);
assertThatJsonStringValue("$['credentialSubject']['gx:termsAndConditions'][0]['gx:URL']", serializedVc)
.isEqualTo("./termsAndConditions/https://dawex.com/termsAndConditions");
assertThatJsonStringValue("$['credentialSubject']['gx:termsAndConditions'][0]['gx:hash']", serializedVc)
.isEqualTo("d8402a23de560f5ab34b22d1a142feb9e13b3143");
assertThatJsonListValue("$['credentialSubject']['gx:policy']", serializedVc)
.hasSize(1)
.first()
.isEqualTo("policy");
assertThatJsonStringValue("$['credentialSubject']['gx:dataAccountExport']['gx:requestType']", serializedVc)
.isEqualTo("DataAccountExport.requestType");
assertThatJsonStringValue("$['credentialSubject']['gx:dataAccountExport']['gx:accessType']", serializedVc)
.isEqualTo("DataAccountExport.accessType");
assertThatJsonStringValue("$['credentialSubject']['gx:dataAccountExport']['gx:formatType']", serializedVc)
.isEqualTo("DataAccountExport.formatType");
assertThatJsonListValue("$['credentialSubject']['gx:aggregationOf']", serializedVc).hasSize(1);
assertThatJsonStringValue("$['credentialSubject']['gx:aggregationOf'][0]['id']", serializedVc)
.isEqualTo("./dataResource/62bac14584fd784b1541e9cb");
}
private static DataProductVerifiableCredential getDataProductVerifiableCredential() {
return DataProductVerifiableCredential.builder()
.id(new DataProductVerifiableCredential.Id("62bab5ae84fd784b1541e8f3", "62b570acb33e417edcb345ee"))
.issuer("62b570acb33e417ed-issuer")
.issuanceDate(LocalDate.of(2022, Month.AUGUST, 4).atStartOfDay(ZoneOffset.UTC))
.credentialSubject(DataProductCredentialSubject.builder()
.id("62bab5ae84fd784-dataproduct")
.title("Statistics of road accidents in France")
.description("This publication provides data on road accidents in France.")
.issued(LocalDate.of(2022, Month.JANUARY, 18).atStartOfDay(ZoneOffset.UTC))
.providedBy(ProvidedBy.builder().id("62b570acb33e417-provider").build())
.termsAndConditions(List.of(TermsAndConditionURI.builder()
.url("https://dawex.com/termsAndConditions")
.hash("d8402a23de560f5ab34b22d1a142feb9e13b3143")
.build()))
.policy(List.of("policy"))
.dataAccountExport(DataAccountExport.builder()
.requestType("DataAccountExport.requestType")
.accessType("DataAccountExport.accessType")
.formatType("DataAccountExport.formatType")
.build())
.aggregationOf(List.of(
AggregationOf.builder()
.id("62bac14584fd784b1541e9cb")
.build()
))
.build())
.build();
}
@Override
protected ObjectMapper getObjectMapper() {
final var objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
objectMapper.registerModule(JacksonModuleFactory.dataProductSerializationModule(getFormatProvider(), () -> "https://dawex.com"));
return objectMapper;
}
private static FormatProvider getFormatProvider() { | package com.dawex.sigourney.trustframework.vc.model.v2210.dataproduct;
class DataProductVerifiableCredentialTest extends AbstractVerifiableCredentialTest {
@Test
void shouldGenerateValidVerifiableCredentialForDataProduct() throws JsonProcessingException {
// given
final var verifiableCredential = getDataProductVerifiableCredential();
// when
final String serializedVc = serializeVc(verifiableCredential);
// then
assertThatProofIsValid(serializedVc);
assertThatJsonListValue("$['@context']", serializedVc).hasSize(4);
assertThatJsonStringValue("$['@context'][0]['@base']", serializedVc).isEqualTo("https://dawex.com");
assertThatJsonStringValue("$['@context'][0]['dct']", serializedVc).isEqualTo("http://purl.org/dc/terms/");
assertThatJsonStringValue("$['@context'][1]", serializedVc).isEqualTo("https://www.w3.org/2018/credentials/v1");
assertThatJsonStringValue("$['@context'][2]", serializedVc).isEqualTo("https://w3id.org/security/suites/jws-2020/v1");
assertThatJsonStringValue("$['@context'][3]", serializedVc).isEqualTo(
"https://registry.lab.gaia-x.eu/development/api/trusted-shape-registry/v1/shapes/jsonld/trustframework#");
assertThatJsonStringValue("$['type']", serializedVc).isEqualTo("VerifiableCredential");
assertThatJsonStringValue("$['id']", serializedVc)
.isEqualTo(
"./api/secure/participant/organisations/62b570acb33e417edcb345ee/dataOfferings/62bab5ae84fd784b1541e8f3/verifiableCredential");
assertThatJsonStringValue("$['issuer']", serializedVc).isEqualTo("./organisations/62b570acb33e417ed-issuer");
assertThatJsonStringValue("$['issuanceDate']", serializedVc).isEqualTo("2022-08-04T00:00:00Z");
assertThatJsonStringValue("$['credentialSubject']['id']", serializedVc)
.isEqualTo("./dataOfferings/62bab5ae84fd784-dataproduct");
assertThatJsonStringValue("$['credentialSubject']['type']", serializedVc)
.isEqualTo("gx:ServiceOffering");
assertThatJsonStringValue("$['credentialSubject']['dct:title']", serializedVc)
.isEqualTo("Statistics of road accidents in France");
assertThatJsonStringValue("$['credentialSubject']['dct:description']", serializedVc)
.isEqualTo("This publication provides data on road accidents in France.");
assertThatJsonStringValue("$['credentialSubject']['dct:issued']", serializedVc).isEqualTo("2022-01-18T00:00:00Z");
assertThatJsonStringValue("$['credentialSubject']['gx:providedBy']['id']", serializedVc)
.isEqualTo("./organisations/62b570acb33e417-provider");
assertThatJsonListValue("$['credentialSubject']['gx:termsAndConditions']", serializedVc)
.hasSize(1);
assertThatJsonStringValue("$['credentialSubject']['gx:termsAndConditions'][0]['gx:URL']", serializedVc)
.isEqualTo("./termsAndConditions/https://dawex.com/termsAndConditions");
assertThatJsonStringValue("$['credentialSubject']['gx:termsAndConditions'][0]['gx:hash']", serializedVc)
.isEqualTo("d8402a23de560f5ab34b22d1a142feb9e13b3143");
assertThatJsonListValue("$['credentialSubject']['gx:policy']", serializedVc)
.hasSize(1)
.first()
.isEqualTo("policy");
assertThatJsonStringValue("$['credentialSubject']['gx:dataAccountExport']['gx:requestType']", serializedVc)
.isEqualTo("DataAccountExport.requestType");
assertThatJsonStringValue("$['credentialSubject']['gx:dataAccountExport']['gx:accessType']", serializedVc)
.isEqualTo("DataAccountExport.accessType");
assertThatJsonStringValue("$['credentialSubject']['gx:dataAccountExport']['gx:formatType']", serializedVc)
.isEqualTo("DataAccountExport.formatType");
assertThatJsonListValue("$['credentialSubject']['gx:aggregationOf']", serializedVc).hasSize(1);
assertThatJsonStringValue("$['credentialSubject']['gx:aggregationOf'][0]['id']", serializedVc)
.isEqualTo("./dataResource/62bac14584fd784b1541e9cb");
}
private static DataProductVerifiableCredential getDataProductVerifiableCredential() {
return DataProductVerifiableCredential.builder()
.id(new DataProductVerifiableCredential.Id("62bab5ae84fd784b1541e8f3", "62b570acb33e417edcb345ee"))
.issuer("62b570acb33e417ed-issuer")
.issuanceDate(LocalDate.of(2022, Month.AUGUST, 4).atStartOfDay(ZoneOffset.UTC))
.credentialSubject(DataProductCredentialSubject.builder()
.id("62bab5ae84fd784-dataproduct")
.title("Statistics of road accidents in France")
.description("This publication provides data on road accidents in France.")
.issued(LocalDate.of(2022, Month.JANUARY, 18).atStartOfDay(ZoneOffset.UTC))
.providedBy(ProvidedBy.builder().id("62b570acb33e417-provider").build())
.termsAndConditions(List.of(TermsAndConditionURI.builder()
.url("https://dawex.com/termsAndConditions")
.hash("d8402a23de560f5ab34b22d1a142feb9e13b3143")
.build()))
.policy(List.of("policy"))
.dataAccountExport(DataAccountExport.builder()
.requestType("DataAccountExport.requestType")
.accessType("DataAccountExport.accessType")
.formatType("DataAccountExport.formatType")
.build())
.aggregationOf(List.of(
AggregationOf.builder()
.id("62bac14584fd784b1541e9cb")
.build()
))
.build())
.build();
}
@Override
protected ObjectMapper getObjectMapper() {
final var objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
objectMapper.registerModule(JacksonModuleFactory.dataProductSerializationModule(getFormatProvider(), () -> "https://dawex.com"));
return objectMapper;
}
private static FormatProvider getFormatProvider() { | final DefaultFormatProvider formatProvider = new DefaultFormatProvider(); | 1 | 2023-10-25 16:10:40+00:00 | 8k |
mcxiaoxiao/library-back | src/main/java/com/main/reader/ReaderServiceImpl.java | [
{
"identifier": "BookEntity",
"path": "src/main/java/com/main/schema/BookEntity.java",
"snippet": "@Entity\n@Table(name = \"book\", schema = \"public\", catalog = \"library\")\npublic class BookEntity {\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Id\n @Column(name = \"bookid\")\n ... | import com.main.schema.BookEntity;
import com.main.schema.HistoryEntity;
import com.main.schema.ReaderEntity;
import com.main.schema.TakeEntity;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.util.List; | 4,545 | package com.main.reader;
@Service
public class ReaderServiceImpl implements ReaderService {
@Resource
private ReaderRepository readerRepository;
public ReaderServiceImpl(ReaderRepository readerRepository)
{
this.readerRepository=readerRepository;
}
@Override | package com.main.reader;
@Service
public class ReaderServiceImpl implements ReaderService {
@Resource
private ReaderRepository readerRepository;
public ReaderServiceImpl(ReaderRepository readerRepository)
{
this.readerRepository=readerRepository;
}
@Override | public Page<ReaderEntity> findReaderAll(int pageNumber, int pageSize) | 2 | 2023-10-30 14:38:00+00:00 | 8k |
kdetard/koki | app/src/main/java/io/github/kdetard/koki/feature/settings/SettingsLogoutController.java | [
{
"identifier": "NetworkModule",
"path": "app/src/main/java/io/github/kdetard/koki/di/NetworkModule.java",
"snippet": "@Module\n@InstallIn(SingletonComponent.class)\npublic abstract class NetworkModule {\n public static final String BASE_URL = \"https://uiot.ixxc.dev\";\n public static final Strin... | import static autodispose2.AutoDispose.autoDisposable;
import android.view.View;
import androidx.datastore.rxjava3.RxDataStore;
import com.maxkeppeler.sheets.core.SheetStyle;
import com.maxkeppeler.sheets.info.InfoSheet;
import com.squareup.moshi.JsonAdapter;
import com.tencent.mmkv.MMKV;
import java.util.Objects;
import dagger.hilt.EntryPoint;
import dagger.hilt.InstallIn;
import dagger.hilt.android.EntryPointAccessors;
import dagger.hilt.components.SingletonComponent;
import io.github.kdetard.koki.R;
import io.github.kdetard.koki.Settings;
import io.github.kdetard.koki.di.NetworkModule;
import io.github.kdetard.koki.feature.base.BaseController;
import io.github.kdetard.koki.keycloak.KeycloakApiService;
import io.github.kdetard.koki.keycloak.RxRestKeycloak;
import io.github.kdetard.koki.keycloak.models.KeycloakConfig;
import io.github.kdetard.koki.keycloak.models.KeycloakToken;
import io.reactivex.rxjava3.core.Single;
import kotlin.Unit; | 4,977 | package io.github.kdetard.koki.feature.settings;
public class SettingsLogoutController extends BaseController {
@EntryPoint
@InstallIn(SingletonComponent.class)
interface SettingsLogoutEntryPoint {
RxDataStore<Settings> settings();
KeycloakApiService keycloakApiService();
JsonAdapter<KeycloakToken> keycloakTokenJsonAdapter();
}
SettingsLogoutEntryPoint entryPoint;
KeycloakConfig mKeycloakConfig;
public SettingsLogoutController() { super(R.layout.controller_settings_dialog); }
@Override
public void onViewCreated(View view) {
super.onViewCreated(view);
entryPoint = EntryPointAccessors.fromApplication(Objects.requireNonNull(getApplicationContext()), SettingsLogoutEntryPoint.class);
mKeycloakConfig = KeycloakConfig.getDefaultConfig(getApplicationContext());
new InfoSheet().show(Objects.requireNonNull(getActivity()), null, sheet -> {
sheet.style(SheetStyle.DIALOG);
sheet.setShowsDialog(true);
sheet.title(R.string.logout);
sheet.content(R.string.confirm_logout);
sheet.onCancel(this::cancelLogout);
sheet.onNegative(R.string.decline_logout, this::cancelLogout);
sheet.onPositive(R.string.accept_logout, this::confirmLogout);
return null;
});
}
private Unit cancelLogout() {
getRouter().popController(this);
return null;
}
private Unit confirmLogout() {
entryPoint.settings()
.data()
.firstOrError()
.map(Settings::getKeycloakTokenJson)
.map(entryPoint.keycloakTokenJsonAdapter()::fromJson)
.map(KeycloakToken::refreshToken)
.flatMapCompletable(refreshToken -> | package io.github.kdetard.koki.feature.settings;
public class SettingsLogoutController extends BaseController {
@EntryPoint
@InstallIn(SingletonComponent.class)
interface SettingsLogoutEntryPoint {
RxDataStore<Settings> settings();
KeycloakApiService keycloakApiService();
JsonAdapter<KeycloakToken> keycloakTokenJsonAdapter();
}
SettingsLogoutEntryPoint entryPoint;
KeycloakConfig mKeycloakConfig;
public SettingsLogoutController() { super(R.layout.controller_settings_dialog); }
@Override
public void onViewCreated(View view) {
super.onViewCreated(view);
entryPoint = EntryPointAccessors.fromApplication(Objects.requireNonNull(getApplicationContext()), SettingsLogoutEntryPoint.class);
mKeycloakConfig = KeycloakConfig.getDefaultConfig(getApplicationContext());
new InfoSheet().show(Objects.requireNonNull(getActivity()), null, sheet -> {
sheet.style(SheetStyle.DIALOG);
sheet.setShowsDialog(true);
sheet.title(R.string.logout);
sheet.content(R.string.confirm_logout);
sheet.onCancel(this::cancelLogout);
sheet.onNegative(R.string.decline_logout, this::cancelLogout);
sheet.onPositive(R.string.accept_logout, this::confirmLogout);
return null;
});
}
private Unit cancelLogout() {
getRouter().popController(this);
return null;
}
private Unit confirmLogout() {
entryPoint.settings()
.data()
.firstOrError()
.map(Settings::getKeycloakTokenJson)
.map(entryPoint.keycloakTokenJsonAdapter()::fromJson)
.map(KeycloakToken::refreshToken)
.flatMapCompletable(refreshToken -> | RxRestKeycloak.endSession(entryPoint.keycloakApiService(), mKeycloakConfig, refreshToken)) | 3 | 2023-10-30 00:44:59+00:00 | 8k |
HiNinoJay/easyUsePoi | src/main/java/top/nino/easyUsePoi/word/module/DocumentTool.java | [
{
"identifier": "ModuleTypeEnum",
"path": "src/main/java/top/nino/easyUsePoi/word/constant/ModuleTypeEnum.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic enum ModuleTypeEnum {\n\n PARAGRAPH(\"paragraph\"),\n TABLE(\"table\"),\n BAR_CHART(\"barChart\"),\n Pi_CHART(\"piChart\");\n\n ... | import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.xddf.usermodel.PresetColor;
import org.apache.poi.xwpf.usermodel.BreakType;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.nino.easyUsePoi.word.constant.ModuleTypeEnum;
import top.nino.easyUsePoi.word.constant.text.ColorEnum;
import top.nino.easyUsePoi.word.constant.text.FontSizeEnum;
import top.nino.easyUsePoi.word.module.chart.BarChartTool;
import top.nino.easyUsePoi.word.module.chart.PiChartTool;
import top.nino.easyUsePoi.word.module.data.WordJsonVo;
import top.nino.easyUsePoi.word.module.data.WordModule;
import top.nino.easyUsePoi.word.module.data.WordText;
import top.nino.easyUsePoi.word.module.paragraph.ParagraphTool;
import top.nino.easyUsePoi.word.module.table.TableTool;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List; | 4,972 | package top.nino.easyUsePoi.word.module;
/**
* @Author:zengzhj
* @Date:2023/10/30 13:02
*/
@Component
@Slf4j
public class DocumentTool {
/**
* A4纸张 的 宽
*/
private final static long A4_WIDTH = 12242L;
/**
* A4纸张 的 高
*/
private final static long A4_HEIGHT = 15842L;
@Autowired | package top.nino.easyUsePoi.word.module;
/**
* @Author:zengzhj
* @Date:2023/10/30 13:02
*/
@Component
@Slf4j
public class DocumentTool {
/**
* A4纸张 的 宽
*/
private final static long A4_WIDTH = 12242L;
/**
* A4纸张 的 高
*/
private final static long A4_HEIGHT = 15842L;
@Autowired | private ParagraphTool paragraphTool; | 8 | 2023-10-31 19:43:22+00:00 | 8k |
inceptive-tech/ENTSOEDataRetrieval | src/test/java/tech/inceptive/ai4czc/entsoedataretrieval/csv/transformers/TestUnavailabilityDocCSVTransformer.java | [
{
"identifier": "UnavailabilityMarketDocument",
"path": "src/main/java/tech/inceptive/ai4czc/entsoedataretrieval/fetcher/xjc/UnavailabilityMarketDocument.java",
"snippet": "@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"Unavailability_MarketDocument\", propOrder = {\n \"mrid\",\n \"revis... | import java.io.BufferedWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import javax.xml.bind.JAXBException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import static org.mockito.Mockito.*;
import tech.inceptive.ai4czc.entsoedataretrieval.csv.ColumnDefinition;
import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.UnavailabilityMarketDocument;
import tech.inceptive.ai4czc.entsoedataretrieval.fetcher.xjc.custom.JAXBDeserializerHelper; | 5,019 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers;
/**
*
* @author Andres Bel Alonso
*/
public class TestUnavailabilityDocCSVTransformer {
private static final Logger LOGGER = LogManager.getLogger(TestUnavailabilityDocCSVTransformer.class);
@Test
public void testWriteNextEntry() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(",1,1");
}
@Test
public void testWriteNextEntryOutOfBondsBefore() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2018, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(false, out);
verify(mockBW, times(0)).write(any(String.class));
}
@Test
public void testWriteNextEntryOutOfBondsAfter() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2020, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(false, out);
verify(mockBW, times(0)).write(any(String.class));
}
@Test
public void testWriteNextEntryStartPoint() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 7, 22, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(",1,1");
}
@Test
public void testWriteNextEntryEndPoint() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 19, 22, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(false, out);
verify(mockBW, times(0)).write(any(String.class));
}
@Test
public void testWriteNewEntryDifferentSepator() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(";1;1");
}
@Test
public void testWriteNewEntryNonScheduled() throws IOException {
// this document contains an outage non scheduled
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMeUnscheduled.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2020, 4, 10, 4, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(";1;0");
}
@Test
public void testWriteNewEntryGenerationOutage() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("GenerationOutage.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2023, 3, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(";1;1;114.0");
}
@Test
public void testComputeColumnDefTransmission() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
//when
List<ColumnDefinition> colDef = transformer.computeColumnDef();
//then
assertEquals(2, colDef.size());
assertEquals(UnavailabilityDocCSVTransformer.TRANSMISSION_UNAVAILABILITY_BASE_NAME + "10T-ME-RS-00001G",
colDef.get(0).colName());
assertEquals(UnavailabilityDocCSVTransformer.UNAVAILABILITY_SCHEDULED_BN + "10T-ME-RS-00001G",
colDef.get(1).colName());
}
@Test
public void testComputeColumnDefGeneration() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("GenerationOutage.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
//when
List<ColumnDefinition> colDef = transformer.computeColumnDef();
//then
assertEquals(3, colDef.size());
assertEquals(UnavailabilityDocCSVTransformer.GENERATION_UNAVAILABILITY_BASE_NAME + "21W00000000PIVA9",
colDef.get(0).colName());
assertEquals(UnavailabilityDocCSVTransformer.UNAVAILABILITY_SCHEDULED_BN + "21W00000000PIVA9",
colDef.get(1).colName());
assertEquals("ME_" + UnavailabilityDocCSVTransformer.NOMINAL_OUTAGE_POWER + "21W00000000PIVA9",
colDef.get(2).colName());
}
@Test
public void testComputeColumnDefTransmissionMissingAsset() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutagaeGridUnknow.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
//when
List<ColumnDefinition> colDef = transformer.computeColumnDef();
//then
assertEquals(2, colDef.size());
assertEquals(UnavailabilityDocCSVTransformer.TRANSMISSION_UNAVAILABILITY_BASE_NAME + "Unknown_asset_IT-CS_ME",
colDef.get(0).colName());
assertEquals(UnavailabilityDocCSVTransformer.UNAVAILABILITY_SCHEDULED_BN + "Unknown_asset_IT-CS_ME",
colDef.get(1).colName());
}
private UnavailabilityMarketDocument readUnavailabilityDoc(String xmlFilename) throws IOException {
try { | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package tech.inceptive.ai4czc.entsoedataretrieval.csv.transformers;
/**
*
* @author Andres Bel Alonso
*/
public class TestUnavailabilityDocCSVTransformer {
private static final Logger LOGGER = LogManager.getLogger(TestUnavailabilityDocCSVTransformer.class);
@Test
public void testWriteNextEntry() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(",1,1");
}
@Test
public void testWriteNextEntryOutOfBondsBefore() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2018, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(false, out);
verify(mockBW, times(0)).write(any(String.class));
}
@Test
public void testWriteNextEntryOutOfBondsAfter() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2020, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(false, out);
verify(mockBW, times(0)).write(any(String.class));
}
@Test
public void testWriteNextEntryStartPoint() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 7, 22, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(",1,1");
}
@Test
public void testWriteNextEntryEndPoint() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ",", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 19, 22, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(false, out);
verify(mockBW, times(0)).write(any(String.class));
}
@Test
public void testWriteNewEntryDifferentSepator() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2019, 7, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(";1;1");
}
@Test
public void testWriteNewEntryNonScheduled() throws IOException {
// this document contains an outage non scheduled
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMeUnscheduled.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2020, 4, 10, 4, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(";1;0");
}
@Test
public void testWriteNewEntryGenerationOutage() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("GenerationOutage.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
BufferedWriter mockBW = mock(BufferedWriter.class);
LocalDateTime ldt = LocalDateTime.of(2023, 3, 10, 12, 0);
//when
boolean out = transformer.writeNextEntry(ldt, mockBW);
//then
assertEquals(true, out);
verify(mockBW, times(1)).write(";1;1;114.0");
}
@Test
public void testComputeColumnDefTransmission() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutageGridRsMe.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
//when
List<ColumnDefinition> colDef = transformer.computeColumnDef();
//then
assertEquals(2, colDef.size());
assertEquals(UnavailabilityDocCSVTransformer.TRANSMISSION_UNAVAILABILITY_BASE_NAME + "10T-ME-RS-00001G",
colDef.get(0).colName());
assertEquals(UnavailabilityDocCSVTransformer.UNAVAILABILITY_SCHEDULED_BN + "10T-ME-RS-00001G",
colDef.get(1).colName());
}
@Test
public void testComputeColumnDefGeneration() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("GenerationOutage.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
//when
List<ColumnDefinition> colDef = transformer.computeColumnDef();
//then
assertEquals(3, colDef.size());
assertEquals(UnavailabilityDocCSVTransformer.GENERATION_UNAVAILABILITY_BASE_NAME + "21W00000000PIVA9",
colDef.get(0).colName());
assertEquals(UnavailabilityDocCSVTransformer.UNAVAILABILITY_SCHEDULED_BN + "21W00000000PIVA9",
colDef.get(1).colName());
assertEquals("ME_" + UnavailabilityDocCSVTransformer.NOMINAL_OUTAGE_POWER + "21W00000000PIVA9",
colDef.get(2).colName());
}
@Test
public void testComputeColumnDefTransmissionMissingAsset() throws IOException {
//given
UnavailabilityMarketDocument doc = readUnavailabilityDoc("OutagaeGridUnknow.xml");
UnavailabilityDocCSVTransformer transformer = new UnavailabilityDocCSVTransformer(doc, ";", "\"");
//when
List<ColumnDefinition> colDef = transformer.computeColumnDef();
//then
assertEquals(2, colDef.size());
assertEquals(UnavailabilityDocCSVTransformer.TRANSMISSION_UNAVAILABILITY_BASE_NAME + "Unknown_asset_IT-CS_ME",
colDef.get(0).colName());
assertEquals(UnavailabilityDocCSVTransformer.UNAVAILABILITY_SCHEDULED_BN + "Unknown_asset_IT-CS_ME",
colDef.get(1).colName());
}
private UnavailabilityMarketDocument readUnavailabilityDoc(String xmlFilename) throws IOException {
try { | return JAXBDeserializerHelper.doJAXBUnmarshall( | 1 | 2023-10-30 09:09:53+00:00 | 8k |
EricFan2002/SC2002 | src/app/entity/report/EnquiryReport.java | [
{
"identifier": "Camp",
"path": "src/app/entity/camp/Camp.java",
"snippet": "public class Camp extends CampDetails implements ITaggedItem {\n\n protected Staff staffInCharge;\n protected Set<Student> attendees;\n protected Set<Student> committees;\n protected Set<Student> registeredStudents;... | import java.util.ArrayList;
import java.util.Arrays;
import app.entity.camp.Camp;
import app.entity.camp.CampList;
import app.entity.enquiry.Enquiry; | 6,017 | package app.entity.report;
/**
* The {@code EnquiryReport} class represents a report on camp enquiries, including details about questions and answers.
* It extends the {@code Report} class and implements the {@code ISerializeable} interface.
*/
public class EnquiryReport extends Report {
/**
* The fields included in the report.
*/
private static String[] fields = { "Camp ID", "Camp Name", "Sender ID", "Sender Name", "Question",
"Answered by Name", "Answered by ID", "Answer" };
/**
* The list of camps to be included in the report.
*/
private CampList camp;
/**
* Constructs an EnquiryReport object with the specified camp list.
*
* @param camp The list of camps to be included in the report.
*/
public EnquiryReport(CampList camp) {
super();
this.camp = new CampList();
camp.forEach((curCamp) -> {
this.camp.add(curCamp);
});
}
/**
* Constructs an EnquiryReport object with the specified camp.
*
* @param camp The camp to be included in the report.
*/
public EnquiryReport(Camp camp) {
super();
this.camp = new CampList();
this.camp.add(camp);
}
/**
* Serializes the enquiry report and represents its data as an ArrayList of ArrayList of Strings.
*
* @return An {@code ArrayList<ArrayList<String>>} representing the serialized data of the enquiry report.
*/
public final ArrayList<ArrayList<String>> serialize() {
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
ArrayList<String> header = new ArrayList<String>(Arrays.asList(fields));
data.add(header);
for (Camp camp : this.camp) { | package app.entity.report;
/**
* The {@code EnquiryReport} class represents a report on camp enquiries, including details about questions and answers.
* It extends the {@code Report} class and implements the {@code ISerializeable} interface.
*/
public class EnquiryReport extends Report {
/**
* The fields included in the report.
*/
private static String[] fields = { "Camp ID", "Camp Name", "Sender ID", "Sender Name", "Question",
"Answered by Name", "Answered by ID", "Answer" };
/**
* The list of camps to be included in the report.
*/
private CampList camp;
/**
* Constructs an EnquiryReport object with the specified camp list.
*
* @param camp The list of camps to be included in the report.
*/
public EnquiryReport(CampList camp) {
super();
this.camp = new CampList();
camp.forEach((curCamp) -> {
this.camp.add(curCamp);
});
}
/**
* Constructs an EnquiryReport object with the specified camp.
*
* @param camp The camp to be included in the report.
*/
public EnquiryReport(Camp camp) {
super();
this.camp = new CampList();
this.camp.add(camp);
}
/**
* Serializes the enquiry report and represents its data as an ArrayList of ArrayList of Strings.
*
* @return An {@code ArrayList<ArrayList<String>>} representing the serialized data of the enquiry report.
*/
public final ArrayList<ArrayList<String>> serialize() {
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
ArrayList<String> header = new ArrayList<String>(Arrays.asList(fields));
data.add(header);
for (Camp camp : this.camp) { | ArrayList<Enquiry> enquiries = camp.getEnquiryList(); | 2 | 2023-11-01 05:18:29+00:00 | 8k |
LLNL/response | src/main/java/gov/llnl/gnem/response/NDCUnitsParser.java | [
{
"identifier": "ResponseUnits",
"path": "src/main/java/com/isti/jevalresp/ResponseUnits.java",
"snippet": "public class ResponseUnits implements Serializable {\r\n\r\n private static final long serialVersionUID = 6244556146016308579L;\r\n\r\n private final Unit<? extends Quantity<?>> inputUnits;\... | import tec.units.ri.unit.MetricPrefix;
import static tec.units.ri.unit.Units.METRE;
import static tec.units.ri.unit.Units.METRE_PER_SECOND;
import static tec.units.ri.unit.Units.METRE_PER_SQUARE_SECOND;
import static tec.units.ri.unit.Units.PASCAL;
import edu.iris.Fissures.model.UnitImpl;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import com.isti.jevalresp.ResponseUnits;
import com.isti.jevalresp.UnitsStatus;
| 5,025 | /*-
* #%L
* Seismic Response Processing Module
* LLNL-CODE-856351
* This work was performed under the auspices of the U.S. Department of Energy
* by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.
* %%
* Copyright (C) 2023 Lawrence Livermore National Laboratory
* %%
* 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.
* #L%
*/
package gov.llnl.gnem.response;
/**
*
* @author dodge1
*/
public class NDCUnitsParser {
public ResponseUnits getResponseUnits(File file) throws FileNotFoundException {
ResponseUnits quantity = new ResponseUnits();
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.trim().startsWith("#")) {
String tmp = line.toLowerCase();
if (tmp.contains("nm/s/s")) {
| /*-
* #%L
* Seismic Response Processing Module
* LLNL-CODE-856351
* This work was performed under the auspices of the U.S. Department of Energy
* by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344.
* %%
* Copyright (C) 2023 Lawrence Livermore National Laboratory
* %%
* 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.
* #L%
*/
package gov.llnl.gnem.response;
/**
*
* @author dodge1
*/
public class NDCUnitsParser {
public ResponseUnits getResponseUnits(File file) throws FileNotFoundException {
ResponseUnits quantity = new ResponseUnits();
try (Scanner sc = new Scanner(file)) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
if (line.trim().startsWith("#")) {
String tmp = line.toLowerCase();
if (tmp.contains("nm/s/s")) {
| return new ResponseUnits(MetricPrefix.NANO(METRE_PER_SQUARE_SECOND), UnitImpl.NANOMETER_PER_SECOND_PER_SECOND, UnitsStatus.QUANTITY_AND_UNITS);
| 1 | 2023-10-30 21:06:43+00:00 | 8k |
NUMS-half/OnlineOA | src/main/java/cn/edu/neu/onlineoa/controller/ApplyExportServlet.java | [
{
"identifier": "Apply",
"path": "src/main/java/cn/edu/neu/onlineoa/bean/Apply.java",
"snippet": "public class Apply {\n private int aid;\n private int status = -1;\n private String studentId;\n private String studentName;\n private String courseId;\n private String courseName;\n pr... | import cn.edu.neu.onlineoa.bean.Apply;
import cn.edu.neu.onlineoa.bean.ApplyStatus;
import cn.edu.neu.onlineoa.service.ApplyService;
import cn.edu.neu.onlineoa.utils.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List; | 3,929 | package cn.edu.neu.onlineoa.controller;
@WebServlet(name = "ApplyExportServlet", urlPatterns = "/applyExport")
public class ApplyExportServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置文件类型与文件名
String filename = "申请审批信息导出_" + DateUtils.getLocalDateTime("yyyyMMdd_HH-mm-ss");
String encodedFileName = URLEncoder.encode(filename, "UTF-8");
resp.setContentType("application/vnd.ms-excel");
resp.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName + ".xls");
// 创建Excel工作簿
Workbook workbook = new HSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("已通过的申请");
// 获取要导出的数据
ApplyService applyService = new ApplyService();
List<Apply> applyList = applyService.findAllPassedApply();
// 创建表头行
Row headerRow = sheet.createRow(0);
// 添加表头列
headerRow.createCell(0).setCellValue("申请ID");
headerRow.createCell(1).setCellValue("申请状态");
headerRow.createCell(2).setCellValue("学生ID");
headerRow.createCell(3).setCellValue("学生姓名");
headerRow.createCell(4).setCellValue("课程ID");
headerRow.createCell(5).setCellValue("课程名称");
headerRow.createCell(6).setCellValue("申请原因");
headerRow.createCell(7).setCellValue("申请提交时间");
headerRow.createCell(8).setCellValue("第一审批人ID");
headerRow.createCell(9).setCellValue("第一次审批时间");
headerRow.createCell(10).setCellValue("第二审批人ID");
headerRow.createCell(11).setCellValue("第二次审批时间");
headerRow.createCell(12).setCellValue("学生是否确认");
// 填充数据行
int rowNum = 1;
for ( Apply apply : applyList ) {
Row dataRow = sheet.createRow(rowNum++);
dataRow.createCell(0).setCellValue(apply.getAid()); | package cn.edu.neu.onlineoa.controller;
@WebServlet(name = "ApplyExportServlet", urlPatterns = "/applyExport")
public class ApplyExportServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置文件类型与文件名
String filename = "申请审批信息导出_" + DateUtils.getLocalDateTime("yyyyMMdd_HH-mm-ss");
String encodedFileName = URLEncoder.encode(filename, "UTF-8");
resp.setContentType("application/vnd.ms-excel");
resp.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName + ".xls");
// 创建Excel工作簿
Workbook workbook = new HSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("已通过的申请");
// 获取要导出的数据
ApplyService applyService = new ApplyService();
List<Apply> applyList = applyService.findAllPassedApply();
// 创建表头行
Row headerRow = sheet.createRow(0);
// 添加表头列
headerRow.createCell(0).setCellValue("申请ID");
headerRow.createCell(1).setCellValue("申请状态");
headerRow.createCell(2).setCellValue("学生ID");
headerRow.createCell(3).setCellValue("学生姓名");
headerRow.createCell(4).setCellValue("课程ID");
headerRow.createCell(5).setCellValue("课程名称");
headerRow.createCell(6).setCellValue("申请原因");
headerRow.createCell(7).setCellValue("申请提交时间");
headerRow.createCell(8).setCellValue("第一审批人ID");
headerRow.createCell(9).setCellValue("第一次审批时间");
headerRow.createCell(10).setCellValue("第二审批人ID");
headerRow.createCell(11).setCellValue("第二次审批时间");
headerRow.createCell(12).setCellValue("学生是否确认");
// 填充数据行
int rowNum = 1;
for ( Apply apply : applyList ) {
Row dataRow = sheet.createRow(rowNum++);
dataRow.createCell(0).setCellValue(apply.getAid()); | dataRow.createCell(1).setCellValue(ApplyStatus.getNameByIndex(apply.getStatus())); | 1 | 2023-10-31 04:50:21+00:00 | 8k |
TNO/PPS | plugins/nl.esi.pps.tmsc.analysis.ui/xtend-gen/nl/esi/pps/tmsc/analysis/ui/dataanalysis/TimeBoundOutlierDataAnalysisItemContentProvider.java | [
{
"identifier": "Dependency",
"path": "plugins/nl.esi.pps.tmsc/src-gen/nl/esi/pps/tmsc/Dependency.java",
"snippet": "public interface Dependency extends PropertiesContainer, ITimeRange {\n\t/**\n\t * Returns the value of the '<em><b>Tmsc</b></em>' container reference.\n\t * It is bidirectional and its o... | import java.util.Collections;
import java.util.Set;
import nl.esi.pps.tmsc.Dependency;
import nl.esi.pps.tmsc.analysis.TimeBoundOutlierAnalysis;
import nl.esi.pps.tmsc.provider.dataanalysis.IDataAnalysisItemContentProvider;
import org.eclipse.lsat.common.xtend.Queries; | 5,395 | /**
* Copyright (c) 2018-2023 TNO and Contributors to the GitHub community
*
* This program and the accompanying materials are made available
* under the terms of the MIT License which is available at
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*/
package nl.esi.pps.tmsc.analysis.ui.dataanalysis;
@SuppressWarnings("all")
public class TimeBoundOutlierDataAnalysisItemContentProvider implements IDataAnalysisItemContentProvider {
@Override
public Set<String> getConfigurations(final Object object) {
final Dependency dependency = ((Dependency) object);
Set<String> _xifexpression = null; | /**
* Copyright (c) 2018-2023 TNO and Contributors to the GitHub community
*
* This program and the accompanying materials are made available
* under the terms of the MIT License which is available at
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*/
package nl.esi.pps.tmsc.analysis.ui.dataanalysis;
@SuppressWarnings("all")
public class TimeBoundOutlierDataAnalysisItemContentProvider implements IDataAnalysisItemContentProvider {
@Override
public Set<String> getConfigurations(final Object object) {
final Dependency dependency = ((Dependency) object);
Set<String> _xifexpression = null; | boolean _isSetTimeBoundSamples = TimeBoundOutlierAnalysis.isSetTimeBoundSamples(dependency); | 1 | 2023-10-30 16:00:25+00:00 | 8k |
CERBON-MODS/Bosses-of-Mass-Destruction-FORGE | src/main/java/com/cerbon/bosses_of_mass_destruction/projectile/PetalBladeProjectile.java | [
{
"identifier": "BMDEntities",
"path": "src/main/java/com/cerbon/bosses_of_mass_destruction/entity/BMDEntities.java",
"snippet": "public class BMDEntities {\n public static final BMDConfig mobConfig = AutoConfig.getConfigHolder(BMDConfig.class).getConfig();\n\n public static final DeferredRegister... | import com.cerbon.bosses_of_mass_destruction.entity.BMDEntities;
import com.cerbon.bosses_of_mass_destruction.entity.custom.gauntlet.GauntletEntity;
import com.cerbon.bosses_of_mass_destruction.projectile.util.ExemptEntities;
import net.minecraft.network.syncher.EntityDataAccessor;
import net.minecraft.network.syncher.EntityDataSerializers;
import net.minecraft.network.syncher.SynchedEntityData;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.EntityType;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.ai.attributes.Attributes;
import net.minecraft.world.entity.projectile.ThrowableItemProjectile;
import net.minecraft.world.level.Level;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraft.world.phys.EntityHitResult;
import org.jetbrains.annotations.NotNull;
import java.util.List;
import java.util.function.Consumer; | 5,306 | package com.cerbon.bosses_of_mass_destruction.projectile;
public class PetalBladeProjectile extends BaseThrownItemProjectile{
private Consumer<LivingEntity> entityHit;
| package com.cerbon.bosses_of_mass_destruction.projectile;
public class PetalBladeProjectile extends BaseThrownItemProjectile{
private Consumer<LivingEntity> entityHit;
| public static final EntityDataAccessor<Float> renderRotation = SynchedEntityData.defineId(GauntletEntity.class, EntityDataSerializers.FLOAT); | 1 | 2023-10-25 16:28:17+00:00 | 8k |
SmartGecko44/Spigot-Admin-Toys | src/main/java/org/gecko/wauh/listeners/BarrierListener.java | [
{
"identifier": "Main",
"path": "src/main/java/org/gecko/wauh/Main.java",
"snippet": "public final class Main extends JavaPlugin {\n\n ConfigurationManager configManager;\n FileConfiguration config;\n private int playerRadiusLimit;\n private int tntRadiusLimit;\n private int creeperRadius... | import de.tr7zw.changeme.nbtapi.NBTItem;
import net.md_5.bungee.api.ChatMessageType;
import net.md_5.bungee.api.chat.TextComponent;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.gecko.wauh.Main;
import org.gecko.wauh.data.ConfigurationManager;
import org.gecko.wauh.logic.Scale;
import java.util.*; | 5,003 | dist = (int) clickedLocation.distance(block.getLocation()) + 1;
if (dist > radiusLimit - 3) {
limitReached = true;
limitReachedThisIteration = true;
}
if ((dist - 1) > highestDist) {
if (dist > 1) {
int progressPercentage = (int) ((double) highestDist / (realRadiusLimit - 2) * 100);
highestDist = dist - 1;
// Send a message to the player only when the dist value rises
if (highestDist < realRadiusLimit - 1) {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.RED + progressPercentage + "% " + ChatColor.GREEN + "(" + ChatColor.RED + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
} else if (!limitReachedThisIteration) {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.GREEN + progressPercentage + "% (" + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
} else {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.GREEN + "100% " + "(" + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
}
}
}
// Check if the block is grass or dirt
if (block.getType() == Material.GRASS) {
grassRemovedCount++;
} else if (block.getType() == Material.DIRT) {
dirtRemovedCount++;
} else if (block.getType() == Material.BARRIER) {
barrierRemovedCount++;
}
if (!Main.getPlugin(Main.class).getShowRemoval()) {
markedBlocks.add(block);
} else {
block.setType(Material.AIR);
}
// Iterate through neighboring blocks and add them to the next set
// Iterate through neighboring blocks and add them to the next set
for (int i = -1; i <= 1; i++) {
if (i == 0) continue; // Skip the current block
addIfValid(block.getRelative(i, 0, 0), nextSet);
addIfValid(block.getRelative(0, i, 0), nextSet);
addIfValid(block.getRelative(0, 0, i), nextSet);
}
processedBlocks.add(block);
}
blocksToProcess = nextSet;
if (limitReachedThisIteration) {
barriuhFin();
} else if (!blocksToProcess.isEmpty()) {
if (Main.getPlugin(Main.class).getShowRemoval()) {
Bukkit.getScheduler().runTaskLater(Main.getPlugin(Main.class), this::processBlockRemoval, 1L);
} else {
processBlockRemoval();
}
} else {
if (dist > 1) {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.GREEN + "100% " + "(" + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
}
displaySummary();
}
}
private void barriuhFin() {
// Check if there are more blocks to process
if (limitReached) {
displaySummary();
} else if (!blocksToProcess.isEmpty()) {
if (Main.getPlugin(Main.class).getShowRemoval()) {
Bukkit.getScheduler().runTaskLater(Main.getPlugin(Main.class), this::processBlockRemoval, 1L);
} else {
processBlockRemoval();
}
} else {
displaySummary();
}
}
public void displaySummary() {
Player player = currentRemovingPlayer;
// Display the block removal summary to the player
if (grassRemovedCount + dirtRemovedCount + barrierRemovedCount > 1) {
if (barrierRemovedCount == 0 && grassRemovedCount == 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks.");
} else if (barrierRemovedCount == 0 && dirtRemovedCount == 0 && grassRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks.");
} else if (barrierRemovedCount == 0 && grassRemovedCount > 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks and " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks.");
} else if (barrierRemovedCount > 0 && grassRemovedCount > 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks, " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
} else if (barrierRemovedCount > 0 && grassRemovedCount > 0 && dirtRemovedCount == 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
} else if (barrierRemovedCount > 0 && grassRemovedCount == 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
}
// Display the block removal summary in the console
Bukkit.getConsoleSender().sendMessage(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.GREEN + " removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks, " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
if (!Main.getPlugin(Main.class).getShowRemoval()) {
removeMarkedBlocks();
} else {
blockRemovalActive = false;
currentRemovingPlayer = null;
stopBlockRemoval = false;
blocksToProcess.clear();
markedBlocks.clear();
processedBlocks.clear();
removedBlocks.clear();
}
} else {
blockRemovalActive = false;
currentRemovingPlayer = null;
stopBlockRemoval = false;
blocksToProcess.clear();
markedBlocks.clear();
processedBlocks.clear();
removedBlocks.clear();
}
}
private void removeMarkedBlocks() { | package org.gecko.wauh.listeners;
public class BarrierListener implements Listener {
private final Set<Block> markedBlocks = new HashSet<>();
private final Set<Block> processedBlocks = new HashSet<>();
private final Set<Block> removedBlocks = new HashSet<>();
public Player currentRemovingPlayer;
public boolean stopBlockRemoval = false;
public boolean blockRemovalActive = false;
private int grassRemovedCount;
private int dirtRemovedCount;
private int barrierRemovedCount;
private Set<Block> blocksToProcess = new HashSet<>();
private Location clickedLocation;
private boolean limitReached = false;
private int highestDist = 0;
private int dist;
private int radiusLimit;
private int realRadiusLimit;
private static final Set<Material> IMMUTABLE_MATERIALS = EnumSet.of(Material.GRASS, Material.DIRT, Material.BARRIER, Material.STRUCTURE_VOID);
private void addIfValid(Block block, Set<Block> nextSet) {
if (IMMUTABLE_MATERIALS.contains(block.getType())) {
nextSet.add(block);
}
}
@EventHandler
public void barrierBreakEventHandler(BlockBreakEvent event) {
if (!event.getPlayer().isOp() || event.getPlayer().getInventory().getItemInMainHand() == null || event.getPlayer().getInventory().getItemInMainHand().getAmount() == 0 || event.getPlayer().getInventory().getItemInMainHand().getType() == Material.AIR) {
return;
}
ConfigurationManager configManager;
FileConfiguration config;
configManager = new ConfigurationManager(Main.getPlugin(Main.class));
config = configManager.getConfig();
if (config.getInt("Barrier enabled") == 0) {
return;
}
BucketListener bucketListener = Main.getPlugin(Main.class).getBucketListener();
BedrockListener bedrockListener = Main.getPlugin(Main.class).getBedrockListener();
WaterBucketListener waterBucketListener = Main.getPlugin(Main.class).getWaterBucketListener();
NBTItem nbtItem = new NBTItem(event.getPlayer().getInventory().getItemInMainHand());
String identifier = nbtItem.getString("Ident");
radiusLimit = Main.getPlugin(Main.class).getRadiusLimit();
realRadiusLimit = radiusLimit - 2;
if (realRadiusLimit > 1) {
if (!bucketListener.wauhRemovalActive && !blockRemovalActive && !bedrockListener.allRemovalActive && !waterBucketListener.tsunamiActive) {
Player player = event.getPlayer();
if (IMMUTABLE_MATERIALS.contains(event.getBlock().getType())) {
// Check if the bucket is filling with water
if (player.getInventory().getItemInMainHand().getType() == Material.BARRIER && identifier.equalsIgnoreCase("Custom Barrier")) {
blockRemovalActive = true;
limitReached = false;
clickedLocation = event.getBlock().getLocation();
// Reset the water removal counts and initialize the set of blocks to process
grassRemovedCount = 0;
dirtRemovedCount = 0;
barrierRemovedCount = 0;
highestDist = 0;
blocksToProcess.clear();
currentRemovingPlayer = player;
// Add the clicked block to the set of blocks to process
blocksToProcess.add(clickedLocation.getBlock());
// Start the water removal process
processBlockRemoval();
}
}
}
}
}
private void processBlockRemoval() {
if (stopBlockRemoval) {
stopBlockRemoval = false;
displaySummary();
return;
}
Set<Block> nextSet = new HashSet<>();
boolean limitReachedThisIteration = false; // Variable to track whether the limit was reached this iteration
for (Block block : blocksToProcess) {
if (processedBlocks.contains(block)) {
continue;
}
dist = (int) clickedLocation.distance(block.getLocation()) + 1;
if (dist > radiusLimit - 3) {
limitReached = true;
limitReachedThisIteration = true;
}
if ((dist - 1) > highestDist) {
if (dist > 1) {
int progressPercentage = (int) ((double) highestDist / (realRadiusLimit - 2) * 100);
highestDist = dist - 1;
// Send a message to the player only when the dist value rises
if (highestDist < realRadiusLimit - 1) {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.RED + progressPercentage + "% " + ChatColor.GREEN + "(" + ChatColor.RED + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
} else if (!limitReachedThisIteration) {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.GREEN + progressPercentage + "% (" + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
} else {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.GREEN + "100% " + "(" + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
}
}
}
// Check if the block is grass or dirt
if (block.getType() == Material.GRASS) {
grassRemovedCount++;
} else if (block.getType() == Material.DIRT) {
dirtRemovedCount++;
} else if (block.getType() == Material.BARRIER) {
barrierRemovedCount++;
}
if (!Main.getPlugin(Main.class).getShowRemoval()) {
markedBlocks.add(block);
} else {
block.setType(Material.AIR);
}
// Iterate through neighboring blocks and add them to the next set
// Iterate through neighboring blocks and add them to the next set
for (int i = -1; i <= 1; i++) {
if (i == 0) continue; // Skip the current block
addIfValid(block.getRelative(i, 0, 0), nextSet);
addIfValid(block.getRelative(0, i, 0), nextSet);
addIfValid(block.getRelative(0, 0, i), nextSet);
}
processedBlocks.add(block);
}
blocksToProcess = nextSet;
if (limitReachedThisIteration) {
barriuhFin();
} else if (!blocksToProcess.isEmpty()) {
if (Main.getPlugin(Main.class).getShowRemoval()) {
Bukkit.getScheduler().runTaskLater(Main.getPlugin(Main.class), this::processBlockRemoval, 1L);
} else {
processBlockRemoval();
}
} else {
if (dist > 1) {
currentRemovingPlayer.spigot().sendMessage(ChatMessageType.ACTION_BAR, new TextComponent(ChatColor.GREEN + "Block removal: " + ChatColor.GREEN + "100% " + "(" + dist + ChatColor.WHITE + "/" + ChatColor.GREEN + realRadiusLimit + ")"));
}
displaySummary();
}
}
private void barriuhFin() {
// Check if there are more blocks to process
if (limitReached) {
displaySummary();
} else if (!blocksToProcess.isEmpty()) {
if (Main.getPlugin(Main.class).getShowRemoval()) {
Bukkit.getScheduler().runTaskLater(Main.getPlugin(Main.class), this::processBlockRemoval, 1L);
} else {
processBlockRemoval();
}
} else {
displaySummary();
}
}
public void displaySummary() {
Player player = currentRemovingPlayer;
// Display the block removal summary to the player
if (grassRemovedCount + dirtRemovedCount + barrierRemovedCount > 1) {
if (barrierRemovedCount == 0 && grassRemovedCount == 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks.");
} else if (barrierRemovedCount == 0 && dirtRemovedCount == 0 && grassRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks.");
} else if (barrierRemovedCount == 0 && grassRemovedCount > 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks and " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks.");
} else if (barrierRemovedCount > 0 && grassRemovedCount > 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks, " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
} else if (barrierRemovedCount > 0 && grassRemovedCount > 0 && dirtRemovedCount == 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
} else if (barrierRemovedCount > 0 && grassRemovedCount == 0 && dirtRemovedCount > 0) {
player.sendMessage(ChatColor.GREEN + "Removed " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
}
// Display the block removal summary in the console
Bukkit.getConsoleSender().sendMessage(ChatColor.LIGHT_PURPLE + player.getName() + ChatColor.GREEN + " removed " + ChatColor.RED + grassRemovedCount + ChatColor.GREEN + " grass blocks, " + ChatColor.RED + dirtRemovedCount + ChatColor.GREEN + " dirt blocks and " + ChatColor.RED + barrierRemovedCount + ChatColor.GREEN + " barrier blocks.");
if (!Main.getPlugin(Main.class).getShowRemoval()) {
removeMarkedBlocks();
} else {
blockRemovalActive = false;
currentRemovingPlayer = null;
stopBlockRemoval = false;
blocksToProcess.clear();
markedBlocks.clear();
processedBlocks.clear();
removedBlocks.clear();
}
} else {
blockRemovalActive = false;
currentRemovingPlayer = null;
stopBlockRemoval = false;
blocksToProcess.clear();
markedBlocks.clear();
processedBlocks.clear();
removedBlocks.clear();
}
}
private void removeMarkedBlocks() { | Scale scale; | 2 | 2023-10-28 11:26:45+00:00 | 8k |
sinch/sinch-sdk-java | client/src/test/java/com/sinch/sdk/domains/numbers/adapters/converters/AvailableNumberDtoConverterTest.java | [
{
"identifier": "AvailableNumber",
"path": "client/src/main/com/sinch/sdk/domains/numbers/models/AvailableNumber.java",
"snippet": "public class AvailableNumber {\n private final String phoneNumber;\n\n private final String regionCode;\n\n private final NumberType type;\n\n private final Collection<... | import static org.junit.jupiter.api.Assertions.assertEquals;
import com.sinch.sdk.domains.numbers.models.AvailableNumber;
import com.sinch.sdk.domains.numbers.models.Capability;
import com.sinch.sdk.domains.numbers.models.NumberType;
import com.sinch.sdk.domains.numbers.models.dto.v1.AvailableNumberDto;
import com.sinch.sdk.domains.numbers.models.dto.v1.AvailableNumbersResponseDto;
import com.sinch.sdk.domains.numbers.models.dto.v1.MoneyDto;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; | 6,450 | package com.sinch.sdk.domains.numbers.adapters.converters;
class AvailableNumberDtoConverterTest {
AvailableNumberDto dtoItem;
public static void compareWithDto(AvailableNumber client, AvailableNumberDto dto) {
assertEquals(dto.getPhoneNumber(), client.getPhoneNumber());
assertEquals(dto.getRegionCode(), client.getRegionCode());
assertEquals(dto.getType(), NumberType.valueOf(client.getType()));
assertEquals(
null == dto.getCapability() ? null : dto.getCapability(),
null == client.getCapability()
? null
: client.getCapability().stream()
.map(Capability::valueOf)
.collect(Collectors.toList()));
MoneyDtoConverterTest.compareWithDto(client.getSetupPrice(), dto.getSetupPrice());
MoneyDtoConverterTest.compareWithDto(client.getMonthlyPrice(), dto.getMonthlyPrice());
assertEquals(dto.getPaymentIntervalMonths(), client.getPaymentIntervalMonths());
assertEquals(
dto.getSupportingDocumentationRequired(), client.getSupportingDocumentationRequired());
}
@Test
void convertAvailableNumbersResponseDto() {
AvailableNumbersResponseDto dto = new AvailableNumbersResponseDto();
dto.setAvailableNumbers(Collections.singletonList(dtoItem));
Collection<AvailableNumber> converted = AvailableNumberDtoConverter.convert(dto);
assertEquals(dto.getAvailableNumbers().size(), converted.size());
}
@Test
void convertEmptyAvailableNumbersResponseDto() {
AvailableNumbersResponseDto dto = new AvailableNumbersResponseDto();
Collection<AvailableNumber> converted = AvailableNumberDtoConverter.convert(dto);
assertEquals(converted.size(), 0);
}
@Test
void convertAvailableNumberDto() {
AvailableNumberDto dto = dtoItem;
AvailableNumber converted = AvailableNumberDtoConverter.convert(dtoItem);
compareWithDto(converted, dto);
}
@Test
void convertAvailableNumberDtoWithUnknownType() {
dtoItem =
new AvailableNumberDto("phoneNumber", "regionCode", 4, true)
.type("foo")
.addCapabilityItem(Capability.SMS.value())
.addCapabilityItem(Capability.VOICE.value()) | package com.sinch.sdk.domains.numbers.adapters.converters;
class AvailableNumberDtoConverterTest {
AvailableNumberDto dtoItem;
public static void compareWithDto(AvailableNumber client, AvailableNumberDto dto) {
assertEquals(dto.getPhoneNumber(), client.getPhoneNumber());
assertEquals(dto.getRegionCode(), client.getRegionCode());
assertEquals(dto.getType(), NumberType.valueOf(client.getType()));
assertEquals(
null == dto.getCapability() ? null : dto.getCapability(),
null == client.getCapability()
? null
: client.getCapability().stream()
.map(Capability::valueOf)
.collect(Collectors.toList()));
MoneyDtoConverterTest.compareWithDto(client.getSetupPrice(), dto.getSetupPrice());
MoneyDtoConverterTest.compareWithDto(client.getMonthlyPrice(), dto.getMonthlyPrice());
assertEquals(dto.getPaymentIntervalMonths(), client.getPaymentIntervalMonths());
assertEquals(
dto.getSupportingDocumentationRequired(), client.getSupportingDocumentationRequired());
}
@Test
void convertAvailableNumbersResponseDto() {
AvailableNumbersResponseDto dto = new AvailableNumbersResponseDto();
dto.setAvailableNumbers(Collections.singletonList(dtoItem));
Collection<AvailableNumber> converted = AvailableNumberDtoConverter.convert(dto);
assertEquals(dto.getAvailableNumbers().size(), converted.size());
}
@Test
void convertEmptyAvailableNumbersResponseDto() {
AvailableNumbersResponseDto dto = new AvailableNumbersResponseDto();
Collection<AvailableNumber> converted = AvailableNumberDtoConverter.convert(dto);
assertEquals(converted.size(), 0);
}
@Test
void convertAvailableNumberDto() {
AvailableNumberDto dto = dtoItem;
AvailableNumber converted = AvailableNumberDtoConverter.convert(dtoItem);
compareWithDto(converted, dto);
}
@Test
void convertAvailableNumberDtoWithUnknownType() {
dtoItem =
new AvailableNumberDto("phoneNumber", "regionCode", 4, true)
.type("foo")
.addCapabilityItem(Capability.SMS.value())
.addCapabilityItem(Capability.VOICE.value()) | .setupPrice(new MoneyDto().currencyCode("EU").amount(".8")) | 5 | 2023-10-31 08:32:59+00:00 | 8k |
SpCoGov/SpCoBot | src/main/java/top/spco/service/command/Command.java | [
{
"identifier": "Message",
"path": "src/main/java/top/spco/api/message/Message.java",
"snippet": "public interface Message extends Codable{\n /**\n * 转为接近官方格式的字符串, 即 \"内容\". 如 At(member) + \"test\" 将转为 \"@QQ test\"\n *\n * @return 转化后的文本\n */\n String toMessageContext();\n}"
},
... | import top.spco.api.*;
import top.spco.api.message.Message;
import top.spco.events.CommandEvents;
import top.spco.service.chat.Chat;
import top.spco.service.chat.Stage;
import top.spco.service.command.commands.HelpCommand;
import top.spco.user.BotUser;
import top.spco.user.UserPermission;
import java.sql.SQLException;
import java.util.List; | 5,796 | /*
* Copyright 2023 SpCo
*
* 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
*
* https://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 top.spco.service.command;
/**
* {@link Command 命令}是一种用户与机器人交互的方式。与{@link Chat 对话}可能有以下不同:
* <ul>
* <li>{@link Chat 对话}传递参数时可以有明确的引导</li>
* <li>{@link Chat 对话}适合传递内容较大的参数</li>
* <li>{@link Chat 对话}每次传递参数都可以对参数进行校验</li>
* <li>{@link Chat 对话}支持传入的参数数量或类型取决于{@link Stage 阶段}的处理流程,而{@link Command 命令}支持传入不限量个参数(至多{@link Integer#MAX_VALUE 2<sup>31</sup>-1}个)</li>
* </ul>
* 这个接口代表一个命令的定义,用于处理用户输入的命令。每个命令都包括{@link #getLabels 标签}、{@link #getDescriptions 描述}、{@link #getScope 作用域}、{@link #needPermission 所需权限}等信息,
* 并提供{@link #init 初始化}和{@link #onCommand 执行命令}的方法。<p>
* <b>不建议命令实现此接口,而是继承 {@link AbstractCommand}类</b>
*
* @author SpCo
* @version 1.1.0
* @see AbstractCommand
* @since 0.1.0
*/
public interface Command {
/**
* 命令的标签(或名称)<p>
* 如命令 {@code "/command arg"} 中,{@code "command"} 就是该命令的标签。<p>
* 命令的标签是一个数组。数组的第一个元素是主标签,其余都是别称。<p>
* 在使用 {@link HelpCommand} 时,会将别称的描述重定向到主标签。<p>
* 如:
* <pre>
* help - 显示帮助信息
* ? -> help
* </pre>
*/
String[] getLabels();
List<CommandUsage> getUsages();
/**
* 命令的描述
*
* @return 命令的描述
*/
String getDescriptions();
/**
* 命令的作用域
*
* @return 命令的作用域
* @see CommandScope
*/
CommandScope getScope();
/**
* 使用命令所需的最低权限等级<p>
* 注意:这里的最低权限指的是{@link BotUser 机器人用户}的{@link UserPermission 用户权限},而不是群聊中{@link Member 群成员}的{@link MemberPermission 成员权限}。
*
* @return 使用命令所需的最低权限等级
* @see UserPermission
*/ | /*
* Copyright 2023 SpCo
*
* 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
*
* https://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 top.spco.service.command;
/**
* {@link Command 命令}是一种用户与机器人交互的方式。与{@link Chat 对话}可能有以下不同:
* <ul>
* <li>{@link Chat 对话}传递参数时可以有明确的引导</li>
* <li>{@link Chat 对话}适合传递内容较大的参数</li>
* <li>{@link Chat 对话}每次传递参数都可以对参数进行校验</li>
* <li>{@link Chat 对话}支持传入的参数数量或类型取决于{@link Stage 阶段}的处理流程,而{@link Command 命令}支持传入不限量个参数(至多{@link Integer#MAX_VALUE 2<sup>31</sup>-1}个)</li>
* </ul>
* 这个接口代表一个命令的定义,用于处理用户输入的命令。每个命令都包括{@link #getLabels 标签}、{@link #getDescriptions 描述}、{@link #getScope 作用域}、{@link #needPermission 所需权限}等信息,
* 并提供{@link #init 初始化}和{@link #onCommand 执行命令}的方法。<p>
* <b>不建议命令实现此接口,而是继承 {@link AbstractCommand}类</b>
*
* @author SpCo
* @version 1.1.0
* @see AbstractCommand
* @since 0.1.0
*/
public interface Command {
/**
* 命令的标签(或名称)<p>
* 如命令 {@code "/command arg"} 中,{@code "command"} 就是该命令的标签。<p>
* 命令的标签是一个数组。数组的第一个元素是主标签,其余都是别称。<p>
* 在使用 {@link HelpCommand} 时,会将别称的描述重定向到主标签。<p>
* 如:
* <pre>
* help - 显示帮助信息
* ? -> help
* </pre>
*/
String[] getLabels();
List<CommandUsage> getUsages();
/**
* 命令的描述
*
* @return 命令的描述
*/
String getDescriptions();
/**
* 命令的作用域
*
* @return 命令的作用域
* @see CommandScope
*/
CommandScope getScope();
/**
* 使用命令所需的最低权限等级<p>
* 注意:这里的最低权限指的是{@link BotUser 机器人用户}的{@link UserPermission 用户权限},而不是群聊中{@link Member 群成员}的{@link MemberPermission 成员权限}。
*
* @return 使用命令所需的最低权限等级
* @see UserPermission
*/ | UserPermission needPermission(); | 6 | 2023-10-26 10:27:47+00:00 | 8k |
cty1928/GreenTravel | src/Android/Maps-master/app/src/main/java/org/zarroboogs/maps/ui/navi/NaviRouteActivity.java | [
{
"identifier": "BJCamera",
"path": "src/Android/Maps-master/app/src/main/java-gen/org/zarroboogs/maps/beans/BJCamera.java",
"snippet": "public class BJCamera {\n\n private Long id;\n /** Not-null value. */\n private String name;\n private String address;\n private Double latitude;\n p... | import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviViewOptions;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import org.zarroboogs.maps.beans.BJCamera;
import org.zarroboogs.maps.ui.BaseActivity;
import org.zarroboogs.maps.ui.anim.AnimEndListener;
import org.zarroboogs.maps.ui.anim.ViewAnimUtils;
import org.zarroboogs.maps.ui.maps.MapsMainActivity;
import org.zarroboogs.maps.R;
import org.zarroboogs.maps.module.TTSController;
import org.zarroboogs.maps.presenters.MarkerInteractor;
import org.zarroboogs.maps.presenters.MarkerInteractorImpl;
import org.zarroboogs.maps.utils.SettingUtils;
import org.zarroboogs.maps.utils.Utils;
import java.util.ArrayList;
import java.util.List; | 6,710 | package org.zarroboogs.maps.ui.navi;
/**
* 路径规划结果展示界面
*/
public class NaviRouteActivity extends BaseActivity implements OnClickListener,
OnMapLoadedListener{
// View
private ImageButton mStartNaviButton;// 实时导航按钮
private MapView mMapView;// 地图控件
private ImageView mRouteBackView;// 返回按钮
private TextView mRouteDistanceView;// 距离显示控件
private TextView mRouteTimeView;// 时间显示控件
private TextView mRouteCostView;// 花费显示控件
private ListView mRoutSettingListView;
private TextView mShowRoutType;
// 地图导航资源
private AMap mAmap;
private AMapNavi mAmapNavi;
private RouteOverLay mRouteOverLay;
private boolean mIsMapLoaded = false;
private List<NaviLatLng> mEndNavi;
private List<NaviLatLng> mStartNavi;
public static final String NAVI_ENDS = "navi_ends";
public static final String NAVI_START = "navi_start";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route);
mEndNavi = getIntent().getParcelableArrayListExtra(NAVI_ENDS);
mStartNavi = getIntent().getParcelableArrayListExtra(NAVI_START);
Log.d("NaviRouteActivity ", "onCreate- " + mEndNavi.get(0).getLatitude());
initView(savedInstanceState);
mAmapNavi = AMapNavi.getInstance(this);
mAmapNavi.setAMapNaviListener(naviRouteListener);
boolean startGps = mAmapNavi.startGPS();
Log.d("NaviRouteActivity ", "onCreate- startGps- " + startGps);
boolean iscalDrive = mAmapNavi.calculateDriveRoute(mStartNavi, mEndNavi, null, AMapNavi.DrivingDefault);
Log.d("NaviRouteActivity ", "onCreate- calculateDriveRoute- " + iscalDrive);
if (SettingUtils.readCurrentCameraState() == SettingUtils.SWITCH_ON){ | package org.zarroboogs.maps.ui.navi;
/**
* 路径规划结果展示界面
*/
public class NaviRouteActivity extends BaseActivity implements OnClickListener,
OnMapLoadedListener{
// View
private ImageButton mStartNaviButton;// 实时导航按钮
private MapView mMapView;// 地图控件
private ImageView mRouteBackView;// 返回按钮
private TextView mRouteDistanceView;// 距离显示控件
private TextView mRouteTimeView;// 时间显示控件
private TextView mRouteCostView;// 花费显示控件
private ListView mRoutSettingListView;
private TextView mShowRoutType;
// 地图导航资源
private AMap mAmap;
private AMapNavi mAmapNavi;
private RouteOverLay mRouteOverLay;
private boolean mIsMapLoaded = false;
private List<NaviLatLng> mEndNavi;
private List<NaviLatLng> mStartNavi;
public static final String NAVI_ENDS = "navi_ends";
public static final String NAVI_START = "navi_start";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route);
mEndNavi = getIntent().getParcelableArrayListExtra(NAVI_ENDS);
mStartNavi = getIntent().getParcelableArrayListExtra(NAVI_START);
Log.d("NaviRouteActivity ", "onCreate- " + mEndNavi.get(0).getLatitude());
initView(savedInstanceState);
mAmapNavi = AMapNavi.getInstance(this);
mAmapNavi.setAMapNaviListener(naviRouteListener);
boolean startGps = mAmapNavi.startGPS();
Log.d("NaviRouteActivity ", "onCreate- startGps- " + startGps);
boolean iscalDrive = mAmapNavi.calculateDriveRoute(mStartNavi, mEndNavi, null, AMapNavi.DrivingDefault);
Log.d("NaviRouteActivity ", "onCreate- calculateDriveRoute- " + iscalDrive);
if (SettingUtils.readCurrentCameraState() == SettingUtils.SWITCH_ON){ | MarkerInteractor markerInteractor = new MarkerInteractorImpl(); | 6 | 2023-10-31 01:21:54+00:00 | 8k |
zxzf1234/jimmer-ruoyivuepro | backend/yudao-service/yudao-service-biz/src/main/java/cn/iocoder/yudao/service/convert/infra/oauth2/OAuth2OpenConvert.java | [
{
"identifier": "KeyValue",
"path": "backend/yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/core/KeyValue.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class KeyValue<K, V> {\n\n private K key;\n private V value;\n\n}"
},
{
"identif... | import cn.hutool.core.date.LocalDateTimeUtil;
import cn.iocoder.yudao.framework.common.core.KeyValue;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.service.vo.infra.oauth2.open.OAuth2OpenAccessTokenRespVO;
import cn.iocoder.yudao.service.vo.infra.oauth2.open.OAuth2OpenAuthorizeInfoRespVO;
import cn.iocoder.yudao.service.vo.infra.oauth2.open.OAuth2OpenCheckTokenRespVO;
import cn.iocoder.yudao.service.model.infra.oauth2.SystemOauth2AccessToken;
import cn.iocoder.yudao.service.model.infra.oauth2.SystemOauth2Approve;
import cn.iocoder.yudao.service.model.infra.oauth2.SystemOauth2Client;
import cn.iocoder.yudao.service.util.oauth2.OAuth2Utils;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | 5,967 | package cn.iocoder.yudao.service.convert.infra.oauth2;
@Mapper
public interface OAuth2OpenConvert {
OAuth2OpenConvert INSTANCE = Mappers.getMapper(OAuth2OpenConvert.class);
default OAuth2OpenAccessTokenRespVO convert(SystemOauth2AccessToken bean) {
OAuth2OpenAccessTokenRespVO respVO = convert0(bean);
respVO.setTokenType(SecurityFrameworkUtils.AUTHORIZATION_BEARER.toLowerCase());
respVO.setExpiresIn(OAuth2Utils.getExpiresIn(bean.expiresTime()));
respVO.setScope(OAuth2Utils.buildScopeStr(bean.scopes()));
return respVO;
}
OAuth2OpenAccessTokenRespVO convert0(SystemOauth2AccessToken bean);
default OAuth2OpenCheckTokenRespVO convert2(SystemOauth2AccessToken bean) {
OAuth2OpenCheckTokenRespVO respVO = convert3(bean);
respVO.setExp(LocalDateTimeUtil.toEpochMilli(bean.expiresTime()) / 1000L);
respVO.setUserType(UserTypeEnum.ADMIN.getValue());
return respVO;
}
OAuth2OpenCheckTokenRespVO convert3(SystemOauth2AccessToken bean);
default OAuth2OpenAuthorizeInfoRespVO convert(SystemOauth2Client client, List<SystemOauth2Approve> approves) {
// 构建 scopes
List<KeyValue<String, Boolean>> scopes = new ArrayList<>(client.scopes().size()); | package cn.iocoder.yudao.service.convert.infra.oauth2;
@Mapper
public interface OAuth2OpenConvert {
OAuth2OpenConvert INSTANCE = Mappers.getMapper(OAuth2OpenConvert.class);
default OAuth2OpenAccessTokenRespVO convert(SystemOauth2AccessToken bean) {
OAuth2OpenAccessTokenRespVO respVO = convert0(bean);
respVO.setTokenType(SecurityFrameworkUtils.AUTHORIZATION_BEARER.toLowerCase());
respVO.setExpiresIn(OAuth2Utils.getExpiresIn(bean.expiresTime()));
respVO.setScope(OAuth2Utils.buildScopeStr(bean.scopes()));
return respVO;
}
OAuth2OpenAccessTokenRespVO convert0(SystemOauth2AccessToken bean);
default OAuth2OpenCheckTokenRespVO convert2(SystemOauth2AccessToken bean) {
OAuth2OpenCheckTokenRespVO respVO = convert3(bean);
respVO.setExp(LocalDateTimeUtil.toEpochMilli(bean.expiresTime()) / 1000L);
respVO.setUserType(UserTypeEnum.ADMIN.getValue());
return respVO;
}
OAuth2OpenCheckTokenRespVO convert3(SystemOauth2AccessToken bean);
default OAuth2OpenAuthorizeInfoRespVO convert(SystemOauth2Client client, List<SystemOauth2Approve> approves) {
// 构建 scopes
List<KeyValue<String, Boolean>> scopes = new ArrayList<>(client.scopes().size()); | Map<String, SystemOauth2Approve> approveMap = CollectionUtils.convertMap(approves, SystemOauth2Approve::scope); | 2 | 2023-10-27 06:35:24+00:00 | 8k |
matheusmisumoto/workout-logger-api | src/main/java/dev/matheusmisumoto/workoutloggerapi/controller/WorkoutController.java | [
{
"identifier": "Workout",
"path": "src/main/java/dev/matheusmisumoto/workoutloggerapi/model/Workout.java",
"snippet": "@Entity\r\n@Table(name=\"workouts\")\r\npublic class Workout implements Serializable {\r\n\t\r\n\tprivate static final long serialVersionUID = 1L;\r\n\t\r\n\t@Id\r\n\t@GeneratedValue(s... | import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import dev.matheusmisumoto.workoutloggerapi.dto.PreviousStatsDTO;
import dev.matheusmisumoto.workoutloggerapi.dto.PreviousStatsWorkoutsDTO;
import dev.matheusmisumoto.workoutloggerapi.dto.WorkoutRecordDTO;
import dev.matheusmisumoto.workoutloggerapi.dto.WorkoutSetShowDTO;
import dev.matheusmisumoto.workoutloggerapi.model.Workout;
import dev.matheusmisumoto.workoutloggerapi.model.Exercise;
import dev.matheusmisumoto.workoutloggerapi.model.User;
import dev.matheusmisumoto.workoutloggerapi.repository.ExerciseRepository;
import dev.matheusmisumoto.workoutloggerapi.repository.UserRepository;
import dev.matheusmisumoto.workoutloggerapi.repository.WorkoutRepository;
import dev.matheusmisumoto.workoutloggerapi.repository.WorkoutSetRepository;
import dev.matheusmisumoto.workoutloggerapi.security.JWTService;
import dev.matheusmisumoto.workoutloggerapi.type.WorkoutStatusType;
import dev.matheusmisumoto.workoutloggerapi.util.WorkoutUtil;
import jakarta.servlet.http.HttpServletRequest;
| 4,568 | package dev.matheusmisumoto.workoutloggerapi.controller;
@RestController
@RequestMapping("/v1/workouts")
public class WorkoutController {
@Autowired
WorkoutRepository workoutRepository;
@Autowired
ExerciseRepository exerciseRepository;
@Autowired
WorkoutSetRepository workoutSetRepository;
@Autowired
UserRepository userRepository;
@Autowired
JWTService jwtService;
@PostMapping
public ResponseEntity<Object> saveWorkout(HttpServletRequest request,
@RequestBody WorkoutRecordDTO workoutRecordDTO) {
// Retrieve logged user ID from JWT
var token = request.getHeader("Authorization").replace("Bearer ", "");
var loggedUserId = UUID.fromString(jwtService.validateToken(token));
// Save metadata
| package dev.matheusmisumoto.workoutloggerapi.controller;
@RestController
@RequestMapping("/v1/workouts")
public class WorkoutController {
@Autowired
WorkoutRepository workoutRepository;
@Autowired
ExerciseRepository exerciseRepository;
@Autowired
WorkoutSetRepository workoutSetRepository;
@Autowired
UserRepository userRepository;
@Autowired
JWTService jwtService;
@PostMapping
public ResponseEntity<Object> saveWorkout(HttpServletRequest request,
@RequestBody WorkoutRecordDTO workoutRecordDTO) {
// Retrieve logged user ID from JWT
var token = request.getHeader("Authorization").replace("Bearer ", "");
var loggedUserId = UUID.fromString(jwtService.validateToken(token));
// Save metadata
| var workout = new Workout();
| 0 | 2023-10-29 23:18:38+00:00 | 8k |
jaszlo/Playerautoma | src/main/java/net/jasper/mod/util/keybinds/Constants.java | [
{
"identifier": "PlayerRecorder",
"path": "src/main/java/net/jasper/mod/automation/PlayerRecorder.java",
"snippet": "public class PlayerRecorder {\n\n private static final Logger LOGGER = PlayerAutomaClient.LOGGER;\n\n public static Recording record = new Recording();\n\n public static State st... | import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
import net.jasper.mod.automation.PlayerRecorder;
import net.jasper.mod.gui.PlayerAutomaMenu;
import net.jasper.mod.gui.RecordingSelector;
import net.jasper.mod.gui.RecordingStorer;
import net.minecraft.client.option.KeyBinding;
import net.minecraft.client.util.InputUtil;
import org.lwjgl.glfw.GLFW; | 5,763 | package net.jasper.mod.util.keybinds;
/**
* Class storing all KeyBinding-Constants
*/
public class Constants {
protected static final int AMOUNT_KEYBINDS = 8;
private static final String KEYBINDING_CATEGORY = "Playerautoma";
private static final String[] names = {
// Player Recoding Keybinds
"Start Recording",
"Stop Recording",
"Replay Recording",
"Cancel Replay",
"Loop Replay",
"Store Recording",
"Load Recording",
// Open Menu
"Open Mod Menu"
};
private static final KeyBinding[] bindings = {
// Player Recoding Keybinds
new KeyBinding(names[0], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_G, KEYBINDING_CATEGORY),
new KeyBinding(names[1], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_H, KEYBINDING_CATEGORY),
new KeyBinding(names[2], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_J, KEYBINDING_CATEGORY),
new KeyBinding(names[3], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_K, KEYBINDING_CATEGORY),
new KeyBinding(names[4], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_L, KEYBINDING_CATEGORY),
new KeyBinding(names[5], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_U, KEYBINDING_CATEGORY),
new KeyBinding(names[6], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_I, KEYBINDING_CATEGORY),
// Open Menu
new KeyBinding(names[7], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_O, KEYBINDING_CATEGORY)
};
public static final KeyBinding CANCEL_REPLAY = bindings[3];
private static final Runnable[] callbackMethods = {
// Player Recording Keybinds | package net.jasper.mod.util.keybinds;
/**
* Class storing all KeyBinding-Constants
*/
public class Constants {
protected static final int AMOUNT_KEYBINDS = 8;
private static final String KEYBINDING_CATEGORY = "Playerautoma";
private static final String[] names = {
// Player Recoding Keybinds
"Start Recording",
"Stop Recording",
"Replay Recording",
"Cancel Replay",
"Loop Replay",
"Store Recording",
"Load Recording",
// Open Menu
"Open Mod Menu"
};
private static final KeyBinding[] bindings = {
// Player Recoding Keybinds
new KeyBinding(names[0], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_G, KEYBINDING_CATEGORY),
new KeyBinding(names[1], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_H, KEYBINDING_CATEGORY),
new KeyBinding(names[2], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_J, KEYBINDING_CATEGORY),
new KeyBinding(names[3], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_K, KEYBINDING_CATEGORY),
new KeyBinding(names[4], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_L, KEYBINDING_CATEGORY),
new KeyBinding(names[5], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_U, KEYBINDING_CATEGORY),
new KeyBinding(names[6], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_I, KEYBINDING_CATEGORY),
// Open Menu
new KeyBinding(names[7], InputUtil.Type.KEYSYM, GLFW.GLFW_KEY_O, KEYBINDING_CATEGORY)
};
public static final KeyBinding CANCEL_REPLAY = bindings[3];
private static final Runnable[] callbackMethods = {
// Player Recording Keybinds | PlayerRecorder::startRecord, | 0 | 2023-10-25 11:30:02+00:00 | 8k |
SUFIAG/Hotel-Reservation-System-Java-And-PHP | src/app/src/main/java/com/sameetasadullah/i180479_i180531/presentationLayer/Hotel_Reservation_Screen.java | [
{
"identifier": "HRS",
"path": "src/app/src/main/java/com/sameetasadullah/i180479_i180531/logicLayer/HRS.java",
"snippet": "public class HRS {\n private Vector<Customer> customers;\n private Vector<Hotel> hotels;\n private Vector<Vendor> vendors;\n private writerAndReader readAndWrite;\n ... | import androidx.appcompat.app.AppCompatActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.sameetasadullah.i180479_i180531.R;
import com.sameetasadullah.i180479_i180531.logicLayer.HRS;
import com.sameetasadullah.i180479_i180531.logicLayer.Hotel;
import com.sameetasadullah.i180479_i180531.logicLayer.Reservation;
import com.sameetasadullah.i180479_i180531.logicLayer.Room;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Vector; | 5,353 | package com.sameetasadullah.i180479_i180531.presentationLayer;
public class Hotel_Reservation_Screen extends AppCompatActivity {
RelativeLayout endButton;
TextView hotelName,rooms,totalPrice,totalRooms;
HRS hrs;
String Email,checkInDate,checkOutDate,HotelName,HotelLocation;
Hotel h1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_reservation_screen);
hotelName = findViewById(R.id.tv_hotel_name);
rooms = findViewById(R.id.tv_rooms);
totalPrice = findViewById(R.id.tv_total_price);
totalRooms = findViewById(R.id.tv_total_rooms);
endButton = findViewById(R.id.END_button);
hrs = HRS.getInstance(Hotel_Reservation_Screen.this);
Email = getIntent().getStringExtra("Email");
HotelName = getIntent().getStringExtra("Hotel_name");
HotelLocation = getIntent().getStringExtra("Hotel_Loc");
checkInDate = getIntent().getStringExtra("checkinDate");
checkOutDate = getIntent().getStringExtra("checkOutDate");
h1 = hrs.searchHotelByNameLoc(HotelName,HotelLocation);
| package com.sameetasadullah.i180479_i180531.presentationLayer;
public class Hotel_Reservation_Screen extends AppCompatActivity {
RelativeLayout endButton;
TextView hotelName,rooms,totalPrice,totalRooms;
HRS hrs;
String Email,checkInDate,checkOutDate,HotelName,HotelLocation;
Hotel h1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hotel_reservation_screen);
hotelName = findViewById(R.id.tv_hotel_name);
rooms = findViewById(R.id.tv_rooms);
totalPrice = findViewById(R.id.tv_total_price);
totalRooms = findViewById(R.id.tv_total_rooms);
endButton = findViewById(R.id.END_button);
hrs = HRS.getInstance(Hotel_Reservation_Screen.this);
Email = getIntent().getStringExtra("Email");
HotelName = getIntent().getStringExtra("Hotel_name");
HotelLocation = getIntent().getStringExtra("Hotel_Loc");
checkInDate = getIntent().getStringExtra("checkinDate");
checkOutDate = getIntent().getStringExtra("checkOutDate");
h1 = hrs.searchHotelByNameLoc(HotelName,HotelLocation);
| Vector<Reservation> res= h1.getReservations(); | 2 | 2023-10-25 20:58:45+00:00 | 8k |
achmaddaniel24/kupass | app/src/main/java/com/achmaddaniel/kupass/activity/HomePage.java | [
{
"identifier": "ListAdapter",
"path": "app/src/main/java/com/achmaddaniel/kupass/adapter/ListAdapter.java",
"snippet": "public class ListAdapter extends BaseAdapter {\n\t\n\tprivate ArrayList<ListItem> mList;\n\tprivate Context mContext;\n\t\n\tpublic ListAdapter(Context context) {\n\t\tmContext = cont... | import com.achmaddaniel.kupass.R;
import com.achmaddaniel.kupass.adapter.ListAdapter;
import com.achmaddaniel.kupass.adapter.ListItem;
import com.achmaddaniel.kupass.database.Preference;
import com.achmaddaniel.kupass.database.SQLDataHelper;
import com.achmaddaniel.kupass.core.ConstantVar;
import com.achmaddaniel.kupass.core.FilePermissionHandler;
import com.achmaddaniel.kupass.core.FileUtil;
import com.achmaddaniel.kupass.core.Password;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.appcompat.widget.SearchView;
import androidx.core.content.ContextCompat;
import androidx.annotation.Nullable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.view.View;
import android.view.LayoutInflater;
import android.view.animation.AnimationUtils;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
import java.util.ArrayList; | 5,583 | mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
}
ArrayList<ListItem> filter = new ArrayList<>();
for(ListItem item : mListItem)
if(item.getPasswordName().toLowerCase().contains(newText.toLowerCase()))
filter.add(item);
if(!filter.isEmpty())
mAdapter.setFilteredList(filter);
return true;
}
});
update();
}
private void update() {
mListItem = mSQL.getAll();
mAdapter.setList(mListItem);
if(!(mListItem.size() > 0))
mListView.setBackgroundColor(getResources().getColor(R.color.transparent));
else
mListView.setBackgroundResource(R.drawable.list_item_background);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener((adapter, view, position, id) -> {
ListItem currentItem = mAdapter.getCurrentItem(position);
final View inflater = LayoutInflater.from(HomePage.this).inflate(R.layout.dialog_layout, null);
((TextInputEditText)inflater.findViewById(R.id.password_name)).setText(currentItem.getPasswordName());
((TextInputEditText)inflater.findViewById(R.id.username)).setText(currentItem.getUserName());
((TextInputEditText)inflater.findViewById(R.id.password)).setText(currentItem.getPassword());
((TextInputEditText)inflater.findViewById(R.id.note)).setText(currentItem.getNote());
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_edit))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_save), (dialog, which) -> {
final String passwordName = ((TextInputEditText)inflater.findViewById(R.id.password_name)).getText().toString();
final String username = ((TextInputEditText)inflater.findViewById(R.id.username)).getText().toString();
final String password = ((TextInputEditText)inflater.findViewById(R.id.password)).getText().toString();
final String note = ((TextInputEditText)inflater.findViewById(R.id.note)).getText().toString();
mSQL.update(currentItem.getId(), passwordName, username, password, note);
showToast(getString(R.string.toast_success_update));
if(mIsFabClicked) {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
}
update();
})
.setView(inflater)
.create()
.show();
});
mListView.setOnItemLongClickListener((adapter, view, position, id) -> {
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_delete))
.setMessage(getString(R.string.dialog_message_delete))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_delete), (dialog, which) -> {
mSQL.delete(mListItem.get(position).getId());
showToast(getString(R.string.toast_success_delete));
update();
})
.create()
.show();
return true;
});
}
// Handle FAB onClickListener
private void fabHandle() {
mFab.setOnClickListener((view) -> {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
});
mCreatePassFab.setOnClickListener((view) -> {
final View inflater = LayoutInflater.from(HomePage.this).inflate(R.layout.dialog_layout, null);
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_create))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_create), (dialog, which) -> {
final String passwordName = ((TextInputEditText)inflater.findViewById(R.id.password_name)).getText().toString();
final String username = ((TextInputEditText)inflater.findViewById(R.id.username)).getText().toString();
final String password = ((TextInputEditText)inflater.findViewById(R.id.password)).getText().toString();
final String note = ((TextInputEditText)inflater.findViewById(R.id.note)).getText().toString();
mSQL.create(passwordName, username, password, note);
showToast(getString(R.string.toast_success));
if(mIsFabClicked) {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
}
update();
})
.setView(inflater)
.create()
.show();
});
// Export
mExportFab.setOnClickListener((view) -> {
if(!(mListItem.size() > 0)) {
setFabVisibility(false);
showToast(getString(R.string.toast_no_data));
return;
}
CharSequence[] listExport = getResources().getStringArray(R.array.export_method_list);
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_export))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_export), (dialog, which) -> {
checkPermission();
if(mPermissionHandler.checkReadWritePermission()) {
ArrayList<Password> listPassword = new ArrayList<>();
for(ListItem item : mListItem)
listPassword.add(new Password(item)); | package com.achmaddaniel.kupass.activity;
public class HomePage extends AppCompatActivity {
// Initialize widget variable
private SearchView mSearchView;
private FloatingActionButton mFab;
private FloatingActionButton mCreatePassFab;
private FloatingActionButton mExportFab;
private FloatingActionButton mSettingsFab;
private FilePermissionHandler mPermissionHandler;
private boolean mIsFabClicked = false;
private ListAdapter mAdapter;
private ArrayList<ListItem> mListItem;
private SQLDataHelper mSQL;
private ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
checkPermission();
initialisation();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mPermissionHandler.onActivityResult(requestCode, resultCode, data);
}
private void initialisation() {
Preference.init(this);
mSQL = new SQLDataHelper(this);
mAdapter = new ListAdapter(this);
mListItem = new ArrayList<>();
mListView = findViewById(R.id.list_view);
// Init language
Resources res = getResources();
Configuration config = res.getConfiguration();
switch(Preference.getLanguage()) {
case ConstantVar.LANG_EN:
config.setLocale(Locale.getDefault());
break;
case ConstantVar.LANG_IN:
config.setLocale(new Locale("in"));
break;
}
res.updateConfiguration(config, res.getDisplayMetrics());
// Theme
switch(Preference.getTheme()) {
case ConstantVar.THEME_SYSTEM:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
break;
case ConstantVar.THEME_LIGHT:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
break;
case ConstantVar.THEME_DARK:
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
break;
}
// FAB Initialisation
mFab = findViewById(R.id.fab);
mCreatePassFab = findViewById(R.id.fab_add);
mExportFab = findViewById(R.id.fab_export);
mSettingsFab = findViewById(R.id.fab_settings);
fabHandle();
setFabVisibility(false);
// Search function
mSearchView = findViewById(R.id.search_view);
mSearchView.clearFocus();
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
if(mIsFabClicked) {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
}
ArrayList<ListItem> filter = new ArrayList<>();
for(ListItem item : mListItem)
if(item.getPasswordName().toLowerCase().contains(newText.toLowerCase()))
filter.add(item);
if(!filter.isEmpty())
mAdapter.setFilteredList(filter);
return true;
}
});
update();
}
private void update() {
mListItem = mSQL.getAll();
mAdapter.setList(mListItem);
if(!(mListItem.size() > 0))
mListView.setBackgroundColor(getResources().getColor(R.color.transparent));
else
mListView.setBackgroundResource(R.drawable.list_item_background);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener((adapter, view, position, id) -> {
ListItem currentItem = mAdapter.getCurrentItem(position);
final View inflater = LayoutInflater.from(HomePage.this).inflate(R.layout.dialog_layout, null);
((TextInputEditText)inflater.findViewById(R.id.password_name)).setText(currentItem.getPasswordName());
((TextInputEditText)inflater.findViewById(R.id.username)).setText(currentItem.getUserName());
((TextInputEditText)inflater.findViewById(R.id.password)).setText(currentItem.getPassword());
((TextInputEditText)inflater.findViewById(R.id.note)).setText(currentItem.getNote());
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_edit))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_save), (dialog, which) -> {
final String passwordName = ((TextInputEditText)inflater.findViewById(R.id.password_name)).getText().toString();
final String username = ((TextInputEditText)inflater.findViewById(R.id.username)).getText().toString();
final String password = ((TextInputEditText)inflater.findViewById(R.id.password)).getText().toString();
final String note = ((TextInputEditText)inflater.findViewById(R.id.note)).getText().toString();
mSQL.update(currentItem.getId(), passwordName, username, password, note);
showToast(getString(R.string.toast_success_update));
if(mIsFabClicked) {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
}
update();
})
.setView(inflater)
.create()
.show();
});
mListView.setOnItemLongClickListener((adapter, view, position, id) -> {
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_delete))
.setMessage(getString(R.string.dialog_message_delete))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_delete), (dialog, which) -> {
mSQL.delete(mListItem.get(position).getId());
showToast(getString(R.string.toast_success_delete));
update();
})
.create()
.show();
return true;
});
}
// Handle FAB onClickListener
private void fabHandle() {
mFab.setOnClickListener((view) -> {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
});
mCreatePassFab.setOnClickListener((view) -> {
final View inflater = LayoutInflater.from(HomePage.this).inflate(R.layout.dialog_layout, null);
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_create))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_create), (dialog, which) -> {
final String passwordName = ((TextInputEditText)inflater.findViewById(R.id.password_name)).getText().toString();
final String username = ((TextInputEditText)inflater.findViewById(R.id.username)).getText().toString();
final String password = ((TextInputEditText)inflater.findViewById(R.id.password)).getText().toString();
final String note = ((TextInputEditText)inflater.findViewById(R.id.note)).getText().toString();
mSQL.create(passwordName, username, password, note);
showToast(getString(R.string.toast_success));
if(mIsFabClicked) {
mIsFabClicked = !mIsFabClicked;
setFabVisibility(mIsFabClicked);
}
update();
})
.setView(inflater)
.create()
.show();
});
// Export
mExportFab.setOnClickListener((view) -> {
if(!(mListItem.size() > 0)) {
setFabVisibility(false);
showToast(getString(R.string.toast_no_data));
return;
}
CharSequence[] listExport = getResources().getStringArray(R.array.export_method_list);
new MaterialAlertDialogBuilder(HomePage.this)
.setTitle(getString(R.string.dialog_title_export))
.setNegativeButton(getString(R.string.dialog_cancel), (dialog, which) -> {
})
.setPositiveButton(getString(R.string.dialog_export), (dialog, which) -> {
checkPermission();
if(mPermissionHandler.checkReadWritePermission()) {
ArrayList<Password> listPassword = new ArrayList<>();
for(ListItem item : mListItem)
listPassword.add(new Password(item)); | FileUtil data = new FileUtil(listPassword); | 6 | 2023-10-26 20:28:08+00:00 | 8k |
MachineMC/Cogwheel | cogwheel-core/src/main/java/org/machinemc/cogwheel/serialization/Serializers.java | [
{
"identifier": "DataVisitor",
"path": "cogwheel-core/src/main/java/org/machinemc/cogwheel/DataVisitor.java",
"snippet": "public interface DataVisitor {\n\n int READ_ACCESS = 0x01, WRITE_ACCESS = 0x02, FULL_ACCESS = READ_ACCESS | WRITE_ACCESS;\n\n @Contract(\"_ -> this\")\n DataVisitor visit(St... | import org.jetbrains.annotations.Nullable;
import org.machinemc.cogwheel.DataVisitor;
import org.machinemc.cogwheel.ErrorHandler;
import org.machinemc.cogwheel.config.*;
import org.machinemc.cogwheel.util.ArrayUtils;
import org.machinemc.cogwheel.util.JavaUtils;
import org.machinemc.cogwheel.util.NumberUtils;
import org.machinemc.cogwheel.util.classbuilder.ClassBuilder;
import org.machinemc.cogwheel.util.classbuilder.ObjectBuilder;
import org.machinemc.cogwheel.util.classbuilder.RecordBuilder;
import org.machinemc.cogwheel.util.error.ErrorContainer;
import org.machinemc.cogwheel.util.error.ErrorEntry;
import org.machinemc.cogwheel.util.error.ErrorType;
import java.io.File;
import java.lang.reflect.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Path;
import java.time.Instant;
import java.util.*;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.stream.Stream; | 6,960 | package org.machinemc.cogwheel.serialization;
public class Serializers {
public static <T extends Serializer<?>> T newSerializer(Class<T> serializerClass, SerializerContext context) {
if (JavaUtils.hasConstructor(serializerClass, SerializerContext.class)) | package org.machinemc.cogwheel.serialization;
public class Serializers {
public static <T extends Serializer<?>> T newSerializer(Class<T> serializerClass, SerializerContext context) {
if (JavaUtils.hasConstructor(serializerClass, SerializerContext.class)) | return JavaUtils.newInstance(serializerClass, ArrayUtils.array(SerializerContext.class), context); | 2 | 2023-10-25 11:31:02+00:00 | 8k |
frc7787/FTC-Centerstage | TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/drive/opmode/TrackingWheelLateralDistanceTuner.java | [
{
"identifier": "SampleMecanumDrive",
"path": "TeamCode/src/main/java/org/firstinspires/ftc/teamcode/RoadRunner/drive/SampleMecanumDrive.java",
"snippet": "@Config\npublic class SampleMecanumDrive extends MecanumDrive {\n public static PIDCoefficients TRANSLATIONAL_PID_FB = new PIDCoefficients(0, 0, ... | import com.acmerobotics.dashboard.config.Config;
import com.acmerobotics.roadrunner.geometry.Pose2d;
import com.acmerobotics.roadrunner.util.Angle;
import com.qualcomm.robotcore.eventloop.opmode.Disabled;
import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode;
import com.qualcomm.robotcore.eventloop.opmode.TeleOp;
import com.qualcomm.robotcore.util.RobotLog;
import org.firstinspires.ftc.teamcode.RoadRunner.drive.SampleMecanumDrive;
import org.firstinspires.ftc.teamcode.RoadRunner.drive.StandardTrackingWheelLocalizer; | 4,192 | package org.firstinspires.ftc.teamcode.RoadRunner.drive.opmode;
/**
* Opmode designed to assist the user in tuning the `StandardTrackingWheelLocalizer`'s
* LATERAL_DISTANCE value. The LATERAL_DISTANCE is the center-to-center distance of the parallel
* wheels.
*
* Tuning Routine:
*
* 1. Set the LATERAL_DISTANCE value in StandardTrackingWheelLocalizer.java to the physical
* measured value. This need only be an estimated value as you will be tuning it anyways.
*
* 2. Make a mark on the bot (with a piece of tape or sharpie or however you wish) and make an
* similar mark right below the indicator on your bot. This will be your reference point to
* ensure you've turned exactly 360°.
*
* 3. Although not entirely necessary, having the bot's pose being drawn in dashbooard does help
* identify discrepancies in the LATERAL_DISTANCE value. To access the dashboard,
* connect your computer to the RC's WiFi network. In your browser, navigate to
* https://192.168.49.1:8080/dash if you're using the RC phone or https://192.168.43.1:8080/dash
* if you are using the Control Hub.
* Ensure the field is showing (select the field view in top right of the page).
*
* 4. Press play to begin the tuning routine.
*
* 5. Use the right joystick on gamepad 1 to turn the bot counterclockwise.
*
* 6. Spin the bot 10 times, counterclockwise. Make sure to keep track of these turns.
*
* 7. Once the bot has finished spinning 10 times, press A to finishing the routine. The indicators
* on the bot and on the ground you created earlier should be lined up.
*
* 8. Your effective LATERAL_DISTANCE will be given. Stick this value into your
* StandardTrackingWheelLocalizer.java class.
*
* 9. If this value is incorrect, run the routine again while adjusting the LATERAL_DISTANCE value
* yourself. Read the heading output and follow the advice stated in the note below to manually
* nudge the values yourself.
*
* Note:
* It helps to pay attention to how the pose on the field is drawn in dashboard. A blue circle with
* a line from the circumference to the center should be present, representing the bot. The line
* indicates forward. If your LATERAL_DISTANCE value is tuned currently, the pose drawn in
* dashboard should keep track with the pose of your actual bot. If the drawn bot turns slower than
* the actual bot, the LATERAL_DISTANCE should be decreased. If the drawn bot turns faster than the
* actual bot, the LATERAL_DISTANCE should be increased.
*
* If your drawn bot oscillates around a point in dashboard, don't worry. This is because the
* position of the perpendicular wheel isn't perfectly set and causes a discrepancy in the
* effective center of rotation. You can ignore this effect. The center of rotation will be offset
* slightly but your heading will still be fine. This does not affect your overall tracking
* precision. The heading should still line up.
*/
@Config
@TeleOp(name = "Tracking Wheel Lateral Distance Tuner", group = "drive")
@Disabled
public class TrackingWheelLateralDistanceTuner extends LinearOpMode {
public static int NUM_TURNS = 10;
@Override
public void runOpMode() throws InterruptedException { | package org.firstinspires.ftc.teamcode.RoadRunner.drive.opmode;
/**
* Opmode designed to assist the user in tuning the `StandardTrackingWheelLocalizer`'s
* LATERAL_DISTANCE value. The LATERAL_DISTANCE is the center-to-center distance of the parallel
* wheels.
*
* Tuning Routine:
*
* 1. Set the LATERAL_DISTANCE value in StandardTrackingWheelLocalizer.java to the physical
* measured value. This need only be an estimated value as you will be tuning it anyways.
*
* 2. Make a mark on the bot (with a piece of tape or sharpie or however you wish) and make an
* similar mark right below the indicator on your bot. This will be your reference point to
* ensure you've turned exactly 360°.
*
* 3. Although not entirely necessary, having the bot's pose being drawn in dashbooard does help
* identify discrepancies in the LATERAL_DISTANCE value. To access the dashboard,
* connect your computer to the RC's WiFi network. In your browser, navigate to
* https://192.168.49.1:8080/dash if you're using the RC phone or https://192.168.43.1:8080/dash
* if you are using the Control Hub.
* Ensure the field is showing (select the field view in top right of the page).
*
* 4. Press play to begin the tuning routine.
*
* 5. Use the right joystick on gamepad 1 to turn the bot counterclockwise.
*
* 6. Spin the bot 10 times, counterclockwise. Make sure to keep track of these turns.
*
* 7. Once the bot has finished spinning 10 times, press A to finishing the routine. The indicators
* on the bot and on the ground you created earlier should be lined up.
*
* 8. Your effective LATERAL_DISTANCE will be given. Stick this value into your
* StandardTrackingWheelLocalizer.java class.
*
* 9. If this value is incorrect, run the routine again while adjusting the LATERAL_DISTANCE value
* yourself. Read the heading output and follow the advice stated in the note below to manually
* nudge the values yourself.
*
* Note:
* It helps to pay attention to how the pose on the field is drawn in dashboard. A blue circle with
* a line from the circumference to the center should be present, representing the bot. The line
* indicates forward. If your LATERAL_DISTANCE value is tuned currently, the pose drawn in
* dashboard should keep track with the pose of your actual bot. If the drawn bot turns slower than
* the actual bot, the LATERAL_DISTANCE should be decreased. If the drawn bot turns faster than the
* actual bot, the LATERAL_DISTANCE should be increased.
*
* If your drawn bot oscillates around a point in dashboard, don't worry. This is because the
* position of the perpendicular wheel isn't perfectly set and causes a discrepancy in the
* effective center of rotation. You can ignore this effect. The center of rotation will be offset
* slightly but your heading will still be fine. This does not affect your overall tracking
* precision. The heading should still line up.
*/
@Config
@TeleOp(name = "Tracking Wheel Lateral Distance Tuner", group = "drive")
@Disabled
public class TrackingWheelLateralDistanceTuner extends LinearOpMode {
public static int NUM_TURNS = 10;
@Override
public void runOpMode() throws InterruptedException { | SampleMecanumDrive drive = new SampleMecanumDrive(hardwareMap); | 0 | 2023-10-31 16:06:46+00:00 | 8k |
Fuzss/diagonalwalls | 1.18/Common/src/main/java/fuzs/diagonalwindows/world/level/block/StarCollisionBlock.java | [
{
"identifier": "DiagonalWindows",
"path": "1.18/Common/src/main/java/fuzs/diagonalwindows/DiagonalWindows.java",
"snippet": "public class DiagonalWindows implements ModConstructor {\n public static final String MOD_ID = \"diagonalwindows\";\n public static final String MOD_NAME = \"Diagonal Windo... | import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import fuzs.diagonalwindows.DiagonalWindows;
import fuzs.diagonalwindows.api.world.level.block.DiagonalBlock;
import fuzs.diagonalwindows.api.world.level.block.EightWayDirection;
import fuzs.diagonalwindows.world.phys.shapes.NoneVoxelShape;
import fuzs.diagonalwindows.world.phys.shapes.VoxelCollection;
import fuzs.diagonalwindows.world.phys.shapes.VoxelUtils;
import net.minecraft.Util;
import net.minecraft.core.BlockPos;
import net.minecraft.core.Direction;
import net.minecraft.world.level.BlockGetter;
import net.minecraft.world.level.LevelAccessor;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.CrossCollisionBlock;
import net.minecraft.world.level.block.PipeBlock;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.block.state.StateDefinition;
import net.minecraft.world.level.block.state.properties.BooleanProperty;
import net.minecraft.world.level.material.FluidState;
import net.minecraft.world.level.material.Fluids;
import net.minecraft.world.phys.Vec3;
import net.minecraft.world.phys.shapes.Shapes;
import net.minecraft.world.phys.shapes.VoxelShape;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream; | 3,905 | package fuzs.diagonalwindows.world.level.block;
public interface StarCollisionBlock extends DiagonalBlock {
/**
* calculating shape unions is rather expensive, and since {@link VoxelShape} is immutable we use a cache for all diagonal blocks with the same shape
*/
Map<List<Float>, VoxelShape[]> DIMENSIONS_TO_SHAPE_CACHE = Maps.newHashMap(); | package fuzs.diagonalwindows.world.level.block;
public interface StarCollisionBlock extends DiagonalBlock {
/**
* calculating shape unions is rather expensive, and since {@link VoxelShape} is immutable we use a cache for all diagonal blocks with the same shape
*/
Map<List<Float>, VoxelShape[]> DIMENSIONS_TO_SHAPE_CACHE = Maps.newHashMap(); | Map<EightWayDirection, BooleanProperty> DIRECTION_TO_PROPERTY_MAP = Util.make(Maps.newEnumMap(EightWayDirection.class), (directions) -> { | 2 | 2023-10-27 09:06:16+00:00 | 8k |
slatepowered/slate | slate-common/src/main/java/slatepowered/slate/packages/key/URLFilesDownload.java | [
{
"identifier": "Logger",
"path": "slate-common/src/main/java/slatepowered/slate/logging/Logger.java",
"snippet": "public interface Logger {\r\n\r\n /* Information */\r\n void info(Object... msg);\r\n default void info(Supplier<Object> msg) { info(msg.get()); }\r\n\r\n /* Warnings */\r\n ... | import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import slatepowered.slate.logging.Logger;
import slatepowered.slate.logging.Logging;
import slatepowered.slate.packages.PackageKey;
import slatepowered.slate.packages.PackageManager;
import slatepowered.slate.packages.local.LocalFilesPackage;
import slatepowered.veru.data.Pair;
import slatepowered.veru.io.IOUtil;
import slatepowered.veru.misc.Throwables;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
| 3,693 | package slatepowered.slate.packages.key;
/**
* A resolved package key which downloads a file.
*/
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class URLFilesDownload extends ResolvedPackageKeyUnion<URLFilesDownload, LocalFilesPackage> {
| package slatepowered.slate.packages.key;
/**
* A resolved package key which downloads a file.
*/
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class URLFilesDownload extends ResolvedPackageKeyUnion<URLFilesDownload, LocalFilesPackage> {
| private static final Logger LOGGER = Logging.getLogger("URLFilesDownload");
| 0 | 2023-10-30 08:58:02+00:00 | 8k |
Ax3dGaming/Sons-Of-Sins-Organs-Addition | src/main/java/com/axed/compat/JEISosorgansPlugin.java | [
{
"identifier": "ModBlocks",
"path": "src/main/java/com/axed/block/ModBlocks.java",
"snippet": "public class ModBlocks {\n public static final DeferredRegister<Block> BLOCKS =\n DeferredRegister.create(ForgeRegistries.BLOCKS, sosorgans.MODID);\n\n public static final RegistryObject<Bloc... | import com.axed.block.ModBlocks;
import com.axed.block.entity.ModBlockEntities;
import com.axed.recipe.ModRecipes;
import com.axed.recipe.OrganCreatorRecipe;
import com.axed.screen.ModMenuTypes;
import com.axed.screen.OrganCreatorMenu;
import com.axed.screen.OrganCreatorScreen;
import com.axed.sosorgans;
import mezz.jei.api.IModPlugin;
import mezz.jei.api.JeiPlugin;
import mezz.jei.api.registration.*;
import net.minecraft.client.Minecraft;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.RecipeManager;
import java.util.List; | 4,132 | package com.axed.compat;
@JeiPlugin
public class JEISosorgansPlugin implements IModPlugin {
@Override
public ResourceLocation getPluginUid() {
return new ResourceLocation(sosorgans.MODID, "jei_plugin");
}
@Override
public void registerCategories(IRecipeCategoryRegistration registration) {
registration.addRecipeCategories(new OrganCreationCategory(registration.getJeiHelpers().getGuiHelper()));
}
public void registerRecipeTransferHandlers(IRecipeTransferRegistration registration) {
registration.addRecipeTransferHandler(OrganCreatorMenu.class, ModMenuTypes.ORGAN_CREATOR_MENU.get(), OrganCreationCategory.ORGAN_CREATION_TYPE, 36, 2, 0, 36);
}
@Override
public void registerRecipeCatalysts(IRecipeCatalystRegistration registration) {
registration.addRecipeCatalyst(new ItemStack(ModBlocks.ORGAN_CREATOR.get()), OrganCreationCategory.ORGAN_CREATION_TYPE);
}
@Override
public void registerRecipes(IRecipeRegistration registration) {
RecipeManager recipeManager = Minecraft.getInstance().level.getRecipeManager();
| package com.axed.compat;
@JeiPlugin
public class JEISosorgansPlugin implements IModPlugin {
@Override
public ResourceLocation getPluginUid() {
return new ResourceLocation(sosorgans.MODID, "jei_plugin");
}
@Override
public void registerCategories(IRecipeCategoryRegistration registration) {
registration.addRecipeCategories(new OrganCreationCategory(registration.getJeiHelpers().getGuiHelper()));
}
public void registerRecipeTransferHandlers(IRecipeTransferRegistration registration) {
registration.addRecipeTransferHandler(OrganCreatorMenu.class, ModMenuTypes.ORGAN_CREATOR_MENU.get(), OrganCreationCategory.ORGAN_CREATION_TYPE, 36, 2, 0, 36);
}
@Override
public void registerRecipeCatalysts(IRecipeCatalystRegistration registration) {
registration.addRecipeCatalyst(new ItemStack(ModBlocks.ORGAN_CREATOR.get()), OrganCreationCategory.ORGAN_CREATION_TYPE);
}
@Override
public void registerRecipes(IRecipeRegistration registration) {
RecipeManager recipeManager = Minecraft.getInstance().level.getRecipeManager();
| List<OrganCreatorRecipe> organRecipes = recipeManager.getAllRecipesFor(OrganCreatorRecipe.Type.INSTANCE); | 3 | 2023-10-25 19:33:18+00:00 | 8k |
gianlucameloni/shelly-em | src/main/java/com/gmeloni/shelly/service/ScheduledService.java | [
{
"identifier": "GetEMStatusResponse",
"path": "src/main/java/com/gmeloni/shelly/dto/rest/GetEMStatusResponse.java",
"snippet": "@Data\npublic class GetEMStatusResponse {\n @JsonProperty(\"unixtime\")\n private Long unixTime;\n @JsonProperty(\"emeters\")\n private List<RawEMSample> rawEMSamp... | import com.gmeloni.shelly.dto.rest.GetEMStatusResponse;
import com.gmeloni.shelly.model.HourlyEMEnergy;
import com.gmeloni.shelly.model.RawEMData;
import com.gmeloni.shelly.repository.HourlyEMEnergyRepository;
import com.gmeloni.shelly.repository.RawEMDataRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.TimeZone;
import static com.gmeloni.shelly.Constants.DATE_AND_TIME_FORMAT; | 3,883 | package com.gmeloni.shelly.service;
@Service
public class ScheduledService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final DateTimeFormatter sampleFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT);
private final DateTimeFormatter hourlyAggregationFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT);
@Autowired
private RawEMDataService rawEMDataService;
@Autowired
private RawEMDataRepository rawEmDataRepository;
@Autowired
private HourlyEMEnergyRepository hourlyEMEnergyRepository;
@Value("${raw-em.sampling.period.milliseconds}")
private String samplingPeriodInMilliseconds;
@Value("${raw-em.sampling.threshold}")
private Double samplingThreshold;
@Scheduled(fixedRateString = "${raw-em.sampling.period.milliseconds}")
public void processRawEMData() {
GetEMStatusResponse getEMStatusResponse = rawEMDataService.getRawEMSamples();
LocalDateTime sampleDateTime = LocalDateTime.ofInstant(
Instant.ofEpochSecond(getEMStatusResponse.getUnixTime()),
TimeZone.getTimeZone("Europe/Rome").toZoneId()
);
Double gridPower = getEMStatusResponse.getRawEMSamples().get(0).getPower();
Double pvPower = getEMStatusResponse.getRawEMSamples().get(1).getPower();
Double gridVoltage = getEMStatusResponse.getRawEMSamples().get(0).getVoltage();
Double pvVoltage = getEMStatusResponse.getRawEMSamples().get(1).getVoltage();
RawEMData rawEmData = new RawEMData(
sampleDateTime,
gridPower,
pvPower,
gridVoltage,
pvVoltage
);
rawEmDataRepository.save(rawEmData);
log.info("Saved raw EM data: [{}, {}, {}, {}, {}]", sampleFormatter.format(sampleDateTime), String.format("%.2f", gridPower), String.format("%.2f", pvPower), String.format("%.2f", gridVoltage), String.format("%.2f", pvVoltage));
}
@Scheduled(cron = "${raw-em.hourly-aggregate.cron.schedule}", zone = "Europe/Rome")
public void processHourlyAggregatedData() {
final double dt = Double.parseDouble(samplingPeriodInMilliseconds) / 1000 / 3600;
LocalDateTime fromTimestamp = LocalDateTime.now().minusHours(1).truncatedTo(ChronoUnit.HOURS);
LocalDateTime toTimestamp = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS);
List<RawEMData> rawEMDataSamples = rawEmDataRepository.findAllBySampleTimestampBetween(fromTimestamp, toTimestamp);
Double gridEnergyIn = rawEMDataSamples
.stream()
.filter(s -> (s.getGridPower() > samplingThreshold))
.mapToDouble(d -> d.getGridPower() * dt)
.sum();
Double gridEnergyOut = rawEMDataSamples
.stream()
.filter(s -> (s.getGridPower() < -1 * samplingThreshold))
.mapToDouble(d -> Math.abs(d.getGridPower()) * dt)
.sum();
Double pvEnergyIn = rawEMDataSamples
.stream()
.filter(s -> (s.getPvPower() > samplingThreshold))
.mapToDouble(d -> d.getPvPower() * dt)
.sum();
Double pvEnergyOut = rawEMDataSamples
.stream()
.filter(s -> (s.getPvPower() < -1 * samplingThreshold))
.mapToDouble(d -> Math.abs(d.getPvPower()) * dt)
.sum();
Double maxGridVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getGridVoltage())
.max()
.getAsDouble();
Double minGridVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getGridVoltage())
.min()
.getAsDouble();
Double maxPvVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getPvVoltage())
.max()
.getAsDouble();
Double minPvVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getPvVoltage())
.min()
.getAsDouble(); | package com.gmeloni.shelly.service;
@Service
public class ScheduledService {
private final Logger log = LoggerFactory.getLogger(this.getClass());
private final DateTimeFormatter sampleFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT);
private final DateTimeFormatter hourlyAggregationFormatter = DateTimeFormatter.ofPattern(DATE_AND_TIME_FORMAT);
@Autowired
private RawEMDataService rawEMDataService;
@Autowired
private RawEMDataRepository rawEmDataRepository;
@Autowired
private HourlyEMEnergyRepository hourlyEMEnergyRepository;
@Value("${raw-em.sampling.period.milliseconds}")
private String samplingPeriodInMilliseconds;
@Value("${raw-em.sampling.threshold}")
private Double samplingThreshold;
@Scheduled(fixedRateString = "${raw-em.sampling.period.milliseconds}")
public void processRawEMData() {
GetEMStatusResponse getEMStatusResponse = rawEMDataService.getRawEMSamples();
LocalDateTime sampleDateTime = LocalDateTime.ofInstant(
Instant.ofEpochSecond(getEMStatusResponse.getUnixTime()),
TimeZone.getTimeZone("Europe/Rome").toZoneId()
);
Double gridPower = getEMStatusResponse.getRawEMSamples().get(0).getPower();
Double pvPower = getEMStatusResponse.getRawEMSamples().get(1).getPower();
Double gridVoltage = getEMStatusResponse.getRawEMSamples().get(0).getVoltage();
Double pvVoltage = getEMStatusResponse.getRawEMSamples().get(1).getVoltage();
RawEMData rawEmData = new RawEMData(
sampleDateTime,
gridPower,
pvPower,
gridVoltage,
pvVoltage
);
rawEmDataRepository.save(rawEmData);
log.info("Saved raw EM data: [{}, {}, {}, {}, {}]", sampleFormatter.format(sampleDateTime), String.format("%.2f", gridPower), String.format("%.2f", pvPower), String.format("%.2f", gridVoltage), String.format("%.2f", pvVoltage));
}
@Scheduled(cron = "${raw-em.hourly-aggregate.cron.schedule}", zone = "Europe/Rome")
public void processHourlyAggregatedData() {
final double dt = Double.parseDouble(samplingPeriodInMilliseconds) / 1000 / 3600;
LocalDateTime fromTimestamp = LocalDateTime.now().minusHours(1).truncatedTo(ChronoUnit.HOURS);
LocalDateTime toTimestamp = LocalDateTime.now().truncatedTo(ChronoUnit.HOURS);
List<RawEMData> rawEMDataSamples = rawEmDataRepository.findAllBySampleTimestampBetween(fromTimestamp, toTimestamp);
Double gridEnergyIn = rawEMDataSamples
.stream()
.filter(s -> (s.getGridPower() > samplingThreshold))
.mapToDouble(d -> d.getGridPower() * dt)
.sum();
Double gridEnergyOut = rawEMDataSamples
.stream()
.filter(s -> (s.getGridPower() < -1 * samplingThreshold))
.mapToDouble(d -> Math.abs(d.getGridPower()) * dt)
.sum();
Double pvEnergyIn = rawEMDataSamples
.stream()
.filter(s -> (s.getPvPower() > samplingThreshold))
.mapToDouble(d -> d.getPvPower() * dt)
.sum();
Double pvEnergyOut = rawEMDataSamples
.stream()
.filter(s -> (s.getPvPower() < -1 * samplingThreshold))
.mapToDouble(d -> Math.abs(d.getPvPower()) * dt)
.sum();
Double maxGridVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getGridVoltage())
.max()
.getAsDouble();
Double minGridVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getGridVoltage())
.min()
.getAsDouble();
Double maxPvVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getPvVoltage())
.max()
.getAsDouble();
Double minPvVoltage = rawEMDataSamples
.stream()
.mapToDouble(d -> d.getPvVoltage())
.min()
.getAsDouble(); | hourlyEMEnergyRepository.save(new HourlyEMEnergy(fromTimestamp, toTimestamp, gridEnergyIn, gridEnergyOut, pvEnergyIn, pvEnergyOut, maxGridVoltage, minGridVoltage, maxPvVoltage, minPvVoltage)); | 1 | 2023-10-26 19:52:00+00:00 | 8k |
DimitarDSimeonov/ShopApp | src/main/java/bg/softuni/shop_app/model/entity/Product.java | [
{
"identifier": "Category",
"path": "src/main/java/bg/softuni/shop_app/model/entity/enums/Category.java",
"snippet": "public enum Category {\n VEHICLE(\"Превозни средства\"),\n ELECTRONIC(\"Електроника\"),\n ESTATE(\"Имоти\"),\n CLOTHING(\"Облекло\"),\n OTHER(\"Други\");\n\n private St... | import bg.softuni.shop_app.model.entity.enums.Category;
import bg.softuni.shop_app.model.entity.enums.Location;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List; | 3,721 | package bg.softuni.shop_app.model.entity;
@Getter
@Setter
@Entity
@Table(name = "products")
public class Product extends BaseEntity{
@Column(nullable = false)
private String title;
@Column(columnDefinition = "TEXT", nullable = false)
private String description;
@Column(name = "price", nullable = false)
private BigDecimal price;
@Enumerated(EnumType.STRING)
private Category category;
@Column(name = "date_of_post")
private LocalDateTime dateOfPost;
@Enumerated(EnumType.STRING) | package bg.softuni.shop_app.model.entity;
@Getter
@Setter
@Entity
@Table(name = "products")
public class Product extends BaseEntity{
@Column(nullable = false)
private String title;
@Column(columnDefinition = "TEXT", nullable = false)
private String description;
@Column(name = "price", nullable = false)
private BigDecimal price;
@Enumerated(EnumType.STRING)
private Category category;
@Column(name = "date_of_post")
private LocalDateTime dateOfPost;
@Enumerated(EnumType.STRING) | private Location location; | 1 | 2023-10-27 13:33:23+00:00 | 8k |
achrafaitibba/invoiceYou | src/main/java/com/onxshield/invoiceyou/invoicestatement/service/invoiceService.java | [
{
"identifier": "requestException",
"path": "src/main/java/com/onxshield/invoiceyou/invoicestatement/exceptions/requestException.java",
"snippet": "@Getter\npublic class requestException extends RuntimeException{\n\n private HttpStatus httpStatus;\n public requestException(String message) {\n ... | import com.onxshield.invoiceyou.invoicestatement.dto.request.invoiceRequest;
import com.onxshield.invoiceyou.invoicestatement.dto.response.basicInvoiceResponse;
import com.onxshield.invoiceyou.invoicestatement.dto.response.merchandiseResponse;
import com.onxshield.invoiceyou.invoicestatement.exceptions.requestException;
import com.onxshield.invoiceyou.invoicestatement.model.*;
import com.onxshield.invoiceyou.invoicestatement.repository.*;
import com.onxshield.invoiceyou.invoicestatement.util.numberToWordUtil;
import com.onxshield.invoiceyou.invoicestatement.util.doubleTwoDigitConverter;
import jakarta.transaction.Transactional;
import lombok.*;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import java.time.Year;
import java.util.List;
import java.util.Optional; | 4,212 | merchandiseRequest -> {
merchandise merchandiseToSave;
Optional<inventory> inventory = inventoryRepository.findByProductProductId(merchandiseRequest.productId());
Double availability = inventory.get().getAvailability();
if (availability >= merchandiseRequest.quantity() && availability > 0) {
Double totalByProduct = merchandiseRequest.quantity() * inventory.get().getSellPrice();
inventory.get().setAvailability(availability - merchandiseRequest.quantity());
merchandiseToSave = new merchandise();
merchandiseToSave.setProduct(productRepository.findById(merchandiseRequest.productId()).get());
merchandiseToSave.setQuantity(merchandiseRequest.quantity());
merchandiseToSave.setTotal(totalByProduct);
return merchandiseRepository.save(merchandiseToSave);
} else {
throw new requestException("Product isn't available in the inventory, out of stock", HttpStatus.CONFLICT);
}
}
)
.toList();
}
public invoice createInvoice(invoiceRequest request) {
Optional<client> client = clientRepository.findById(request.clientId());
if (invoiceRepository.findById(request.invoiceId()).isEmpty()) {
deleteInvoiceNumberByInvoiceNumber(request.invoiceId());
List<merchandise> savedMerchandise = null;
if (request.merchandiseList() != null) {
savedMerchandise = merchandiseRequestToMerchandise(request);
}
invoice invoiceToSave = invoice.builder()
.invoiceId(request.invoiceId())
.invoiceDate(request.invoiceDate())
.client(client.get())
.totalTTC(request.totalTTC())
.TVA(twoDigitTVA(request.totalTTC().doubleValue() / 6))
.spelledTotal(numberToWordUtil.convert(request.totalTTC()))
.paymentMethod(paymentMethod.valueOf(request.paymentMethod()))
.bankName(request.bankName())
.checkNumber(request.checkNumber())
.paymentDate(request.paymentDate())
.printed(Boolean.valueOf(request.printed()))
.invoiceAction(action.valueOf(request.invoiceAction()))
.invoiceStatus(status.valueOf(request.invoiceStatus()))
.invoiceFile(request.invoiceFile())
.merchandiseList(savedMerchandise)
.discount(request.discount())
.build();
invoice saved = invoiceRepository.save(invoiceToSave);
if (request.merchandiseList() != null) {
//savedMerchandise = merchandiseRequestToMerchandise(request);
for (merchandise merch : savedMerchandise
) {
Optional<merchandise> toUpdate = merchandiseRepository.findById(merch.getMerchId());
toUpdate.get().setInvoice(saved);
}
}
return saved;
} else throw new requestException("Invoice already exist", HttpStatus.CONFLICT);
}
private void deleteInvoiceNumberByInvoiceNumber(String invoiceNumber) {
Optional<invoiceNumber> invoiceN = invoiceNumberRepository.findById(invoiceNumber);
if (invoiceN.isPresent()) {
invoiceNumberRepository.deleteById(invoiceNumber);
}
}
public invoice updateInvoice(invoiceRequest request) {
// update the invoice ID? if yes (merchandise should be updated also)
// and the list of available ID should have a new record (the previous Invoice id)
/////////////////////////////////////////
Optional<invoice> toUpdate = invoiceRepository.findById(request.invoiceId());
if (toUpdate.isPresent()) {
Optional<client> client = clientRepository.findById(request.clientId());
toUpdate.get().setInvoiceDate(request.invoiceDate());
toUpdate.get().setClient(client.get());
toUpdate.get().setTotalTTC(request.totalTTC());
toUpdate.get().setSpelledTotal(convertNumberToWords(request.totalTTC()));
toUpdate.get().setTVA(twoDigitTVA(request.totalTTC().doubleValue() / 6));
toUpdate.get().setPaymentMethod(paymentMethod.valueOf(request.paymentMethod()));
toUpdate.get().setBankName(request.bankName());
toUpdate.get().setCheckNumber(request.checkNumber());
toUpdate.get().setPaymentDate(request.paymentDate());
toUpdate.get().setPrinted(Boolean.valueOf(request.printed()));
toUpdate.get().setInvoiceAction(action.valueOf(request.invoiceAction()));
toUpdate.get().setInvoiceStatus(status.valueOf(request.invoiceStatus()));
toUpdate.get().setInvoiceFile(request.invoiceFile());
toUpdate.get().setDiscount(request.discount());
if (merchandiseRepository.findAllByInvoice_InvoiceId(request.invoiceId()) != null) {
deleteAllMerchandiseUpdateInventory(request.invoiceId());
List<merchandise> savedMerchandise = merchandiseRequestToMerchandise(request);
for (merchandise merch : savedMerchandise
) {
Optional<merchandise> merchToUpdate = merchandiseRepository.findById(merch.getMerchId());
merchToUpdate.get().setInvoice(toUpdate.get());
}
}
return invoiceRepository.save(toUpdate.get());
} else throw new requestException("The invoice doesn't exist", HttpStatus.NOT_FOUND);
}
public void deleteAllMerchandiseUpdateInventory(String invoiceId) {
List<merchandise> merchandiseList = merchandiseRepository.findAllByInvoice_InvoiceId(invoiceId);
if (merchandiseRepository.findAllByInvoice_InvoiceId(invoiceId) != null) {
for (merchandise merch : merchandiseList
) {
Optional<inventory> toUpdate = inventoryRepository.findByProductProductId(merch.getProduct().getProductId());
Double availableQuantity = toUpdate.get().getAvailability();
toUpdate.get().setAvailability(availableQuantity + merch.getQuantity());
}
merchandiseRepository.deleteByInvoice_InvoiceId(invoiceId);
}
}
public double twoDigitTVA(Double tva) {
| package com.onxshield.invoiceyou.invoicestatement.service;
@Service
@RequiredArgsConstructor
@Transactional
public class invoiceService {
private final invoiceRepository invoiceRepository;
private final clientRepository clientRepository;
private final inventoryRepository inventoryRepository;
private final productRepository productRepository;
private final merchandiseRepository merchandiseRepository;
private final invoiceNumberRepository invoiceNumberRepository;
static long latestInvoiceNumber = 1225;
public invoice createBasicInvoice(invoiceRequest request) {
//find inventory by product id
//check availability
//get the sell price
//calculate total by product = sell price * quantity
//add the total by product to totalTTC
//decrease availability in the inventory
//BUILD the merchandise instances
Optional<client> client = clientRepository.findById(request.clientId());
if (invoiceRepository.findById(request.invoiceId()).isEmpty()) {
deleteInvoiceNumberByInvoiceNumber(request.invoiceId());
List<merchandise> savedMerchandise = merchandiseRequestToMerchandise(request);
invoice invoiceToSave = new invoice();
invoiceToSave.setInvoiceId(request.invoiceId());
invoiceToSave.setInvoiceDate(request.invoiceDate());
invoiceToSave.setClient(client.get());
invoiceToSave.setTotalTTC(request.totalTTC());
invoiceToSave.setTVA(twoDigitTVA(request.totalTTC().doubleValue() / 6));
invoiceToSave.setSpelledTotal(convertNumberToWords(request.totalTTC().longValue()));
invoiceToSave.setMerchandiseList(savedMerchandise);
invoiceToSave.setCheckNumber(request.checkNumber());
invoiceToSave.setPaymentMethod(paymentMethod.valueOf(request.paymentMethod()));
invoiceToSave.setDiscount(request.discount());
invoice saved = invoiceRepository.save(invoiceToSave);
for (merchandise merch : savedMerchandise
) {
Optional<merchandise> toUpdate = merchandiseRepository.findById(merch.getMerchId());
toUpdate.get().setInvoice(saved);
}
return saved;
} else {
throw new requestException("The Id you provided already used by other invoice", HttpStatus.CONFLICT);
}
}
public String convertNumberToWords(Long total) {
return numberToWordUtil.convert(total).toUpperCase();
}
public String[] getAvailableInvoiceNumbers() {
List<String> numbers = invoiceNumberRepository.findAll()
.stream()
.map(invoiceNumber::getInvoiceNumber)
.toList();
return numbers.toArray(new String[0]);
}
public String generateInvoiceNumber() {
int currentYear = Year.now().getValue();
int lastTwoDigits = currentYear % 100;
latestInvoiceNumber++;
String toSave = "ST" + latestInvoiceNumber + "/" + String.format("%02d", lastTwoDigits);
invoiceNumberRepository.save(new invoiceNumber(toSave));
latestInvoiceNumber++;
return "ST" + latestInvoiceNumber + "/" + String.format("%02d", lastTwoDigits);
}
public invoice getInvoiceById(String invoiceId) {
Optional<invoice> invoice = invoiceRepository.findById(invoiceId);
if (invoice.isPresent()) {
return invoice.get();
} else throw new requestException("The Id you provided doesn't exist", HttpStatus.CONFLICT);
}
public basicInvoiceResponse getBasicInvoiceById(String invoiceId) {
invoice invoice = getInvoiceById(invoiceId);
return new basicInvoiceResponse(
invoice.getClient().getName(),
invoice.getInvoiceId(),
invoice.getClient().getICE(),
invoice.getInvoiceDate(),
invoice.getMerchandiseList().stream().map(
merchandise -> new merchandiseResponse(
merchandise.getMerchId(),
merchandise.getProduct().getName(),
merchandise.getProduct().getUnit().toString(),
merchandise.getQuantity(),
inventoryRepository.findByProductProductId(merchandise.getProduct().getProductId()).get().getSellPrice(),
merchandise.getQuantity().longValue() * inventoryRepository.findByProductProductId(merchandise.getProduct().getProductId()).get().getSellPrice().longValue()
)
)
.toList(),
invoice.getTotalTTC(),
invoice.getTVA(),
invoice.getSpelledTotal(),
invoice.getPaymentMethod().toString(),
invoice.getCheckNumber(),
invoice.getDiscount()
);
}
public Page<invoice> getAllInvoices(Integer pageNumber, Integer size, String direction, String sortBy) {
Sort soring = Sort.by(Sort.Direction.valueOf(direction.toUpperCase()), sortBy);
Pageable page = PageRequest.of(pageNumber, size, soring);
return invoiceRepository.findAll(page);
}
public List<merchandise> merchandiseRequestToMerchandise(invoiceRequest request) {
return request.merchandiseList().stream()
.map(
merchandiseRequest -> {
merchandise merchandiseToSave;
Optional<inventory> inventory = inventoryRepository.findByProductProductId(merchandiseRequest.productId());
Double availability = inventory.get().getAvailability();
if (availability >= merchandiseRequest.quantity() && availability > 0) {
Double totalByProduct = merchandiseRequest.quantity() * inventory.get().getSellPrice();
inventory.get().setAvailability(availability - merchandiseRequest.quantity());
merchandiseToSave = new merchandise();
merchandiseToSave.setProduct(productRepository.findById(merchandiseRequest.productId()).get());
merchandiseToSave.setQuantity(merchandiseRequest.quantity());
merchandiseToSave.setTotal(totalByProduct);
return merchandiseRepository.save(merchandiseToSave);
} else {
throw new requestException("Product isn't available in the inventory, out of stock", HttpStatus.CONFLICT);
}
}
)
.toList();
}
public invoice createInvoice(invoiceRequest request) {
Optional<client> client = clientRepository.findById(request.clientId());
if (invoiceRepository.findById(request.invoiceId()).isEmpty()) {
deleteInvoiceNumberByInvoiceNumber(request.invoiceId());
List<merchandise> savedMerchandise = null;
if (request.merchandiseList() != null) {
savedMerchandise = merchandiseRequestToMerchandise(request);
}
invoice invoiceToSave = invoice.builder()
.invoiceId(request.invoiceId())
.invoiceDate(request.invoiceDate())
.client(client.get())
.totalTTC(request.totalTTC())
.TVA(twoDigitTVA(request.totalTTC().doubleValue() / 6))
.spelledTotal(numberToWordUtil.convert(request.totalTTC()))
.paymentMethod(paymentMethod.valueOf(request.paymentMethod()))
.bankName(request.bankName())
.checkNumber(request.checkNumber())
.paymentDate(request.paymentDate())
.printed(Boolean.valueOf(request.printed()))
.invoiceAction(action.valueOf(request.invoiceAction()))
.invoiceStatus(status.valueOf(request.invoiceStatus()))
.invoiceFile(request.invoiceFile())
.merchandiseList(savedMerchandise)
.discount(request.discount())
.build();
invoice saved = invoiceRepository.save(invoiceToSave);
if (request.merchandiseList() != null) {
//savedMerchandise = merchandiseRequestToMerchandise(request);
for (merchandise merch : savedMerchandise
) {
Optional<merchandise> toUpdate = merchandiseRepository.findById(merch.getMerchId());
toUpdate.get().setInvoice(saved);
}
}
return saved;
} else throw new requestException("Invoice already exist", HttpStatus.CONFLICT);
}
private void deleteInvoiceNumberByInvoiceNumber(String invoiceNumber) {
Optional<invoiceNumber> invoiceN = invoiceNumberRepository.findById(invoiceNumber);
if (invoiceN.isPresent()) {
invoiceNumberRepository.deleteById(invoiceNumber);
}
}
public invoice updateInvoice(invoiceRequest request) {
// update the invoice ID? if yes (merchandise should be updated also)
// and the list of available ID should have a new record (the previous Invoice id)
/////////////////////////////////////////
Optional<invoice> toUpdate = invoiceRepository.findById(request.invoiceId());
if (toUpdate.isPresent()) {
Optional<client> client = clientRepository.findById(request.clientId());
toUpdate.get().setInvoiceDate(request.invoiceDate());
toUpdate.get().setClient(client.get());
toUpdate.get().setTotalTTC(request.totalTTC());
toUpdate.get().setSpelledTotal(convertNumberToWords(request.totalTTC()));
toUpdate.get().setTVA(twoDigitTVA(request.totalTTC().doubleValue() / 6));
toUpdate.get().setPaymentMethod(paymentMethod.valueOf(request.paymentMethod()));
toUpdate.get().setBankName(request.bankName());
toUpdate.get().setCheckNumber(request.checkNumber());
toUpdate.get().setPaymentDate(request.paymentDate());
toUpdate.get().setPrinted(Boolean.valueOf(request.printed()));
toUpdate.get().setInvoiceAction(action.valueOf(request.invoiceAction()));
toUpdate.get().setInvoiceStatus(status.valueOf(request.invoiceStatus()));
toUpdate.get().setInvoiceFile(request.invoiceFile());
toUpdate.get().setDiscount(request.discount());
if (merchandiseRepository.findAllByInvoice_InvoiceId(request.invoiceId()) != null) {
deleteAllMerchandiseUpdateInventory(request.invoiceId());
List<merchandise> savedMerchandise = merchandiseRequestToMerchandise(request);
for (merchandise merch : savedMerchandise
) {
Optional<merchandise> merchToUpdate = merchandiseRepository.findById(merch.getMerchId());
merchToUpdate.get().setInvoice(toUpdate.get());
}
}
return invoiceRepository.save(toUpdate.get());
} else throw new requestException("The invoice doesn't exist", HttpStatus.NOT_FOUND);
}
public void deleteAllMerchandiseUpdateInventory(String invoiceId) {
List<merchandise> merchandiseList = merchandiseRepository.findAllByInvoice_InvoiceId(invoiceId);
if (merchandiseRepository.findAllByInvoice_InvoiceId(invoiceId) != null) {
for (merchandise merch : merchandiseList
) {
Optional<inventory> toUpdate = inventoryRepository.findByProductProductId(merch.getProduct().getProductId());
Double availableQuantity = toUpdate.get().getAvailability();
toUpdate.get().setAvailability(availableQuantity + merch.getQuantity());
}
merchandiseRepository.deleteByInvoice_InvoiceId(invoiceId);
}
}
public double twoDigitTVA(Double tva) {
| return doubleTwoDigitConverter.twoDigitTVA(tva); | 2 | 2023-10-29 11:16:37+00:00 | 8k |
Melledy/LunarCore | src/main/java/emu/lunarcore/command/commands/WorldLevelCommand.java | [
{
"identifier": "CommandArgs",
"path": "src/main/java/emu/lunarcore/command/CommandArgs.java",
"snippet": "@Getter\npublic class CommandArgs {\n private String raw;\n private List<String> list;\n private Player sender;\n private Player target;\n \n private int targetUid;\n private i... | import emu.lunarcore.command.Command;
import emu.lunarcore.command.CommandArgs;
import emu.lunarcore.command.CommandHandler;
import emu.lunarcore.util.Utils; | 4,280 | package emu.lunarcore.command.commands;
@Command(label = "worldlevel", aliases = {"wl"}, permission = "player.worldlevel", requireTarget = true, desc = "/worldlevel [world level]. Sets the targeted player's equilibrium level.")
public class WorldLevelCommand implements CommandHandler {
@Override | package emu.lunarcore.command.commands;
@Command(label = "worldlevel", aliases = {"wl"}, permission = "player.worldlevel", requireTarget = true, desc = "/worldlevel [world level]. Sets the targeted player's equilibrium level.")
public class WorldLevelCommand implements CommandHandler {
@Override | public void execute(CommandArgs args) { | 0 | 2023-10-10 12:57:35+00:00 | 8k |
jar-analyzer/jar-analyzer | src/main/java/org/sqlite/SQLiteJDBCLoader.java | [
{
"identifier": "LibraryLoaderUtil",
"path": "src/main/java/org/sqlite/util/LibraryLoaderUtil.java",
"snippet": "public class LibraryLoaderUtil {\n\n public static final String NATIVE_LIB_BASE_NAME = \"sqlitejdbc\";\n\n /**\n * Get the OS-specific resource directory within the jar, where the r... | import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
import java.util.stream.Stream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sqlite.util.LibraryLoaderUtil;
import org.sqlite.util.OSInfo;
import org.sqlite.util.StringUtils; | 4,555 | }
int ch2 = in2.read();
return ch2 == -1;
}
/**
* Extracts and loads the specified library file to the target folder
*
* @param libFolderForCurrentOS Library path.
* @param libraryFileName Library name.
* @param targetFolder Target folder.
* @return
*/
private static boolean extractAndLoadLibraryFile(
String libFolderForCurrentOS, String libraryFileName, String targetFolder)
throws FileException {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName =
String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
String extractedLckFileName = extractedLibFileName + LOCK_EXT;
Path extractedLibFile = Paths.get(targetFolder, extractedLibFileName);
Path extractedLckFile = Paths.get(targetFolder, extractedLckFileName);
try {
// Extract a native library file into the target directory
try (InputStream reader = getResourceAsStream(nativeLibraryFilePath)) {
if (Files.notExists(extractedLckFile)) {
Files.createFile(extractedLckFile);
}
Files.copy(reader, extractedLibFile, StandardCopyOption.REPLACE_EXISTING);
} finally {
// Delete the extracted lib file on JVM exit.
extractedLibFile.toFile().deleteOnExit();
extractedLckFile.toFile().deleteOnExit();
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.toFile().setReadable(true);
extractedLibFile.toFile().setWritable(true, true);
extractedLibFile.toFile().setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
try (InputStream nativeIn = getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = Files.newInputStream(extractedLibFile)) {
if (!contentsEquals(nativeIn, extractedLibIn)) {
throw new FileException(
String.format(
"Failed to write a native library file at %s",
extractedLibFile));
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
} catch (IOException e) {
logger.error("Unexpected IOException", e);
return false;
}
}
// Replacement of java.lang.Class#getResourceAsStream(String) to disable sharing the resource
// stream
// in multiple class loaders and specifically to avoid
// https://bugs.openjdk.java.net/browse/JDK-8205976
private static InputStream getResourceAsStream(String name) {
// Remove leading '/' since all our resource paths include a leading directory
// See:
// https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/Class.java#L3054
String resolvedName = name.substring(1);
ClassLoader cl = SQLiteJDBCLoader.class.getClassLoader();
URL url = cl.getResource(resolvedName);
if (url == null) {
return null;
}
try {
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
return connection.getInputStream();
} catch (IOException e) {
logger.error("Could not connect", e);
return null;
}
}
/**
* Loads native library using the given path and name of the library.
*
* @param path Path of the native library.
* @param name Name of the native library.
* @return True for successfully loading; false otherwise.
*/
private static boolean loadNativeLibrary(String path, String name) {
File libPath = new File(path, name);
if (libPath.exists()) {
try {
System.load(new File(path, name).getAbsolutePath());
return true;
} catch (UnsatisfiedLinkError e) {
logger.error(
"Failed to load native library: {}. osinfo: {}",
name,
OSInfo.getNativeLibFolderPathForCurrentOS(),
e);
return false;
}
} else {
return false;
}
}
private static boolean loadNativeLibraryJdk() {
try { | /*--------------------------------------------------------------------------
* Copyright 2007 Taro L. Saito
*
* 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.
*--------------------------------------------------------------------------*/
// --------------------------------------
// SQLite JDBC Project
//
// SQLite.java
// Since: 2007/05/10
//
// $URL$
// $Author$
// --------------------------------------
package org.sqlite;
/**
* Set the system properties, org.sqlite.lib.path, org.sqlite.lib.name, appropriately so that the
* SQLite JDBC driver can find *.dll, *.dylib and *.so files, according to the current OS (win,
* linux, mac).
*
* <p>The library files are automatically extracted from this project's package (JAR).
*
* <p>usage: call {@link #initialize()} before using SQLite JDBC driver.
*
* @author leo
*/
public class SQLiteJDBCLoader {
private static final Logger logger = LoggerFactory.getLogger(SQLiteJDBCLoader.class);
private static final String LOCK_EXT = ".lck";
private static boolean extracted = false;
/**
* Loads SQLite native JDBC library.
*
* @return True if SQLite native library is successfully loaded; false otherwise.
*/
public static synchronized boolean initialize() throws Exception {
// only cleanup before the first extract
if (!extracted) {
cleanup();
}
loadSQLiteNativeLibrary();
return extracted;
}
private static File getTempDir() {
return new File(
System.getProperty("org.sqlite.tmpdir", System.getProperty("java.io.tmpdir")));
}
/**
* Deleted old native libraries e.g. on Windows the DLL file is not removed on VM-Exit (bug #80)
*/
static void cleanup() {
String searchPattern = "sqlite-" + getVersion();
try (Stream<Path> dirList = Files.list(getTempDir().toPath())) {
dirList.filter(
path ->
!path.getFileName().toString().endsWith(LOCK_EXT)
&& path.getFileName()
.toString()
.startsWith(searchPattern))
.forEach(
nativeLib -> {
Path lckFile = Paths.get(nativeLib + LOCK_EXT);
if (Files.notExists(lckFile)) {
try {
Files.delete(nativeLib);
} catch (Exception e) {
logger.error("Failed to delete old native lib", e);
}
}
});
} catch (IOException e) {
logger.error("Failed to open directory", e);
}
}
/**
* Checks if the SQLite JDBC driver is set to native mode.
*
* @return True if the SQLite JDBC driver is set to native Java mode; false otherwise.
*/
public static boolean isNativeMode() throws Exception {
// load the driver
initialize();
return extracted;
}
/**
* Computes the MD5 value of the input stream.
*
* @param input InputStream.
* @return Encrypted string for the InputStream.
* @throws IOException
* @throws NoSuchAlgorithmException
*/
static String md5sum(InputStream input) throws IOException {
BufferedInputStream in = new BufferedInputStream(input);
try {
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
DigestInputStream digestInputStream = new DigestInputStream(in, digest);
for (; digestInputStream.read() >= 0; ) {}
ByteArrayOutputStream md5out = new ByteArrayOutputStream();
md5out.write(digest.digest());
return md5out.toString();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("MD5 algorithm is not available: " + e);
} finally {
in.close();
}
}
private static boolean contentsEquals(InputStream in1, InputStream in2) throws IOException {
if (!(in1 instanceof BufferedInputStream)) {
in1 = new BufferedInputStream(in1);
}
if (!(in2 instanceof BufferedInputStream)) {
in2 = new BufferedInputStream(in2);
}
int ch = in1.read();
while (ch != -1) {
int ch2 = in2.read();
if (ch != ch2) {
return false;
}
ch = in1.read();
}
int ch2 = in2.read();
return ch2 == -1;
}
/**
* Extracts and loads the specified library file to the target folder
*
* @param libFolderForCurrentOS Library path.
* @param libraryFileName Library name.
* @param targetFolder Target folder.
* @return
*/
private static boolean extractAndLoadLibraryFile(
String libFolderForCurrentOS, String libraryFileName, String targetFolder)
throws FileException {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName =
String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
String extractedLckFileName = extractedLibFileName + LOCK_EXT;
Path extractedLibFile = Paths.get(targetFolder, extractedLibFileName);
Path extractedLckFile = Paths.get(targetFolder, extractedLckFileName);
try {
// Extract a native library file into the target directory
try (InputStream reader = getResourceAsStream(nativeLibraryFilePath)) {
if (Files.notExists(extractedLckFile)) {
Files.createFile(extractedLckFile);
}
Files.copy(reader, extractedLibFile, StandardCopyOption.REPLACE_EXISTING);
} finally {
// Delete the extracted lib file on JVM exit.
extractedLibFile.toFile().deleteOnExit();
extractedLckFile.toFile().deleteOnExit();
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.toFile().setReadable(true);
extractedLibFile.toFile().setWritable(true, true);
extractedLibFile.toFile().setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
try (InputStream nativeIn = getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = Files.newInputStream(extractedLibFile)) {
if (!contentsEquals(nativeIn, extractedLibIn)) {
throw new FileException(
String.format(
"Failed to write a native library file at %s",
extractedLibFile));
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
} catch (IOException e) {
logger.error("Unexpected IOException", e);
return false;
}
}
// Replacement of java.lang.Class#getResourceAsStream(String) to disable sharing the resource
// stream
// in multiple class loaders and specifically to avoid
// https://bugs.openjdk.java.net/browse/JDK-8205976
private static InputStream getResourceAsStream(String name) {
// Remove leading '/' since all our resource paths include a leading directory
// See:
// https://github.com/openjdk/jdk/blob/master/src/java.base/share/classes/java/lang/Class.java#L3054
String resolvedName = name.substring(1);
ClassLoader cl = SQLiteJDBCLoader.class.getClassLoader();
URL url = cl.getResource(resolvedName);
if (url == null) {
return null;
}
try {
URLConnection connection = url.openConnection();
connection.setUseCaches(false);
return connection.getInputStream();
} catch (IOException e) {
logger.error("Could not connect", e);
return null;
}
}
/**
* Loads native library using the given path and name of the library.
*
* @param path Path of the native library.
* @param name Name of the native library.
* @return True for successfully loading; false otherwise.
*/
private static boolean loadNativeLibrary(String path, String name) {
File libPath = new File(path, name);
if (libPath.exists()) {
try {
System.load(new File(path, name).getAbsolutePath());
return true;
} catch (UnsatisfiedLinkError e) {
logger.error(
"Failed to load native library: {}. osinfo: {}",
name,
OSInfo.getNativeLibFolderPathForCurrentOS(),
e);
return false;
}
} else {
return false;
}
}
private static boolean loadNativeLibraryJdk() {
try { | System.loadLibrary(LibraryLoaderUtil.NATIVE_LIB_BASE_NAME); | 0 | 2023-10-07 15:42:35+00:00 | 8k |
EasyProgramming/easy-mqtt | server/src/main/java/com/ep/mqtt/server/server/MqttServer.java | [
{
"identifier": "MqttWebSocketCodec",
"path": "server/src/main/java/com/ep/mqtt/server/codec/MqttWebSocketCodec.java",
"snippet": "public class MqttWebSocketCodec extends MessageToMessageCodec<BinaryWebSocketFrame, ByteBuf> {\n\n @Override\n protected void encode(ChannelHandlerContext ctx, ByteBuf... | import com.ep.mqtt.server.codec.MqttWebSocketCodec;
import com.ep.mqtt.server.config.MqttServerProperties;
import com.ep.mqtt.server.deal.DefaultDeal;
import com.ep.mqtt.server.handler.MqttMessageHandler;
import com.ep.mqtt.server.processor.AbstractMqttProcessor;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.mqtt.MqttDecoder;
import io.netty.handler.codec.mqtt.MqttEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLEngine;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.List; | 6,193 | package com.ep.mqtt.server.server;
/**
* @author zbz
* @date 2023/7/1 10:52
*/
@Slf4j
@Component
public class MqttServer {
@Autowired | package com.ep.mqtt.server.server;
/**
* @author zbz
* @date 2023/7/1 10:52
*/
@Slf4j
@Component
public class MqttServer {
@Autowired | private MqttServerProperties mqttServerProperties; | 1 | 2023-10-08 06:41:33+00:00 | 8k |
egorolegovichyakovlev/DroidRec | app/src/main/java/com/yakovlevegor/DroidRec/MainActivity.java | [
{
"identifier": "OnShakeEventHelper",
"path": "app/src/main/java/com/yakovlevegor/DroidRec/shake/OnShakeEventHelper.java",
"snippet": "public class OnShakeEventHelper {\n private SensorEventListener currentListener;\n private boolean hasListenerChanged;\n private Context context;\n private S... | import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.graphics.drawable.VectorDrawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.display.DisplayManager;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.MotionEvent;
import android.widget.RelativeLayout;
import android.widget.ImageView;
import android.widget.ImageButton;
import android.widget.Chronometer;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RelativeLayout;
import android.widget.LinearLayout;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.AnimatorInflater;
import androidx.vectordrawable.graphics.drawable.VectorDrawableCompat;
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat;
import androidx.vectordrawable.graphics.drawable.Animatable2Compat;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.TooltipCompat;
import com.yakovlevegor.DroidRec.shake.OnShakeEventHelper;
import com.yakovlevegor.DroidRec.shake.event.ServiceConnectedEvent;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList; | 3,761 | recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(255);
recordingStartButtonTransitionBack.start();
break;
}
}
public class ActivityBinder extends Binder {
void recordingStart() {
timeCounter.stop();
timeCounter.setBase(recordingBinder.getTimeStart());
timeCounter.start();
audioPlaybackUnavailable.setVisibility(View.GONE);
modesPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.GONE);
recordingState = MainButtonActionState.RECORDING_IN_PROGRESS;
if (stateToRestore == true) {
showCounter(true, MainButtonState.TRANSITION_TO_RECORDING);
} else {
timeCounter.setScaleX(1.0f);
timeCounter.setScaleY(1.0f);
timerPanel.setVisibility(View.VISIBLE);
transitionToButtonState(MainButtonState.WHILE_RECORDING_NORMAL);
}
}
void recordingStop() {
timeCounter.stop();
timeCounter.setBase(SystemClock.elapsedRealtime());
audioPlaybackUnavailable.setVisibility(View.GONE);
modesPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.GONE);
finishedPanel.setVisibility(View.VISIBLE);
recordStop.setVisibility(View.GONE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
audioPlaybackUnavailable.setVisibility(View.VISIBLE);
}
recordingState = MainButtonActionState.RECORDING_ENDED;
if (stateToRestore == true) {
showCounter(false, MainButtonState.TRANSITION_TO_RECORDING_END);
} else {
timerPanel.setVisibility(View.GONE);
transitionToButtonState(MainButtonState.ENDED_RECORDING_NORMAL);
}
}
void recordingPause(long time) {
timeCounter.setBase(SystemClock.elapsedRealtime()-time);
timeCounter.stop();
modesPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.GONE);
timeCounter.setScaleX(1.0f);
timeCounter.setScaleY(1.0f);
timerPanel.setVisibility(View.VISIBLE);
recordStop.setVisibility(View.VISIBLE);
recordingState = MainButtonActionState.RECORDING_PAUSED;
if (stateToRestore == true) {
transitionToButtonState(MainButtonState.TRANSITION_TO_RECORDING_PAUSE);
} else {
transitionToButtonState(MainButtonState.WHILE_PAUSE_NORMAL);
}
}
void recordingResume(long time) {
timeCounter.setBase(time);
timeCounter.start();
recordStop.setVisibility(View.GONE);
recordingState = MainButtonActionState.RECORDING_IN_PROGRESS;
}
void recordingReset() {
finishedPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.VISIBLE);
modesPanel.setVisibility(View.VISIBLE);
transitionToButtonState(MainButtonState.TRANSITION_TO_RESTART);
}
void resetDir(boolean isAudio) {
resetFolder(isAudio);
}
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
recordingBinder = (ScreenRecorder.RecordingBinder)service;
screenRecorderStarted = recordingBinder.isStarted();
recordingBinder.setConnect(new ActivityBinder());
if (serviceToRecording == true) {
serviceToRecording = false;
recordingStart();
}
| /*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* 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 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.
*
* For more information, please refer to <http://unlicense.org/>
*/
package com.yakovlevegor.DroidRec;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_MICROPHONE = 56808;
private static final int REQUEST_MICROPHONE_PLAYBACK = 59465;
private static final int REQUEST_MICROPHONE_RECORD = 58467;
private static final int REQUEST_STORAGE = 58593;
private static final int REQUEST_STORAGE_AUDIO = 58563;
private static final int REQUEST_MODE_CHANGE = 58857;
private ScreenRecorder.RecordingBinder recordingBinder;
boolean screenRecorderStarted = false;
private MediaProjectionManager activityProjectionManager;
private SharedPreferences appSettings;
private SharedPreferences.Editor appSettingsEditor;
Display display;
ImageButton mainRecordingButton;
ImageButton startRecordingButton;
ImageButton recordScreenSetting;
ImageButton recordMicrophoneSetting;
ImageButton recordAudioSetting;
ImageButton recordInfo;
ImageButton recordSettings;
ImageButton recordShare;
ImageButton recordDelete;
ImageButton recordOpen;
ImageButton recordStop;
LinearLayout timerPanel;
LinearLayout modesPanel;
LinearLayout finishedPanel;
LinearLayout optionsPanel;
Chronometer timeCounter;
TextView audioPlaybackUnavailable;
Intent serviceIntent;
public static String appName = "com.yakovlevegor.DroidRec";
public static String ACTION_ACTIVITY_START_RECORDING = appName+".ACTIVITY_START_RECORDING";
private boolean stateActivated = false;
private boolean serviceToRecording = false;
private AlertDialog dialog;
private boolean recordModeChosen;
private OnShakeEventHelper onShakeEventHelper;
private boolean isRecording = false;
private boolean recordMicrophone = false;
private boolean recordPlayback = false;
private boolean recordOnlyAudio = false;
private VectorDrawableCompat recordScreenState;
private VectorDrawableCompat recordScreenStateDisabled;
private VectorDrawableCompat recordMicrophoneState;
private VectorDrawableCompat recordMicrophoneStateDisabled;
private VectorDrawableCompat recordPlaybackState;
private VectorDrawableCompat recordPlaybackStateDisabled;
private VectorDrawableCompat recordInfoIcon;
private VectorDrawableCompat recordSettingsIcon;
private VectorDrawableCompat recordShareIcon;
private VectorDrawableCompat recordDeleteIcon;
private VectorDrawableCompat recordOpenIcon;
private VectorDrawableCompat recordStopIcon;
private VectorDrawableCompat recordingStartButtonNormal;
private AnimatedVectorDrawableCompat recordingStartButtonHover;
private AnimatedVectorDrawableCompat recordingStartButtonHoverReleased;
private AnimatedVectorDrawableCompat recordingStartButtonTransitionToRecording;
private VectorDrawableCompat recordingBackgroundNormal;
private AnimatedVectorDrawableCompat recordingBackgroundHover;
private AnimatedVectorDrawableCompat recordingBackgroundHoverReleased;
private AnimatedVectorDrawableCompat recordingBackgroundTransition;
private AnimatedVectorDrawableCompat recordingBackgroundTransitionBack;
private VectorDrawableCompat recordingStartCameraLegs;
private AnimatedVectorDrawableCompat recordingStartCameraLegsAppear;
private AnimatedVectorDrawableCompat recordingStartCameraLegsDisappear;
private VectorDrawableCompat recordingStartCameraMicrophone;
private AnimatedVectorDrawableCompat recordingStartCameraMicrophoneAppear;
private AnimatedVectorDrawableCompat recordingStartCameraMicrophoneDisappear;
private AnimatedVectorDrawableCompat recordingStartCameraBodyWorking;
private AnimatedVectorDrawableCompat recordingStartCameraBodyAppear;
private AnimatedVectorDrawableCompat recordingStartCameraBodyDisappear;
private VectorDrawableCompat recordingStartCameraHeadphones;
private AnimatedVectorDrawableCompat recordingStartCameraHeadphonesAppear;
private AnimatedVectorDrawableCompat recordingStartCameraHeadphonesDisappear;
private AnimatedVectorDrawableCompat recordingStopCameraReelsFirstAppear;
private AnimatedVectorDrawableCompat recordingStopCameraReelsFirstDisappear;
private AnimatedVectorDrawableCompat recordingStopCameraReelsSecondAppear;
private AnimatedVectorDrawableCompat recordingStopCameraReelsSecondDisappear;
private AnimatedVectorDrawableCompat recordingStartAudioBodyWorking;
private AnimatedVectorDrawableCompat recordingStartAudioBodyAppear;
private AnimatedVectorDrawableCompat recordingStartAudioBodyDisappear;
private AnimatedVectorDrawableCompat recordingStartAudioTapeWorking;
private AnimatedVectorDrawableCompat recordingStartAudioTapeAppear;
private AnimatedVectorDrawableCompat recordingStartAudioTapeDisappear;
private VectorDrawableCompat recordingStartAudioHeadphones;
private AnimatedVectorDrawableCompat recordingStartAudioHeadphonesAppear;
private AnimatedVectorDrawableCompat recordingStartAudioHeadphonesDisappear;
private VectorDrawableCompat recordingStartAudioMicrophone;
private AnimatedVectorDrawableCompat recordingStartAudioMicrophoneAppear;
private AnimatedVectorDrawableCompat recordingStartAudioMicrophoneDisappear;
private AnimatedVectorDrawableCompat recordingStopAudioReelsFirstAppear;
private AnimatedVectorDrawableCompat recordingStopAudioReelsFirstDisappear;
private AnimatedVectorDrawableCompat recordingStopAudioReelsSecondAppear;
private AnimatedVectorDrawableCompat recordingStopAudioReelsSecondDisappear;
private AnimatedVectorDrawableCompat recordingStartButtonTransitionBack;
private LayerDrawable mainButtonLayers;
private AnimatedVectorDrawableCompat recordingStatusIconPause;
private boolean stateToRestore = false;
private boolean recordButtonHoverRelease = false;
private boolean recordButtonHoverPressed = false;
private boolean recordButtonLocked = false;
private boolean recordButtonPressed = false;
private enum DarkenState {
TO_DARKEN,
SET_DARKEN,
UNDARKEN_RECORD,
UNDARKEN_END,
}
private enum MainButtonState {
BEFORE_RECORDING_NORMAL,
BEFORE_RECORDING_HOVER,
BEFORE_RECORDING_HOVER_RELEASED,
TRANSITION_TO_RECORDING,
START_RECORDING,
CONTINUE_RECORDING,
WHILE_RECORDING_NORMAL,
WHILE_RECORDING_HOVER,
WHILE_RECORDING_HOVER_RELEASED,
TRANSITION_TO_RECORDING_PAUSE,
WHILE_PAUSE_NORMAL,
WHILE_PAUSE_HOVER,
WHILE_PAUSE_HOVER_RELEASED,
TRANSITION_FROM_PAUSE,
TRANSITION_TO_RECORDING_END,
END_SHOW_REELS,
ENDED_RECORDING_NORMAL,
ENDED_RECORDING_HOVER,
ENDED_RECORDING_HOVER_RELEASED,
TRANSITION_TO_RESTART,
}
private enum MainButtonActionState {
RECORDING_STOPPED,
RECORDING_IN_PROGRESS,
RECORDING_PAUSED,
RECORDING_ENDED,
}
private MainButtonState currentMainButtonState;
private MainButtonState nextMainButtonState = null;
private MainButtonActionState recordingState = MainButtonActionState.RECORDING_STOPPED;
boolean hoverInProgress() {
switch (currentMainButtonState) {
case BEFORE_RECORDING_HOVER:
return recordingStartButtonHover.isRunning();
case WHILE_RECORDING_HOVER:
return recordingBackgroundHover.isRunning();
case WHILE_PAUSE_HOVER:
return recordingBackgroundHover.isRunning();
case ENDED_RECORDING_HOVER:
return recordingBackgroundHover.isRunning();
}
return false;
}
void darkenLayers(ArrayList<Drawable> targetDrawables, float amount, int duration, boolean restore, DarkenState darkState, MainButtonState atState) {
if (darkState == DarkenState.SET_DARKEN) {
int drawablesList = targetDrawables.size();
int drawablesCount = 0;
while (drawablesCount < drawablesList) {
targetDrawables.get(drawablesCount).setColorFilter(new PorterDuffColorFilter(Color.argb((int)(amount*100), 0, 0, 0), PorterDuff.Mode.SRC_ATOP));
drawablesCount += 1;
}
} else {
ValueAnimator colorAnim = ObjectAnimator.ofFloat(0f, amount);
if (restore == true) {
colorAnim = ObjectAnimator.ofFloat(amount, 0f);
}
colorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float state = (float) animation.getAnimatedValue();
int drawablesList = targetDrawables.size();
int drawablesCount = 0;
while (drawablesCount < drawablesList) {
if (state == 0.0) {
targetDrawables.get(drawablesCount).setColorFilter(null);
} else {
targetDrawables.get(drawablesCount).setColorFilter(new PorterDuffColorFilter(Color.argb((int)(state*100), 0, 0, 0), PorterDuff.Mode.SRC_ATOP));
}
drawablesCount += 1;
}
if (((state == amount && restore == false) || (state == 0.0 && restore == true)) && currentMainButtonState == atState) {
if (darkState == DarkenState.TO_DARKEN) {
setMainButtonState(MainButtonState.WHILE_PAUSE_NORMAL);
} else if (darkState == DarkenState.UNDARKEN_RECORD) {
setMainButtonState(MainButtonState.WHILE_RECORDING_NORMAL);
} else if (darkState == DarkenState.UNDARKEN_END) {
setMainButtonState(MainButtonState.TRANSITION_TO_RECORDING_END);
}
}
}
});
colorAnim.setDuration(duration);
colorAnim.start();
}
}
void showCounter(boolean displayCounter, MainButtonState beforeState) {
if (displayCounter == true) {
timeCounter.setScaleX(0.0f);
timeCounter.setScaleY(0.0f);
timerPanel.setVisibility(View.VISIBLE);
ValueAnimator counterShowAnimX = ObjectAnimator.ofFloat(timeCounter, "scaleX", 0f, 1f);
ValueAnimator counterShowAnimY = ObjectAnimator.ofFloat(timeCounter, "scaleY", 0f, 1f);
counterShowAnimX.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float state = (float) animation.getAnimatedValue();
if (state == 1f) {
if (beforeState != null) {
transitionToButtonState(beforeState);
}
}
}
});
counterShowAnimX.setDuration(400);
counterShowAnimY.setDuration(400);
counterShowAnimX.start();
counterShowAnimY.start();
} else {
timeCounter.setScaleX(1.0f);
timeCounter.setScaleY(1.0f);
timerPanel.setVisibility(View.VISIBLE);
ValueAnimator counterShowAnimX = ObjectAnimator.ofFloat(timeCounter, "scaleX", 1f, 0f);
ValueAnimator counterShowAnimY = ObjectAnimator.ofFloat(timeCounter, "scaleY", 1f, 0f);
counterShowAnimX.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float state = (float) animation.getAnimatedValue();
if (state == 0f) {
timerPanel.setVisibility(View.GONE);
if (beforeState != null) {
transitionToButtonState(beforeState);
}
}
}
});
counterShowAnimX.setDuration(400);
counterShowAnimY.setDuration(400);
counterShowAnimX.start();
counterShowAnimY.start();
}
}
private void releaseMainButtonFocus() {
if (currentMainButtonState == MainButtonState.BEFORE_RECORDING_HOVER && recordingStartButtonHover.isRunning() == false) {
setMainButtonState(MainButtonState.BEFORE_RECORDING_HOVER_RELEASED);
} else if (currentMainButtonState == MainButtonState.WHILE_RECORDING_HOVER && recordingBackgroundHover.isRunning() == false) {
setMainButtonState(MainButtonState.WHILE_RECORDING_HOVER_RELEASED);
} else if (currentMainButtonState == MainButtonState.WHILE_PAUSE_HOVER && recordingBackgroundHover.isRunning() == false) {
setMainButtonState(MainButtonState.WHILE_PAUSE_HOVER_RELEASED);
} else if (currentMainButtonState == MainButtonState.ENDED_RECORDING_HOVER && recordingBackgroundHover.isRunning() == false) {
setMainButtonState(MainButtonState.ENDED_RECORDING_HOVER_RELEASED);
}
}
private void updateRecordModeData() {
recordMicrophone = appSettings.getBoolean("checksoundmic", false);
recordPlayback = appSettings.getBoolean("checksoundplayback", false);
if (recordPlayback == true && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
recordPlayback = false;
}
recordOnlyAudio = appSettings.getBoolean("recordmode", false);
if (recordOnlyAudio == true && recordPlayback == false && recordMicrophone == false) {
recordOnlyAudio = false;
}
}
private void transitionToButtonState(MainButtonState toState) {
if (hoverInProgress() == false) {
setMainButtonState(toState);
} else {
nextMainButtonState = toState;
}
}
private void setMainButtonState(MainButtonState state) {
MainButtonState prevState = currentMainButtonState;
currentMainButtonState = state;
nextMainButtonState = null;
switch (state) {
case BEFORE_RECORDING_NORMAL:
recordButtonLocked = false;
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_start));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_start));
recordingStartButtonNormal.setAlpha(255);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
recordingStartCameraMicrophone.setAlpha(0);
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
recordingStartCameraBodyWorking.setAlpha(0);
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
recordingStartCameraHeadphones.setAlpha(0);
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
recordingStartAudioTapeWorking.setAlpha(0);
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
recordingStartAudioMicrophone.setAlpha(0);
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
break;
case BEFORE_RECORDING_HOVER:
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(255);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonHover.start();
break;
case BEFORE_RECORDING_HOVER_RELEASED:
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(255);
recordingStartButtonHoverReleased.start();
break;
case TRANSITION_TO_RECORDING:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_pause));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_pause));
} else {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_stop));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_stop));
}
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(255);
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
recordingStartCameraMicrophone.setAlpha(0);
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
recordingStartCameraBodyWorking.setAlpha(0);
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
recordingStartCameraHeadphones.setAlpha(0);
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
recordingStartAudioTapeWorking.setAlpha(0);
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
recordingStartAudioMicrophone.setAlpha(0);
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
recordingStartButtonTransitionToRecording.start();
break;
case START_RECORDING:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_pause));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_pause));
} else {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_stop));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_stop));
}
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(255);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraLegsAppear.setAlpha(255);
recordingStartCameraLegsAppear.start();
} else {
recordingStartCameraLegsAppear.setAlpha(0);
}
recordingStartCameraLegsDisappear.setAlpha(0);
recordingStartCameraMicrophone.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == false) {
recordingStartCameraMicrophoneAppear.setAlpha(255);
recordingStartCameraMicrophoneAppear.start();
} else {
recordingStartCameraMicrophoneAppear.setAlpha(0);
}
recordingStartCameraMicrophoneDisappear.setAlpha(0);
recordingStartCameraBodyWorking.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraBodyAppear.setAlpha(255);
recordingStartCameraBodyAppear.start();
} else {
recordingStartCameraBodyAppear.setAlpha(0);
}
recordingStartCameraBodyDisappear.setAlpha(0);
recordingStartCameraHeadphones.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == false) {
recordingStartCameraHeadphonesAppear.setAlpha(255);
recordingStartCameraHeadphonesAppear.start();
} else {
recordingStartCameraHeadphonesAppear.setAlpha(0);
}
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioBodyAppear.setAlpha(255);
recordingStartAudioBodyAppear.start();
} else {
recordingStartAudioBodyAppear.setAlpha(0);
}
recordingStartAudioBodyDisappear.setAlpha(0);
recordingStartAudioTapeWorking.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioTapeAppear.setAlpha(255);
recordingStartAudioTapeAppear.start();
} else {
recordingStartAudioTapeAppear.setAlpha(0);
}
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == true) {
recordingStartAudioHeadphonesAppear.setAlpha(255);
recordingStartAudioHeadphonesAppear.start();
} else {
recordingStartAudioHeadphonesAppear.setAlpha(0);
}
recordingStartAudioHeadphonesDisappear.setAlpha(0);
recordingStartAudioMicrophone.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == true) {
recordingStartAudioMicrophoneAppear.setAlpha(255);
recordingStartAudioMicrophoneAppear.start();
} else {
recordingStartAudioMicrophoneAppear.setAlpha(0);
}
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
break;
case WHILE_RECORDING_NORMAL:
recordButtonLocked = false;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_pause));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_pause));
} else {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_stop));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_stop));
}
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(255);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraLegs.setAlpha(255);
} else {
recordingStartCameraLegs.setAlpha(0);
}
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == false) {
recordingStartCameraMicrophone.setAlpha(255);
} else {
recordingStartCameraMicrophone.setAlpha(0);
}
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraBodyWorking.setAlpha(255);
recordingStartCameraBodyWorking.start();
} else {
recordingStartCameraBodyWorking.setAlpha(0);
}
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == false) {
recordingStartCameraHeadphones.setAlpha(255);
} else {
recordingStartCameraHeadphones.setAlpha(0);
}
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioBodyWorking.setAlpha(255);
recordingStartAudioBodyWorking.start();
} else {
recordingStartAudioBodyWorking.setAlpha(0);
}
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioTapeWorking.setAlpha(255);
recordingStartAudioTapeWorking.start();
} else {
recordingStartAudioTapeWorking.setAlpha(0);
}
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == true) {
recordingStartAudioHeadphones.setAlpha(255);
} else {
recordingStartAudioHeadphones.setAlpha(0);
}
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == true) {
recordingStartAudioMicrophone.setAlpha(255);
} else {
recordingStartAudioMicrophone.setAlpha(0);
}
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
break;
case WHILE_RECORDING_HOVER:
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(255);
recordingBackgroundHover.start();
recordingBackgroundHoverReleased.setAlpha(0);
break;
case WHILE_RECORDING_HOVER_RELEASED:
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(255);
recordingBackgroundHoverReleased.start();
break;
case TRANSITION_TO_RECORDING_PAUSE:
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_resume));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_resume));
ArrayList<Drawable> layersToDarken = new ArrayList<Drawable>();
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(255);
recordingBackgroundHoverReleased.start();
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraLegs.setAlpha(255);
layersToDarken.add(recordingStartCameraLegs);
} else {
recordingStartCameraLegs.setAlpha(0);
}
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == false) {
recordingStartCameraMicrophone.setAlpha(255);
layersToDarken.add(recordingStartCameraMicrophone);
} else {
recordingStartCameraMicrophone.setAlpha(0);
}
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraBodyWorking.setAlpha(255);
recordingStartCameraBodyWorking.stop();
layersToDarken.add(recordingStartCameraBodyWorking);
} else {
recordingStartCameraBodyWorking.setAlpha(0);
}
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == false) {
recordingStartCameraHeadphones.setAlpha(255);
layersToDarken.add(recordingStartCameraHeadphones);
} else {
recordingStartCameraHeadphones.setAlpha(0);
}
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioBodyWorking.setAlpha(255);
recordingStartAudioBodyWorking.stop();
layersToDarken.add(recordingStartAudioBodyWorking);
} else {
recordingStartAudioBodyWorking.setAlpha(0);
}
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioTapeWorking.setAlpha(255);
recordingStartAudioTapeWorking.stop();
layersToDarken.add(recordingStartAudioTapeWorking);
} else {
recordingStartAudioTapeWorking.setAlpha(0);
}
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == true) {
recordingStartAudioHeadphones.setAlpha(255);
layersToDarken.add(recordingStartAudioHeadphones);
} else {
recordingStartAudioHeadphones.setAlpha(0);
}
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == true) {
recordingStartAudioMicrophone.setAlpha(255);
layersToDarken.add(recordingStartAudioMicrophone);
} else {
recordingStartAudioMicrophone.setAlpha(0);
}
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
darkenLayers(layersToDarken, 0.8f, 200, false, DarkenState.TO_DARKEN, state);
break;
case WHILE_PAUSE_NORMAL:
recordingState = MainButtonActionState.RECORDING_PAUSED;
recordButtonLocked = false;
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_resume));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_resume));
ArrayList<Drawable> layersSetDark = new ArrayList<Drawable>();
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(255);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraLegs.setAlpha(255);
} else {
recordingStartCameraLegs.setAlpha(0);
}
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == false) {
recordingStartCameraMicrophone.setAlpha(255);
} else {
recordingStartCameraMicrophone.setAlpha(0);
}
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraBodyWorking.setAlpha(255);
recordingStartCameraBodyWorking.stop();
} else {
recordingStartCameraBodyWorking.setAlpha(0);
}
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == false) {
recordingStartCameraHeadphones.setAlpha(255);
layersSetDark.add(recordingStartCameraHeadphones);
} else {
recordingStartCameraHeadphones.setAlpha(0);
}
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioBodyWorking.setAlpha(255);
recordingStartAudioBodyWorking.stop();
layersSetDark.add(recordingStartAudioBodyWorking);
} else {
recordingStartAudioBodyWorking.setAlpha(0);
}
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioTapeWorking.setAlpha(255);
recordingStartAudioTapeWorking.stop();
layersSetDark.add(recordingStartAudioTapeWorking);
} else {
recordingStartAudioTapeWorking.setAlpha(0);
}
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == true) {
recordingStartAudioHeadphones.setAlpha(255);
layersSetDark.add(recordingStartAudioHeadphones);
} else {
recordingStartAudioHeadphones.setAlpha(0);
}
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == true) {
recordingStartAudioMicrophone.setAlpha(255);
layersSetDark.add(recordingStartAudioMicrophone);
} else {
recordingStartAudioMicrophone.setAlpha(0);
}
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
darkenLayers(layersSetDark, 0.8f, 200, false, DarkenState.SET_DARKEN, state);
break;
case WHILE_PAUSE_HOVER:
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(255);
recordingBackgroundHover.start();
recordingBackgroundHoverReleased.setAlpha(0);
break;
case WHILE_PAUSE_HOVER_RELEASED:
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(255);
recordingBackgroundHoverReleased.start();
break;
case TRANSITION_FROM_PAUSE:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_pause));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_pause));
} else {
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_stop));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_stop));
}
ArrayList<Drawable> layersToUndarken = new ArrayList<Drawable>();
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(255);
recordingBackgroundHoverReleased.start();
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraLegs.setAlpha(255);
layersToUndarken.add(recordingStartCameraLegs);
} else {
recordingStartCameraLegs.setAlpha(0);
}
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == false) {
recordingStartCameraMicrophone.setAlpha(255);
layersToUndarken.add(recordingStartCameraMicrophone);
} else {
recordingStartCameraMicrophone.setAlpha(0);
}
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraBodyWorking.setAlpha(255);
recordingStartCameraBodyWorking.stop();
layersToUndarken.add(recordingStartCameraBodyWorking);
} else {
recordingStartCameraBodyWorking.setAlpha(0);
}
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == false) {
recordingStartCameraHeadphones.setAlpha(255);
layersToUndarken.add(recordingStartCameraHeadphones);
} else {
recordingStartCameraHeadphones.setAlpha(0);
}
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioBodyWorking.setAlpha(255);
recordingStartAudioBodyWorking.stop();
layersToUndarken.add(recordingStartAudioBodyWorking);
} else {
recordingStartAudioBodyWorking.setAlpha(0);
}
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioTapeWorking.setAlpha(255);
recordingStartAudioTapeWorking.stop();
layersToUndarken.add(recordingStartAudioTapeWorking);
} else {
recordingStartAudioTapeWorking.setAlpha(0);
}
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == true) {
recordingStartAudioHeadphones.setAlpha(255);
layersToUndarken.add(recordingStartAudioHeadphones);
} else {
recordingStartAudioHeadphones.setAlpha(0);
}
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == true) {
recordingStartAudioMicrophone.setAlpha(255);
layersToUndarken.add(recordingStartAudioMicrophone);
} else {
recordingStartAudioMicrophone.setAlpha(0);
}
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
darkenLayers(layersToUndarken, 0.8f, 200, true, DarkenState.UNDARKEN_RECORD, state);
break;
case TRANSITION_TO_RECORDING_END:
mainRecordingButton.setContentDescription(getResources().getString(R.string.recording_finished_title));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.recording_finished_title));
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(255);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
recordingStartCameraLegsAppear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraLegsDisappear.setAlpha(255);
recordingStartCameraLegsDisappear.start();
} else {
recordingStartCameraLegsDisappear.setAlpha(0);
}
recordingStartCameraMicrophone.setAlpha(0);
recordingStartCameraMicrophoneAppear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == false) {
recordingStartCameraMicrophoneDisappear.setAlpha(255);
recordingStartCameraMicrophoneDisappear.start();
} else {
recordingStartCameraMicrophoneDisappear.setAlpha(0);
}
recordingStartCameraBodyWorking.setAlpha(0);
recordingStartCameraBodyAppear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStartCameraBodyDisappear.setAlpha(255);
recordingStartCameraBodyDisappear.start();
} else {
recordingStartCameraBodyDisappear.setAlpha(0);
}
recordingStartCameraHeadphones.setAlpha(0);
recordingStartCameraHeadphonesAppear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == false) {
recordingStartCameraHeadphonesDisappear.setAlpha(255);
recordingStartCameraHeadphonesDisappear.start();
} else {
recordingStartCameraHeadphonesDisappear.setAlpha(0);
}
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsFirstDisappear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStopCameraReelsSecondDisappear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
recordingStartAudioBodyAppear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioBodyDisappear.setAlpha(255);
recordingStartAudioBodyDisappear.start();
} else {
recordingStartAudioBodyDisappear.setAlpha(0);
}
recordingStartAudioTapeWorking.setAlpha(0);
recordingStartAudioTapeAppear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStartAudioTapeDisappear.setAlpha(255);
recordingStartAudioTapeDisappear.start();
} else {
recordingStartAudioTapeDisappear.setAlpha(0);
}
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
recordingStartAudioHeadphonesAppear.setAlpha(0);
if (recordPlayback == true && recordOnlyAudio == true) {
recordingStartAudioHeadphonesDisappear.setAlpha(255);
recordingStartAudioHeadphonesDisappear.start();
} else {
recordingStartAudioHeadphonesDisappear.setAlpha(0);
}
recordingStartAudioMicrophone.setAlpha(0);
recordingStartAudioMicrophoneAppear.setAlpha(0);
if (recordMicrophone == true && recordOnlyAudio == true) {
recordingStartAudioMicrophoneDisappear.setAlpha(255);
recordingStartAudioMicrophoneDisappear.start();
} else {
recordingStartAudioMicrophoneDisappear.setAlpha(0);
}
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsFirstDisappear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
break;
case END_SHOW_REELS:
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(255);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
recordingStartCameraLegs.setColorFilter(null);
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
recordingStartCameraMicrophone.setAlpha(0);
recordingStartCameraMicrophone.setColorFilter(null);
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
recordingStartCameraBodyWorking.setAlpha(0);
recordingStartCameraBodyWorking.setColorFilter(null);
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
recordingStartCameraHeadphones.setAlpha(0);
recordingStartCameraHeadphones.setColorFilter(null);
recordingStartAudioHeadphones.setColorFilter(null);
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStopCameraReelsFirstAppear.setAlpha(255);
recordingStopCameraReelsFirstAppear.start();
} else {
recordingStopCameraReelsFirstAppear.setAlpha(0);
}
recordingStopCameraReelsFirstDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStopCameraReelsSecondAppear.setAlpha(255);
recordingStopCameraReelsSecondAppear.start();
} else {
recordingStopCameraReelsSecondAppear.setAlpha(0);
}
recordingStopCameraReelsSecondDisappear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
recordingStartAudioBodyWorking.setColorFilter(null);
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
recordingStartAudioTapeWorking.setAlpha(0);
recordingStartAudioTapeWorking.setColorFilter(null);
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
recordingStartAudioMicrophone.setAlpha(0);
recordingStartAudioMicrophone.setColorFilter(null);
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStopAudioReelsFirstAppear.setAlpha(255);
recordingStopAudioReelsFirstAppear.start();
} else {
recordingStopAudioReelsFirstAppear.setAlpha(0);
}
recordingStopAudioReelsFirstDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStopAudioReelsSecondAppear.setAlpha(255);
recordingStopAudioReelsSecondAppear.start();
} else {
recordingStopAudioReelsSecondAppear.setAlpha(0);
}
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
break;
case ENDED_RECORDING_NORMAL:
recordingState = MainButtonActionState.RECORDING_ENDED;
recordButtonLocked = false;
mainRecordingButton.setContentDescription(getResources().getString(R.string.recording_finished_title));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.recording_finished_title));
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(255);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
recordingStartCameraLegs.setColorFilter(null);
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
recordingStartCameraMicrophone.setAlpha(0);
recordingStartCameraMicrophone.setColorFilter(null);
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
recordingStartCameraBodyWorking.setAlpha(0);
recordingStartCameraBodyWorking.setColorFilter(null);
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
recordingStartCameraHeadphones.setAlpha(0);
recordingStartCameraHeadphones.setColorFilter(null);
recordingStartAudioHeadphones.setColorFilter(null);
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStopCameraReelsFirstAppear.setAlpha(255);
} else {
recordingStopCameraReelsFirstAppear.setAlpha(0);
}
recordingStopCameraReelsFirstDisappear.setAlpha(0);
if (recordOnlyAudio == false) {
recordingStopCameraReelsSecondAppear.setAlpha(255);
} else {
recordingStopCameraReelsSecondAppear.setAlpha(0);
}
recordingStopCameraReelsSecondDisappear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
recordingStartAudioBodyWorking.setColorFilter(null);
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
recordingStartAudioTapeWorking.setAlpha(0);
recordingStartAudioTapeWorking.setColorFilter(null);
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
recordingStartAudioMicrophone.setAlpha(0);
recordingStartAudioMicrophone.setColorFilter(null);
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStopAudioReelsFirstAppear.setAlpha(255);
} else {
recordingStopAudioReelsFirstAppear.setAlpha(0);
}
recordingStopAudioReelsFirstDisappear.setAlpha(0);
if (recordOnlyAudio == true) {
recordingStopAudioReelsSecondAppear.setAlpha(255);
} else {
recordingStopAudioReelsSecondAppear.setAlpha(0);
}
recordingStopAudioReelsSecondDisappear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(0);
break;
case ENDED_RECORDING_HOVER:
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(255);
recordingBackgroundHover.start();
recordingBackgroundHoverReleased.setAlpha(0);
break;
case ENDED_RECORDING_HOVER_RELEASED:
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(255);
recordingBackgroundHoverReleased.start();
break;
case TRANSITION_TO_RESTART:
recordingState = MainButtonActionState.RECORDING_STOPPED;
mainRecordingButton.setContentDescription(getResources().getString(R.string.record_start));
TooltipCompat.setTooltipText(mainRecordingButton, getResources().getString(R.string.record_start));
recordingStartButtonNormal.setAlpha(0);
recordingStartButtonHover.setAlpha(0);
recordingStartButtonHoverReleased.setAlpha(0);
recordingStartButtonTransitionToRecording.setAlpha(0);
recordingBackgroundNormal.setAlpha(0);
recordingBackgroundHover.setAlpha(0);
recordingBackgroundHoverReleased.setAlpha(0);
recordingBackgroundTransition.setAlpha(0);
recordingBackgroundTransitionBack.setAlpha(0);
recordingStartCameraLegs.setAlpha(0);
recordingStartCameraLegsAppear.setAlpha(0);
recordingStartCameraLegsDisappear.setAlpha(0);
recordingStartCameraMicrophone.setAlpha(0);
recordingStartCameraMicrophoneAppear.setAlpha(0);
recordingStartCameraMicrophoneDisappear.setAlpha(0);
recordingStartCameraBodyWorking.setAlpha(0);
recordingStartCameraBodyAppear.setAlpha(0);
recordingStartCameraBodyDisappear.setAlpha(0);
recordingStartCameraHeadphones.setAlpha(0);
recordingStartCameraHeadphonesAppear.setAlpha(0);
recordingStartCameraHeadphonesDisappear.setAlpha(0);
recordingStopCameraReelsFirstAppear.setAlpha(0);
recordingStopCameraReelsSecondAppear.setAlpha(0);
recordingStartAudioBodyWorking.setAlpha(0);
recordingStartAudioBodyAppear.setAlpha(0);
recordingStartAudioBodyDisappear.setAlpha(0);
recordingStartAudioTapeWorking.setAlpha(0);
recordingStartAudioTapeAppear.setAlpha(0);
recordingStartAudioTapeDisappear.setAlpha(0);
recordingStartAudioHeadphones.setAlpha(0);
recordingStartAudioHeadphonesAppear.setAlpha(0);
recordingStartAudioHeadphonesDisappear.setAlpha(0);
recordingStartAudioMicrophone.setAlpha(0);
recordingStartAudioMicrophoneAppear.setAlpha(0);
recordingStartAudioMicrophoneDisappear.setAlpha(0);
recordingStopAudioReelsFirstAppear.setAlpha(0);
recordingStopAudioReelsSecondAppear.setAlpha(0);
recordingStartButtonTransitionBack.setAlpha(255);
recordingStartButtonTransitionBack.start();
break;
}
}
public class ActivityBinder extends Binder {
void recordingStart() {
timeCounter.stop();
timeCounter.setBase(recordingBinder.getTimeStart());
timeCounter.start();
audioPlaybackUnavailable.setVisibility(View.GONE);
modesPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.GONE);
recordingState = MainButtonActionState.RECORDING_IN_PROGRESS;
if (stateToRestore == true) {
showCounter(true, MainButtonState.TRANSITION_TO_RECORDING);
} else {
timeCounter.setScaleX(1.0f);
timeCounter.setScaleY(1.0f);
timerPanel.setVisibility(View.VISIBLE);
transitionToButtonState(MainButtonState.WHILE_RECORDING_NORMAL);
}
}
void recordingStop() {
timeCounter.stop();
timeCounter.setBase(SystemClock.elapsedRealtime());
audioPlaybackUnavailable.setVisibility(View.GONE);
modesPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.GONE);
finishedPanel.setVisibility(View.VISIBLE);
recordStop.setVisibility(View.GONE);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
audioPlaybackUnavailable.setVisibility(View.VISIBLE);
}
recordingState = MainButtonActionState.RECORDING_ENDED;
if (stateToRestore == true) {
showCounter(false, MainButtonState.TRANSITION_TO_RECORDING_END);
} else {
timerPanel.setVisibility(View.GONE);
transitionToButtonState(MainButtonState.ENDED_RECORDING_NORMAL);
}
}
void recordingPause(long time) {
timeCounter.setBase(SystemClock.elapsedRealtime()-time);
timeCounter.stop();
modesPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.GONE);
timeCounter.setScaleX(1.0f);
timeCounter.setScaleY(1.0f);
timerPanel.setVisibility(View.VISIBLE);
recordStop.setVisibility(View.VISIBLE);
recordingState = MainButtonActionState.RECORDING_PAUSED;
if (stateToRestore == true) {
transitionToButtonState(MainButtonState.TRANSITION_TO_RECORDING_PAUSE);
} else {
transitionToButtonState(MainButtonState.WHILE_PAUSE_NORMAL);
}
}
void recordingResume(long time) {
timeCounter.setBase(time);
timeCounter.start();
recordStop.setVisibility(View.GONE);
recordingState = MainButtonActionState.RECORDING_IN_PROGRESS;
}
void recordingReset() {
finishedPanel.setVisibility(View.GONE);
optionsPanel.setVisibility(View.VISIBLE);
modesPanel.setVisibility(View.VISIBLE);
transitionToButtonState(MainButtonState.TRANSITION_TO_RESTART);
}
void resetDir(boolean isAudio) {
resetFolder(isAudio);
}
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
recordingBinder = (ScreenRecorder.RecordingBinder)service;
screenRecorderStarted = recordingBinder.isStarted();
recordingBinder.setConnect(new ActivityBinder());
if (serviceToRecording == true) {
serviceToRecording = false;
recordingStart();
}
| EventBus.getDefault().post(new ServiceConnectedEvent(true)); | 1 | 2023-10-09 00:04:13+00:00 | 8k |
lunasaw/gb28181-proxy | gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/transmit/request/message/MessageProcessorClient.java | [
{
"identifier": "BroadcastNotifyMessageHandler",
"path": "gb28181-client/src/main/java/io/github/lunasaw/gbproxy/client/transmit/request/message/handler/notify/BroadcastNotifyMessageHandler.java",
"snippet": "@Component\n@Slf4j\n@Getter\n@Setter\npublic class BroadcastNotifyMessageHandler extends Messag... | import io.github.lunasaw.gb28181.common.entity.response.*;
import io.github.lunasaw.gbproxy.client.transmit.request.message.handler.notify.BroadcastNotifyMessageHandler;
import io.github.lunasaw.gbproxy.client.transmit.request.message.handler.query.CatalogQueryMessageClientHandler;
import io.github.lunasaw.gbproxy.client.transmit.request.message.handler.query.DeviceInfoQueryMessageClientHandler;
import io.github.lunasaw.gbproxy.client.transmit.request.message.handler.query.DeviceStatusQueryMessageClientHandler;
import io.github.lunasaw.gb28181.common.entity.notify.DeviceAlarmNotify;
import io.github.lunasaw.gb28181.common.entity.notify.DeviceBroadcastNotify;
import io.github.lunasaw.gb28181.common.entity.query.DeviceAlarmQuery;
import io.github.lunasaw.gb28181.common.entity.query.DeviceConfigDownload;
import io.github.lunasaw.gb28181.common.entity.query.DeviceRecordQuery; | 3,792 | package io.github.lunasaw.gbproxy.client.transmit.request.message;
/**
* @author luna
* @date 2023/10/18
*/
public interface MessageProcessorClient {
/**
* 获取设备录像信息
* DeviceRecord
* {@link DeviceInfoQueryMessageClientHandler}
*
* @param deviceRecordQuery 设备Id
* @return DeviceInfo
*/
DeviceRecord getDeviceRecord(DeviceRecordQuery deviceRecordQuery);
/**
* 获取设备信息
* DeviceStatus
* {@link DeviceStatusQueryMessageClientHandler}
*
* @param userId 设备Id
* @return DeviceInfo
*/
DeviceStatus getDeviceStatus(String userId);
/**
* 获取设备信息
* DeviceInfo
* {@link DeviceInfoQueryMessageClientHandler}
*
* @param userId 设备Id
* @return DeviceInfo
*/
DeviceInfo getDeviceInfo(String userId);
/**
* 获取设备通道信息
* {@link CatalogQueryMessageClientHandler}
*
* @param userId
* @return
*/
DeviceResponse getDeviceItem(String userId);
/**
* 语音广播通知
* {@link BroadcastNotifyMessageHandler}
*
* @param broadcastNotify
* @return
*/
void broadcastNotify(DeviceBroadcastNotify broadcastNotify);
/**
* 设备告警通知
*
* @param deviceAlarmQuery
* @return
*/ | package io.github.lunasaw.gbproxy.client.transmit.request.message;
/**
* @author luna
* @date 2023/10/18
*/
public interface MessageProcessorClient {
/**
* 获取设备录像信息
* DeviceRecord
* {@link DeviceInfoQueryMessageClientHandler}
*
* @param deviceRecordQuery 设备Id
* @return DeviceInfo
*/
DeviceRecord getDeviceRecord(DeviceRecordQuery deviceRecordQuery);
/**
* 获取设备信息
* DeviceStatus
* {@link DeviceStatusQueryMessageClientHandler}
*
* @param userId 设备Id
* @return DeviceInfo
*/
DeviceStatus getDeviceStatus(String userId);
/**
* 获取设备信息
* DeviceInfo
* {@link DeviceInfoQueryMessageClientHandler}
*
* @param userId 设备Id
* @return DeviceInfo
*/
DeviceInfo getDeviceInfo(String userId);
/**
* 获取设备通道信息
* {@link CatalogQueryMessageClientHandler}
*
* @param userId
* @return
*/
DeviceResponse getDeviceItem(String userId);
/**
* 语音广播通知
* {@link BroadcastNotifyMessageHandler}
*
* @param broadcastNotify
* @return
*/
void broadcastNotify(DeviceBroadcastNotify broadcastNotify);
/**
* 设备告警通知
*
* @param deviceAlarmQuery
* @return
*/ | DeviceAlarmNotify getDeviceAlarmNotify(DeviceAlarmQuery deviceAlarmQuery); | 6 | 2023-10-11 06:56:28+00:00 | 8k |
1415181920/yamis-admin | cocoyam-modules/cocoyam-module-sys/src/main/java/io/xiaoyu/sys/modular/admin/service/impl/AdminUsersServiceImpl.java | [
{
"identifier": "CommonPageRequest",
"path": "cocoyam-common/src/main/java/io/xiaoyu/common/req/CommonPageRequest.java",
"snippet": "@Slf4j\npublic class CommonPageRequest {\n\n private static final String PAGE_SIZE_PARAM_NAME = \"perPage\";\n\n private static final String PAGE_PARAM_NAME = \"page... | import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.xiaoyu.common.req.CommonPageRequest;
import io.xiaoyu.common.basic.service.BaseService;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.ObjectUtil;
import io.xiaoyu.common.exception.CommonException;
import io.xiaoyu.sys.modular.admin.entity.AdminUsersEntity;
import io.xiaoyu.sys.modular.admin.mapper.AdminUsersMapper;
import io.xiaoyu.sys.modular.admin.req.AdminUsersQueryReq;
import io.xiaoyu.sys.modular.admin.resp.AdminUsersQueryResp;
import io.xiaoyu.sys.modular.admin.service.AdminUsersService;
import io.xiaoyu.sys.modular.admin.req.AdminUsersAddReq;
import io.xiaoyu.sys.modular.admin.req.AdminUsersEditReq;
import io.xiaoyu.sys.modular.admin.req.AdminUsersDetailReq;
import io.xiaoyu.common.resp.PageResp;
import org.springframework.stereotype.Service;
import javax.annotation.Resource; | 4,431 | package io.xiaoyu.sys.modular.admin.service.impl;
@Service
public class AdminUsersServiceImpl extends BaseService<AdminUsersMapper,AdminUsersEntity> implements AdminUsersService{
| package io.xiaoyu.sys.modular.admin.service.impl;
@Service
public class AdminUsersServiceImpl extends BaseService<AdminUsersMapper,AdminUsersEntity> implements AdminUsersService{
| public PageResp<AdminUsersEntity> queryList(AdminUsersQueryReq req) { | 11 | 2023-10-09 06:04:30+00:00 | 8k |
Swofty-Developments/Continued-Slime-World-Manager | swoftyworldmanager-nms/src/main/java/net/swofty/swm/nms/craft/CraftSlimeWorld.java | [
{
"identifier": "UnknownWorldException",
"path": "swoftyworldmanager-api/src/main/java/net/swofty/swm/api/exceptions/UnknownWorldException.java",
"snippet": "public class UnknownWorldException extends SlimeException {\n\n public UnknownWorldException(String world) {\n super(\"Unknown world \" ... | import com.flowpowered.nbt.CompoundMap;
import com.flowpowered.nbt.CompoundTag;
import com.flowpowered.nbt.ListTag;
import com.flowpowered.nbt.TagType;
import com.flowpowered.nbt.stream.NBTInputStream;
import com.flowpowered.nbt.stream.NBTOutputStream;
import com.github.luben.zstd.Zstd;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import net.swofty.swm.api.exceptions.UnknownWorldException;
import net.swofty.swm.api.exceptions.WorldAlreadyExistsException;
import net.swofty.swm.api.loaders.SlimeLoader;
import net.swofty.swm.api.utils.SlimeFormat;
import net.swofty.swm.api.world.SlimeChunk;
import net.swofty.swm.api.world.SlimeChunkSection;
import net.swofty.swm.api.world.SlimeWorld;
import net.swofty.swm.api.world.properties.SlimePropertyMap;
import org.bukkit.*;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.Player;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteOrder;
import java.util.*;
import java.util.stream.Collectors;
import static net.swofty.swm.api.world.properties.SlimeProperties.*; | 5,013 | package net.swofty.swm.nms.craft;
@Getter
@Setter
@AllArgsConstructor
public class CraftSlimeWorld implements SlimeWorld {
private SlimeLoader loader;
private final String name;
private final Map<Long, SlimeChunk> chunks;
private final CompoundTag extraData;
private final List<CompoundTag> worldMaps;
private SlimePropertyMap propertyMap;
private final boolean readOnly;
private final boolean locked;
@Override
public SlimeChunk getChunk(int x, int z) {
synchronized (chunks) {
Long index = (((long) z) * Integer.MAX_VALUE + ((long) x));
return chunks.get(index);
}
}
@Override
public void unloadWorld(boolean save, String fallBack) {
World world = Bukkit.getWorld(name);
// Teleport all players outside the world before unloading it
List<Player> players = world.getPlayers();
if (!players.isEmpty()) {
World fallbackWorld = null;
if (fallBack != null) {
fallbackWorld = Bukkit.getWorld(fallBack);
} else {
fallbackWorld = Bukkit.getWorlds().get(0);
}
Location spawnLocation = fallbackWorld.getSpawnLocation();
while (spawnLocation.getBlock().getType() != Material.AIR || spawnLocation.getBlock().getRelative(BlockFace.UP).getType() != Material.AIR) {
spawnLocation.add(0, 1, 0);
}
for (Player player : players) {
player.teleport(spawnLocation);
}
}
if (!Bukkit.unloadWorld(world, save)) {
throw new IllegalStateException("Failed to unload world " + name + ".");
} else {
try {
loader.unlockWorld(name);
} catch (UnknownWorldException | IOException e) {
throw new RuntimeException(e);
}
}
}
public void updateChunk(SlimeChunk chunk) {
if (!chunk.getWorldName().equals(getName())) {
throw new IllegalArgumentException("Chunk (" + chunk.getX() + ", " + chunk.getZ() + ") belongs to world '"
+ chunk.getWorldName() + "', not to '" + getName() + "'!");
}
synchronized (chunks) {
chunks.put(((long) chunk.getZ()) * Integer.MAX_VALUE + ((long) chunk.getX()), chunk);
}
}
@Override
public SlimeWorld clone(String worldName) {
try {
return clone(worldName, null); | package net.swofty.swm.nms.craft;
@Getter
@Setter
@AllArgsConstructor
public class CraftSlimeWorld implements SlimeWorld {
private SlimeLoader loader;
private final String name;
private final Map<Long, SlimeChunk> chunks;
private final CompoundTag extraData;
private final List<CompoundTag> worldMaps;
private SlimePropertyMap propertyMap;
private final boolean readOnly;
private final boolean locked;
@Override
public SlimeChunk getChunk(int x, int z) {
synchronized (chunks) {
Long index = (((long) z) * Integer.MAX_VALUE + ((long) x));
return chunks.get(index);
}
}
@Override
public void unloadWorld(boolean save, String fallBack) {
World world = Bukkit.getWorld(name);
// Teleport all players outside the world before unloading it
List<Player> players = world.getPlayers();
if (!players.isEmpty()) {
World fallbackWorld = null;
if (fallBack != null) {
fallbackWorld = Bukkit.getWorld(fallBack);
} else {
fallbackWorld = Bukkit.getWorlds().get(0);
}
Location spawnLocation = fallbackWorld.getSpawnLocation();
while (spawnLocation.getBlock().getType() != Material.AIR || spawnLocation.getBlock().getRelative(BlockFace.UP).getType() != Material.AIR) {
spawnLocation.add(0, 1, 0);
}
for (Player player : players) {
player.teleport(spawnLocation);
}
}
if (!Bukkit.unloadWorld(world, save)) {
throw new IllegalStateException("Failed to unload world " + name + ".");
} else {
try {
loader.unlockWorld(name);
} catch (UnknownWorldException | IOException e) {
throw new RuntimeException(e);
}
}
}
public void updateChunk(SlimeChunk chunk) {
if (!chunk.getWorldName().equals(getName())) {
throw new IllegalArgumentException("Chunk (" + chunk.getX() + ", " + chunk.getZ() + ") belongs to world '"
+ chunk.getWorldName() + "', not to '" + getName() + "'!");
}
synchronized (chunks) {
chunks.put(((long) chunk.getZ()) * Integer.MAX_VALUE + ((long) chunk.getX()), chunk);
}
}
@Override
public SlimeWorld clone(String worldName) {
try {
return clone(worldName, null); | } catch (WorldAlreadyExistsException | IOException ignored) { | 1 | 2023-10-08 10:54:28+00:00 | 8k |
calicosun258/5c-client-N | src/main/java/fifthcolumn/n/copenheimer/CopeService.java | [
{
"identifier": "NMod",
"path": "src/main/java/fifthcolumn/n/NMod.java",
"snippet": "public class NMod implements ModInitializer {\n\n // You can set this to false to enable cope service. DO THIS AT YOUR OWN RISK due to security reasons as the mod would connect to servers on the internet.\n public s... | import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import fifthcolumn.n.NMod;
import fifthcolumn.n.collar.CollarLogin;
import fifthcolumn.n.events.GrieferUpdateEvent;
import fifthcolumn.n.modules.BanEvasion;
import fifthcolumn.n.modules.GrieferTracer;
import fifthcolumn.n.modules.LarpModule;
import fifthcolumn.n.modules.StreamerMode;
import fifthcolumn.n.modules.WaypointSync;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpResponse.BodyHandlers;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import meteordevelopment.meteorclient.MeteorClient;
import meteordevelopment.meteorclient.mixin.MinecraftClientAccessor;
import meteordevelopment.meteorclient.systems.modules.Modules;
import meteordevelopment.meteorclient.systems.waypoints.Waypoints;
import meteordevelopment.meteorclient.utils.world.Dimension;
import net.minecraft.SharedConstants;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.client.network.ServerInfo;
import net.minecraft.client.util.Session;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.registry.RegistryKey;
import net.minecraft.world.World;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | 6,837 | private ScheduledFuture<?> backgroundActiveRefresh;
private final ConcurrentHashMap<String, Griefer> griefers = new ConcurrentHashMap();
private final LoadingCache<TranslateRequest, CompletableFuture<Optional<TranslateResponse>>> translationCache;
public CopeService() {
this.translationCache = CacheBuilder.newBuilder().maximumSize(1000L).expireAfterAccess(1L, TimeUnit.HOURS).build(new CacheLoader<>() {
public CompletableFuture<Optional<TranslateResponse>> load(TranslateRequest req) throws Exception {
CompletableFuture<Optional<TranslateResponse>> resp = new CompletableFuture();
CopeService.this.executor.execute(() -> {
try {
String content = CopeService.this.post("http://cope.fifthcolumnmc.com/api/text/translate", req);
Optional<TranslateResponse> translateResponse = Optional.ofNullable(CopeService.GSON.fromJson(content, TranslateResponse.class));
resp.complete(translateResponse);
} catch (Throwable var5) {
CopeService.LOGGER.error("CopeService Translate Error", var5);
resp.complete(Optional.empty());
}
});
return resp;
}
});
}
public List<Griefer> griefers() {
return new ArrayList(this.griefers.values());
}
public void find(BiConsumer<List<Server>, List<Server>> resultConsumer) {
this.currentFindRequest.skip = 0;
this.doFind(resultConsumer);
}
public void findMore(BiConsumer<List<Server>, List<Server>> resultConsumer) {
FindServersRequest var2 = this.currentFindRequest;
var2.skip = var2.skip + this.currentFindRequest.limit;
this.doFind(resultConsumer);
}
private void doFind(BiConsumer<List<Server>, List<Server>> resultConsumer) {
this.loading.set(true);
this.executor.execute(() -> {
try {
String content = this.post("http://cope.fifthcolumnmc.com/api/servers/find", this.currentFindRequest);
FindServersResponse servers = GSON.fromJson(content, FindServersResponse.class);
this.loading.set(false);
resultConsumer.accept(servers.searchResult, servers.activeServers);
} catch (Throwable var4) {
LOGGER.error("CopeService Find Error", var4);
this.loading.set(false);
}
});
}
public void update(UpdateServerRequest req, Consumer<Server> serverConsumer) {
this.executor.execute(() -> {
try {
String content = this.post("http://cope.fifthcolumnmc.com/api/servers/update", req);
serverConsumer.accept(GSON.fromJson(content, Server.class));
} catch (Throwable var4) {
LOGGER.error("CopeService Update Error", var4);
}
});
}
public void findHistoricalPlayers(Consumer<List<ServerPlayer>> playersConsumer) {
this.createFindPlayersRequest().ifPresent((req) -> {
this.executor.execute(() -> {
try {
String content = this.post("http://cope.fifthcolumnmc.com/api/servers/findPlayers", req);
playersConsumer.accept(GSON.fromJson(content, (new TypeToken<ArrayList<ServerPlayer>>() {
}).getType()));
} catch (Throwable var4) {
LOGGER.error("CopeService FindPlayers Error", var4);
}
});
});
}
public CompletableFuture<Optional<TranslateResponse>> translate(TranslateRequest request) {
return this.translationCache.getUnchecked(request);
}
public void getAccount(Consumer<GetAccountResponse> consumer) {
this.executor.execute(() -> {
String response = this.httpGet("http://cope.fifthcolumnmc.com/api/accounts/alt");
consumer.accept(GSON.fromJson(response, GetAccountResponse.class));
});
}
public void useNewAlternateAccount(Consumer<Session> sessionConsumer) {
this.getAccount((resp) -> {
String username = BanEvasion.isSpacesToNameEnabled() ? " " + resp.username + " " : resp.username;
Session session = new Session(username, resp.uuid, resp.token, Optional.empty(), Optional.empty(), Session.AccountType.MSA);
((MinecraftClientAccessor)MeteorClient.mc).setSession(session);
MeteorClient.mc.getSessionProperties().clear();
MeteorClient.mc.execute(() -> {
sessionConsumer.accept(session);
});
});
}
private void setActive(ActiveServerRequest req) {
try {
String body = this.post("http://cope.fifthcolumnmc.com/api/servers/active", req);
ActiveServerResponse resp = GSON.fromJson(body, ActiveServerResponse.class);
resp.griefers.forEach((griefer) -> {
this.griefers.put(griefer.profileName, griefer);
});
MeteorClient.EVENT_BUS.post(new GrieferUpdateEvent(resp.griefers));
} catch (Throwable var4) {
LOGGER.error("CopeService Active Server Error", var4);
}
}
private String post(String url, Object req) { | package fifthcolumn.n.copenheimer;
public final class CopeService {
private static final Logger LOGGER = LoggerFactory.getLogger(CopeService.class);
private static final String BASE_URL = "http://cope.fifthcolumnmc.com/";
private static final Long backgroundRefreshIntervalSeconds = 5L;
private static final Gson GSON = new Gson();
private final HttpClient clientDelegate = HttpClient.newBuilder().build();
public final FindServersRequest currentFindRequest = defaultFindRequest();
public final Executor executor = Executors.newFixedThreadPool(3, (r) -> {
Thread thread = new Thread(r);
thread.setName("CopeService");
return thread;
});
public AtomicBoolean loading = new AtomicBoolean(false);
public final ScheduledExecutorService backgroundActiveExecutorService = new ScheduledThreadPoolExecutor(1);
private ServerInfo currentServer;
private ServerInfo serverInfo;
private Session defaultSession;
private ScheduledFuture<?> backgroundActiveRefresh;
private final ConcurrentHashMap<String, Griefer> griefers = new ConcurrentHashMap();
private final LoadingCache<TranslateRequest, CompletableFuture<Optional<TranslateResponse>>> translationCache;
public CopeService() {
this.translationCache = CacheBuilder.newBuilder().maximumSize(1000L).expireAfterAccess(1L, TimeUnit.HOURS).build(new CacheLoader<>() {
public CompletableFuture<Optional<TranslateResponse>> load(TranslateRequest req) throws Exception {
CompletableFuture<Optional<TranslateResponse>> resp = new CompletableFuture();
CopeService.this.executor.execute(() -> {
try {
String content = CopeService.this.post("http://cope.fifthcolumnmc.com/api/text/translate", req);
Optional<TranslateResponse> translateResponse = Optional.ofNullable(CopeService.GSON.fromJson(content, TranslateResponse.class));
resp.complete(translateResponse);
} catch (Throwable var5) {
CopeService.LOGGER.error("CopeService Translate Error", var5);
resp.complete(Optional.empty());
}
});
return resp;
}
});
}
public List<Griefer> griefers() {
return new ArrayList(this.griefers.values());
}
public void find(BiConsumer<List<Server>, List<Server>> resultConsumer) {
this.currentFindRequest.skip = 0;
this.doFind(resultConsumer);
}
public void findMore(BiConsumer<List<Server>, List<Server>> resultConsumer) {
FindServersRequest var2 = this.currentFindRequest;
var2.skip = var2.skip + this.currentFindRequest.limit;
this.doFind(resultConsumer);
}
private void doFind(BiConsumer<List<Server>, List<Server>> resultConsumer) {
this.loading.set(true);
this.executor.execute(() -> {
try {
String content = this.post("http://cope.fifthcolumnmc.com/api/servers/find", this.currentFindRequest);
FindServersResponse servers = GSON.fromJson(content, FindServersResponse.class);
this.loading.set(false);
resultConsumer.accept(servers.searchResult, servers.activeServers);
} catch (Throwable var4) {
LOGGER.error("CopeService Find Error", var4);
this.loading.set(false);
}
});
}
public void update(UpdateServerRequest req, Consumer<Server> serverConsumer) {
this.executor.execute(() -> {
try {
String content = this.post("http://cope.fifthcolumnmc.com/api/servers/update", req);
serverConsumer.accept(GSON.fromJson(content, Server.class));
} catch (Throwable var4) {
LOGGER.error("CopeService Update Error", var4);
}
});
}
public void findHistoricalPlayers(Consumer<List<ServerPlayer>> playersConsumer) {
this.createFindPlayersRequest().ifPresent((req) -> {
this.executor.execute(() -> {
try {
String content = this.post("http://cope.fifthcolumnmc.com/api/servers/findPlayers", req);
playersConsumer.accept(GSON.fromJson(content, (new TypeToken<ArrayList<ServerPlayer>>() {
}).getType()));
} catch (Throwable var4) {
LOGGER.error("CopeService FindPlayers Error", var4);
}
});
});
}
public CompletableFuture<Optional<TranslateResponse>> translate(TranslateRequest request) {
return this.translationCache.getUnchecked(request);
}
public void getAccount(Consumer<GetAccountResponse> consumer) {
this.executor.execute(() -> {
String response = this.httpGet("http://cope.fifthcolumnmc.com/api/accounts/alt");
consumer.accept(GSON.fromJson(response, GetAccountResponse.class));
});
}
public void useNewAlternateAccount(Consumer<Session> sessionConsumer) {
this.getAccount((resp) -> {
String username = BanEvasion.isSpacesToNameEnabled() ? " " + resp.username + " " : resp.username;
Session session = new Session(username, resp.uuid, resp.token, Optional.empty(), Optional.empty(), Session.AccountType.MSA);
((MinecraftClientAccessor)MeteorClient.mc).setSession(session);
MeteorClient.mc.getSessionProperties().clear();
MeteorClient.mc.execute(() -> {
sessionConsumer.accept(session);
});
});
}
private void setActive(ActiveServerRequest req) {
try {
String body = this.post("http://cope.fifthcolumnmc.com/api/servers/active", req);
ActiveServerResponse resp = GSON.fromJson(body, ActiveServerResponse.class);
resp.griefers.forEach((griefer) -> {
this.griefers.put(griefer.profileName, griefer);
});
MeteorClient.EVENT_BUS.post(new GrieferUpdateEvent(resp.griefers));
} catch (Throwable var4) {
LOGGER.error("CopeService Active Server Error", var4);
}
}
private String post(String url, Object req) { | if(NMod.COPE_OFFLINE_MODE) | 0 | 2023-10-14 19:18:35+00:00 | 8k |
dadegrande99/HikeMap | app/src/main/java/com/usi/hikemap/ui/viewmodel/ProfileViewModel.java | [
{
"identifier": "AuthenticationResponse",
"path": "app/src/main/java/com/usi/hikemap/model/AuthenticationResponse.java",
"snippet": "public class AuthenticationResponse {\n\n private boolean success;\n private String message;\n\n public AuthenticationResponse() {\n\n }\n\n public boolean ... | import android.app.Application;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import com.usi.hikemap.model.AuthenticationResponse;
import com.usi.hikemap.model.Route;
import com.usi.hikemap.model.User;
import com.usi.hikemap.repository.IManagerRepository;
import com.usi.hikemap.repository.ManagerRepository;
import java.util.List;
import java.util.Map; | 5,111 | package com.usi.hikemap.ui.viewmodel;
public class ProfileViewModel extends AndroidViewModel {
private MutableLiveData<AuthenticationResponse> mAuthenticationResponse; | package com.usi.hikemap.ui.viewmodel;
public class ProfileViewModel extends AndroidViewModel {
private MutableLiveData<AuthenticationResponse> mAuthenticationResponse; | private MutableLiveData<User> mUserLiveData; | 2 | 2023-10-09 14:23:22+00:00 | 8k |
zyyzyykk/kkTerminal | terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Consumer/WebSocketServer.java | [
{
"identifier": "AppConfig",
"path": "terminalBackend/terminal/src/main/java/com/kkbpro/terminal/Config/AppConfig.java",
"snippet": "@Component\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AppConfig {\n\n /**\n * 欢迎语\n */\n @Value(\"${kk.welcome:}\")\n private String we... | import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.lalyos.jfiglet.FigletFont;
import com.kkbpro.terminal.Config.AppConfig;
import com.kkbpro.terminal.Constants.Enum.MessageInfoTypeRnum;
import com.kkbpro.terminal.Constants.Enum.ResultCodeEnum;
import com.kkbpro.terminal.Pojo.EnvInfo;
import com.kkbpro.terminal.Pojo.MessageInfo;
import com.kkbpro.terminal.Result.Result;
import com.kkbpro.terminal.Utils.AesUtil;
import com.kkbpro.terminal.Utils.FileUtil;
import com.kkbpro.terminal.Utils.StringUtil;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.transport.verification.PromiscuousVerifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; | 4,690 | package com.kkbpro.terminal.Consumer;
@Component
@ServerEndpoint("/socket/ssh/{env}") // 注意不要以'/'结尾
public class WebSocketServer {
public static ConcurrentHashMap<String, SSHClient> sshClientMap = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, EnvInfo> envInfoMap = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, String> fileUploadingMap = new ConcurrentHashMap<>();
private static AppConfig appConfig;
private Session sessionSocket = null;
private String sshKey = null;
private SSHClient sshClient;
private net.schmizz.sshj.connection.channel.direct.Session.Shell shell = null;
private InputStream shellInputStream;
private OutputStream shellOutputStream;
private Thread shellOutThread;
@Autowired
public void setAppConfig(AppConfig appConfig) {
WebSocketServer.appConfig = appConfig;
}
@OnOpen
public void onOpen(Session sessionSocket, @PathParam("env") String env) throws IOException {
EnvInfo envInfo =
JSONObject.parseObject(AesUtil.aesDecrypt(StringUtil.changeStr(env)),EnvInfo.class);
// 建立 web-socket 连接
this.sessionSocket = sessionSocket;
// 设置最大空闲超时(上线后失效???)
sessionSocket.setMaxIdleTimeout(appConfig.getMaxIdleTimeout());
// 与服务器建立连接
String host = envInfo.getServer_ip();
int port = envInfo.getServer_port();
String user_name = envInfo.getServer_user();
String password = envInfo.getServer_password();
sshClient = new SSHClient();
try {
sshClient.setConnectTimeout(appConfig.getSshMaxTimeout());
sshClient.addHostKeyVerifier(new PromiscuousVerifier()); // 不验证主机密钥
sshClient.connect(host,port);
sshClient.authPassword(user_name, password); // 使用用户名和密码进行身份验证
} catch (Exception e) {
e.printStackTrace(); | package com.kkbpro.terminal.Consumer;
@Component
@ServerEndpoint("/socket/ssh/{env}") // 注意不要以'/'结尾
public class WebSocketServer {
public static ConcurrentHashMap<String, SSHClient> sshClientMap = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, EnvInfo> envInfoMap = new ConcurrentHashMap<>();
public static ConcurrentHashMap<String, String> fileUploadingMap = new ConcurrentHashMap<>();
private static AppConfig appConfig;
private Session sessionSocket = null;
private String sshKey = null;
private SSHClient sshClient;
private net.schmizz.sshj.connection.channel.direct.Session.Shell shell = null;
private InputStream shellInputStream;
private OutputStream shellOutputStream;
private Thread shellOutThread;
@Autowired
public void setAppConfig(AppConfig appConfig) {
WebSocketServer.appConfig = appConfig;
}
@OnOpen
public void onOpen(Session sessionSocket, @PathParam("env") String env) throws IOException {
EnvInfo envInfo =
JSONObject.parseObject(AesUtil.aesDecrypt(StringUtil.changeStr(env)),EnvInfo.class);
// 建立 web-socket 连接
this.sessionSocket = sessionSocket;
// 设置最大空闲超时(上线后失效???)
sessionSocket.setMaxIdleTimeout(appConfig.getMaxIdleTimeout());
// 与服务器建立连接
String host = envInfo.getServer_ip();
int port = envInfo.getServer_port();
String user_name = envInfo.getServer_user();
String password = envInfo.getServer_password();
sshClient = new SSHClient();
try {
sshClient.setConnectTimeout(appConfig.getSshMaxTimeout());
sshClient.addHostKeyVerifier(new PromiscuousVerifier()); // 不验证主机密钥
sshClient.connect(host,port);
sshClient.authPassword(user_name, password); // 使用用户名和密码进行身份验证
} catch (Exception e) {
e.printStackTrace(); | sendMessage(sessionSocket,"连接服务器失败","fail", ResultCodeEnum.CONNECT_FAIL.getState()); | 2 | 2023-10-14 08:05:24+00:00 | 8k |
ZJU-ACES-ISE/chatunitest-core | src/main/java/zju/cst/aces/util/AskGPT.java | [
{
"identifier": "Config",
"path": "src/main/java/zju/cst/aces/api/config/Config.java",
"snippet": "@Getter\n@Setter\npublic class Config {\n public String date;\n public Gson GSON;\n public Project project;\n public JavaParser parser;\n public JavaParserFacade parserFacade;\n public Li... | import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import zju.cst.aces.api.config.Config;
import zju.cst.aces.api.config.ModelConfig;
import zju.cst.aces.dto.Message;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects; | 5,459 | package zju.cst.aces.util;
public class AskGPT {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
public Config config;
public AskGPT(Config config) {
this.config = config;
}
| package zju.cst.aces.util;
public class AskGPT {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
public Config config;
public AskGPT(Config config) {
this.config = config;
}
| public Response askChatGPT(List<Message> messages) { | 2 | 2023-10-14 07:15:10+00:00 | 8k |
Nyayurn/Yutori-QQ | src/main/java/io/github/nyayurn/yutori/qq/listener/EventListenerContainer.java | [
{
"identifier": "Bot",
"path": "src/main/java/io/github/nyayurn/yutori/qq/entity/event/Bot.java",
"snippet": "@Data\npublic class Bot {\n /**\n * QQ 号\n */\n private String id;\n private ChannelApi channelApi;\n private GuildApi guildApi;\n private GuildMemberApi guildMemberApi;\n... | import io.github.nyayurn.yutori.qq.entity.event.Bot;
import io.github.nyayurn.yutori.qq.event.guild.GuildEvent;
import io.github.nyayurn.yutori.qq.event.guild.GuildMemberEvent;
import io.github.nyayurn.yutori.qq.event.guild.GuildRoleEvent;
import io.github.nyayurn.yutori.qq.event.message.GroupMessageEvent;
import io.github.nyayurn.yutori.qq.event.message.MessageEvent;
import io.github.nyayurn.yutori.qq.event.message.PrivateMessageEvent;
import io.github.nyayurn.yutori.qq.event.user.FriendRequestEvent;
import io.github.nyayurn.yutori.qq.listener.guild.GuildAddedListener;
import io.github.nyayurn.yutori.qq.listener.guild.GuildRemovedListener;
import io.github.nyayurn.yutori.qq.listener.guild.GuildRequestListener;
import io.github.nyayurn.yutori.qq.listener.guild.GuildUpdatedListener;
import io.github.nyayurn.yutori.qq.listener.guild.member.GuildMemberAddedListener;
import io.github.nyayurn.yutori.qq.listener.guild.member.GuildMemberRemovedListener;
import io.github.nyayurn.yutori.qq.listener.guild.member.GuildMemberRequestListener;
import io.github.nyayurn.yutori.qq.listener.guild.member.GuildMemberUpdatedListener;
import io.github.nyayurn.yutori.qq.listener.guild.role.GuildRoleCreatedListener;
import io.github.nyayurn.yutori.qq.listener.guild.role.GuildRoleDeletedListener;
import io.github.nyayurn.yutori.qq.listener.guild.role.GuildRoleUpdatedListener;
import io.github.nyayurn.yutori.qq.listener.login.LoginAddedListener;
import io.github.nyayurn.yutori.qq.listener.login.LoginRemovedListener;
import io.github.nyayurn.yutori.qq.listener.login.LoginUpdatedListener;
import io.github.nyayurn.yutori.qq.listener.message.created.GroupMessageCreatedListener;
import io.github.nyayurn.yutori.qq.listener.message.created.MessageCreatedListener;
import io.github.nyayurn.yutori.qq.listener.message.created.PrivateMessageCreatedListener;
import io.github.nyayurn.yutori.qq.listener.message.deleted.GroupMessageDeletedListener;
import io.github.nyayurn.yutori.qq.listener.message.deleted.MessageDeletedListener;
import io.github.nyayurn.yutori.qq.listener.message.deleted.PrivateMessageDeletedListener;
import io.github.nyayurn.yutori.qq.listener.user.FriendRequestListener;
import lombok.Data;
import java.util.ArrayList;
import java.util.List; | 4,261 | /*
Copyright (c) 2023 Yurn
yutori-qq is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
package io.github.nyayurn.yutori.qq.listener;
/**
* @author Yurn
*/
@Data
public class EventListenerContainer {
public final List<GuildAddedListener> onGuildAddedListenerDelegate = new ArrayList<>();
public final List<GuildUpdatedListener> onGuildUpdatedListenerDelegate = new ArrayList<>();
public final List<GuildRemovedListener> onGuildRemovedListenerDelegate = new ArrayList<>();
public final List<GuildRequestListener> onGuildRequestListenerDelegate = new ArrayList<>();
public final List<GuildMemberAddedListener> onGuildMemberAddedListenerDelegate = new ArrayList<>(); | /*
Copyright (c) 2023 Yurn
yutori-qq is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
*/
package io.github.nyayurn.yutori.qq.listener;
/**
* @author Yurn
*/
@Data
public class EventListenerContainer {
public final List<GuildAddedListener> onGuildAddedListenerDelegate = new ArrayList<>();
public final List<GuildUpdatedListener> onGuildUpdatedListenerDelegate = new ArrayList<>();
public final List<GuildRemovedListener> onGuildRemovedListenerDelegate = new ArrayList<>();
public final List<GuildRequestListener> onGuildRequestListenerDelegate = new ArrayList<>();
public final List<GuildMemberAddedListener> onGuildMemberAddedListenerDelegate = new ArrayList<>(); | public final List<GuildMemberUpdatedListener> onGuildMemberUpdatedListenerDelegate = new ArrayList<>(); | 15 | 2023-10-12 09:58:07+00:00 | 8k |
villainwtf/weave | src/main/java/wtf/villain/weave/builder/WeaveInstanceBuilder.java | [
{
"identifier": "Weave",
"path": "src/main/java/wtf/villain/weave/Weave.java",
"snippet": "public sealed interface Weave permits Weave.Impl {\n\n @NotNull\n static WeaveInstanceBuilder builder() {\n return new WeaveInstanceBuilder();\n }\n\n /**\n * Gets the underlying Retrofit cl... | import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;
import wtf.villain.weave.Weave;
import wtf.villain.weave.client.TolgeeClient;
import wtf.villain.weave.storage.Storage;
import wtf.villain.weave.translation.process.PostProcessor;
import wtf.villain.weave.util.Ensure;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture; | 3,702 | package wtf.villain.weave.builder;
public final class WeaveInstanceBuilder {
@Nullable
private String apiKey;
@Nullable
private String endpoint;
@NotNull
private final List<Integer> projectIds = new ArrayList<>();
@NotNull
private Duration connectTimeout = Duration.ofSeconds(30);
@NotNull
private Duration readTimeout = Duration.ofSeconds(30);
@NotNull
private Duration writeTimeout = Duration.ofSeconds(30);
@NotNull
private final List<PostProcessor> processors = new ArrayList<>();
/**
* Sets the API key to use for the Tolgee client.
*
* @param apiKey the API key
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder apiKey(@NotNull String apiKey) {
this.apiKey = apiKey;
return this;
}
/**
* Sets the endpoint to use for the Tolgee client.
*
* @param endpoint the endpoint
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder endpoint(@NotNull String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Adds the given project IDs to the Tolgee client.
*
* @param projectIds the project IDs
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder addProjects(int... projectIds) {
for (int projectId : projectIds) {
this.projectIds.add(projectId);
}
return this;
}
/**
* Sets the connect timeout for the Tolgee client.
*
* @param connectTimeout the connect timeout
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder connectTimeout(@NotNull Duration connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
/**
* Sets the read timeout for the Tolgee client.
*
* @param readTimeout the read timeout
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder readTimeout(@NotNull Duration readTimeout) {
this.readTimeout = readTimeout;
return this;
}
/**
* Sets the write timeout for the Tolgee client.
*
* @param writeTimeout the write timeout
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder writeTimeout(@NotNull Duration writeTimeout) {
this.writeTimeout = writeTimeout;
return this;
}
/**
* Adds the given translation post processors to the Tolgee client.
*
* @param processors the translation post processors
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder addProcessors(@NotNull PostProcessor... processors) {
this.processors.addAll(Arrays.asList(processors));
return this;
}
/**
* Builds the Tolgee client synchronously.
*
* @return the Tolgee client
*/
@NotNull
public Weave build() {
return buildAsync().join();
}
/**
* Builds the Tolgee client asynchronously.
*
* @return a future that completes when the Tolgee client is built
*/
@NotNull
public CompletableFuture<Weave> buildAsync() {
Ensure.argumentIsSet(apiKey, "apiKey");
Ensure.argumentIsSet(endpoint, "endpoint");
Ensure.that(!projectIds.isEmpty(), "projectIds must contain at least one project ID");
Ensure.argumentIsSet(connectTimeout, "connectTimeout");
Ensure.argumentIsSet(readTimeout, "readTimeout");
Ensure.argumentIsSet(writeTimeout, "writeTimeout");
Ensure.that(connectTimeout.toMillis() > 0, "connectTimeout must be greater than zero");
Ensure.that(readTimeout.toMillis() > 0, "readTimeout must be greater than zero");
Ensure.that(writeTimeout.toMillis() > 0, "writeTimeout must be greater than zero");
CompletableFuture<Weave> future = new CompletableFuture<>();
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new TolgeeInterceptor(apiKey))
.connectTimeout(connectTimeout)
.readTimeout(readTimeout)
.writeTimeout(writeTimeout)
.build();
| package wtf.villain.weave.builder;
public final class WeaveInstanceBuilder {
@Nullable
private String apiKey;
@Nullable
private String endpoint;
@NotNull
private final List<Integer> projectIds = new ArrayList<>();
@NotNull
private Duration connectTimeout = Duration.ofSeconds(30);
@NotNull
private Duration readTimeout = Duration.ofSeconds(30);
@NotNull
private Duration writeTimeout = Duration.ofSeconds(30);
@NotNull
private final List<PostProcessor> processors = new ArrayList<>();
/**
* Sets the API key to use for the Tolgee client.
*
* @param apiKey the API key
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder apiKey(@NotNull String apiKey) {
this.apiKey = apiKey;
return this;
}
/**
* Sets the endpoint to use for the Tolgee client.
*
* @param endpoint the endpoint
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder endpoint(@NotNull String endpoint) {
this.endpoint = endpoint;
return this;
}
/**
* Adds the given project IDs to the Tolgee client.
*
* @param projectIds the project IDs
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder addProjects(int... projectIds) {
for (int projectId : projectIds) {
this.projectIds.add(projectId);
}
return this;
}
/**
* Sets the connect timeout for the Tolgee client.
*
* @param connectTimeout the connect timeout
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder connectTimeout(@NotNull Duration connectTimeout) {
this.connectTimeout = connectTimeout;
return this;
}
/**
* Sets the read timeout for the Tolgee client.
*
* @param readTimeout the read timeout
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder readTimeout(@NotNull Duration readTimeout) {
this.readTimeout = readTimeout;
return this;
}
/**
* Sets the write timeout for the Tolgee client.
*
* @param writeTimeout the write timeout
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder writeTimeout(@NotNull Duration writeTimeout) {
this.writeTimeout = writeTimeout;
return this;
}
/**
* Adds the given translation post processors to the Tolgee client.
*
* @param processors the translation post processors
* @return the builder
*/
@NotNull
public WeaveInstanceBuilder addProcessors(@NotNull PostProcessor... processors) {
this.processors.addAll(Arrays.asList(processors));
return this;
}
/**
* Builds the Tolgee client synchronously.
*
* @return the Tolgee client
*/
@NotNull
public Weave build() {
return buildAsync().join();
}
/**
* Builds the Tolgee client asynchronously.
*
* @return a future that completes when the Tolgee client is built
*/
@NotNull
public CompletableFuture<Weave> buildAsync() {
Ensure.argumentIsSet(apiKey, "apiKey");
Ensure.argumentIsSet(endpoint, "endpoint");
Ensure.that(!projectIds.isEmpty(), "projectIds must contain at least one project ID");
Ensure.argumentIsSet(connectTimeout, "connectTimeout");
Ensure.argumentIsSet(readTimeout, "readTimeout");
Ensure.argumentIsSet(writeTimeout, "writeTimeout");
Ensure.that(connectTimeout.toMillis() > 0, "connectTimeout must be greater than zero");
Ensure.that(readTimeout.toMillis() > 0, "readTimeout must be greater than zero");
Ensure.that(writeTimeout.toMillis() > 0, "writeTimeout must be greater than zero");
CompletableFuture<Weave> future = new CompletableFuture<>();
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(new TolgeeInterceptor(apiKey))
.connectTimeout(connectTimeout)
.readTimeout(readTimeout)
.writeTimeout(writeTimeout)
.build();
| TolgeeClient tolgeeClient = new Retrofit.Builder() | 1 | 2023-10-09 13:46:52+00:00 | 8k |
jmdevall/opencodeplan | src/main/java/jmdevall/opencodeplan/domain/promptmaker/Context.java | [
{
"identifier": "Repository",
"path": "src/main/java/jmdevall/opencodeplan/application/port/out/repository/Repository.java",
"snippet": "public interface Repository {\n\n\tList<SourceFolder> getBuildPath();\n\t\n\tCuSource getCuSource();\n\n void save(String filepath, String newFileContent);\n}"
},... | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import jmdevall.opencodeplan.application.port.out.repository.Repository;
import jmdevall.opencodeplan.domain.Fragment;
import jmdevall.opencodeplan.domain.dependencygraph.DependencyGraph;
import jmdevall.opencodeplan.domain.dependencygraph.Node;
import jmdevall.opencodeplan.domain.dependencygraph.NodeId;
import jmdevall.opencodeplan.domain.plangraph.PlanGraph;
import jmdevall.opencodeplan.domain.plangraph.TemporalContext;
import jmdevall.opencodeplan.domain.dependencygraph.DependencyRelation;
import lombok.Getter; | 5,291 | package jmdevall.opencodeplan.domain.promptmaker;
/**
* The context of the edit
(line 38–41) consists of (a) spatial context, which contains related code such as methods
called from the block 𝐵, and
(b) temporal context, which contains the previous edits that
caused the need to edit the block 𝐵. The temporal context is formed by edits along the paths
from the root nodes of the plan graph to 𝐵.
*/
@Getter
public class Context {
private List<String> spatialContext; | package jmdevall.opencodeplan.domain.promptmaker;
/**
* The context of the edit
(line 38–41) consists of (a) spatial context, which contains related code such as methods
called from the block 𝐵, and
(b) temporal context, which contains the previous edits that
caused the need to edit the block 𝐵. The temporal context is formed by edits along the paths
from the root nodes of the plan graph to 𝐵.
*/
@Getter
public class Context {
private List<String> spatialContext; | private TemporalContext temporalContext; | 6 | 2023-10-14 18:27:18+00:00 | 8k |
eahau/douyin-openapi | generator/src/main/java/com/github/eahau/openapi/douyin/generator/parser/HtmlParser.java | [
{
"identifier": "DocField",
"path": "generator/src/main/java/com/github/eahau/openapi/douyin/generator/DocField.java",
"snippet": "@Getter\n@Setter\npublic class DocField {\n\n /**\n * 字段名称.\n */\n @SerializedName(value = \"name\", alternate = {\"key\"})\n private String name = \"\";\n\... | import com.github.eahau.openapi.douyin.generator.DocField;
import com.github.eahau.openapi.douyin.generator.GeneratorContent;
import com.github.eahau.openapi.douyin.generator.GeneratorContent.GeneratorContentBuilder;
import com.github.eahau.openapi.douyin.generator.Misc;
import com.github.eahau.openapi.douyin.generator.api.DouYinOpenDocApi.DocResponse;
import com.google.common.collect.ImmutableRangeMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Range;
import com.google.common.collect.RangeMap;
import com.google.common.collect.Streams;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.Configuration.Defaults;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import com.jayway.jsonpath.spi.json.GsonJsonProvider;
import com.jayway.jsonpath.spi.json.JsonProvider;
import com.jayway.jsonpath.spi.mapper.GsonMappingProvider;
import com.jayway.jsonpath.spi.mapper.MappingProvider;
import com.vladsch.flexmark.ast.Heading;
import com.vladsch.flexmark.ast.HtmlBlock;
import com.vladsch.flexmark.ast.ListBlock;
import com.vladsch.flexmark.ast.Paragraph;
import com.vladsch.flexmark.ast.Text;
import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.ast.Block;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import io.swagger.v3.oas.models.PathItem.HttpMethod;
import io.swagger.v3.oas.models.servers.Server;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream; | 7,071 | /*
* Copyright 2023 eahau@foxmail.com
*
* 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.github.eahau.openapi.douyin.generator.parser;
@Slf4j
public class HtmlParser {
static final Parser PARSER = Parser.builder()
.extensions(Collections.singletonList(TablesExtension.create()))
.build();
static {
Configuration.setDefaults(
new Defaults() {
final JsonProvider jsonProvider = new GsonJsonProvider(Misc.GSON);
final MappingProvider mappingProvider = new GsonMappingProvider(Misc.GSON);
@Override
public JsonProvider jsonProvider() {
return jsonProvider;
}
@Override
public Set<Option> options() {
return EnumSet.of(Option.SUPPRESS_EXCEPTIONS);
}
@Override
public MappingProvider mappingProvider() {
return mappingProvider;
}
}
);
}
final DocResponse response;
final com.vladsch.flexmark.util.ast.Document markdown;
| /*
* Copyright 2023 eahau@foxmail.com
*
* 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.github.eahau.openapi.douyin.generator.parser;
@Slf4j
public class HtmlParser {
static final Parser PARSER = Parser.builder()
.extensions(Collections.singletonList(TablesExtension.create()))
.build();
static {
Configuration.setDefaults(
new Defaults() {
final JsonProvider jsonProvider = new GsonJsonProvider(Misc.GSON);
final MappingProvider mappingProvider = new GsonMappingProvider(Misc.GSON);
@Override
public JsonProvider jsonProvider() {
return jsonProvider;
}
@Override
public Set<Option> options() {
return EnumSet.of(Option.SUPPRESS_EXCEPTIONS);
}
@Override
public MappingProvider mappingProvider() {
return mappingProvider;
}
}
);
}
final DocResponse response;
final com.vladsch.flexmark.util.ast.Document markdown;
| final GeneratorContentBuilder builder = GeneratorContent.builder(); | 1 | 2023-10-07 09:09:15+00:00 | 8k |
Aywen1/wispy | src/fr/nicolas/wispy/Panels/GamePanel.java | [
{
"identifier": "Runner",
"path": "src/fr/nicolas/wispy/Runner.java",
"snippet": "public class Runner implements Runnable {\n\n\tprivate boolean isRunning = false;\n\tprivate GamePanel gamePanel;\n\tprivate int maxFps = 80;\n\tprivate long waitTime = 4;\n\n\tpublic Runner(GamePanel gamePanel) {\n\t\tthi... | import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import fr.nicolas.wispy.Runner;
import fr.nicolas.wispy.Frames.MainFrame;
import fr.nicolas.wispy.Panels.Components.Game.Player;
import fr.nicolas.wispy.Panels.Components.Menu.EscapeMenu;
import fr.nicolas.wispy.Panels.Components.Menu.WPanel;
import fr.nicolas.wispy.Panels.Fonctions.MapManager;
import fr.nicolas.wispy.Panels.Fonctions.MapManager.RefreshPaintMap; | 6,914 | package fr.nicolas.wispy.Panels;
public class GamePanel extends WPanel implements KeyListener, MouseListener, MouseMotionListener {
public static final int BLOCK_SIZE = 25, INIT_PLAYER_X = 605, INIT_PLAYER_Y = 315;
private int newBlockWidth = BLOCK_SIZE, newBlockHeight = BLOCK_SIZE, playerX, playerY, playerWidth, playerHeight; | package fr.nicolas.wispy.Panels;
public class GamePanel extends WPanel implements KeyListener, MouseListener, MouseMotionListener {
public static final int BLOCK_SIZE = 25, INIT_PLAYER_X = 605, INIT_PLAYER_Y = 315;
private int newBlockWidth = BLOCK_SIZE, newBlockHeight = BLOCK_SIZE, playerX, playerY, playerWidth, playerHeight; | private Runner runner; | 0 | 2023-10-13 13:10:56+00:00 | 8k |
PfauMC/CyanWorld | cyanworld-cyanuniverse/src/main/java/ru/cyanworld/cyanuniverse/commands/CmdNbt.java | [
{
"identifier": "ItemBuilder",
"path": "cyanworld-cyan1dex/src/main/java/ru/cyanworld/cyan1dex/api/ItemBuilder.java",
"snippet": "public class ItemBuilder {\n public ItemStack itemStack;\n public ItemMeta itemMeta;\n\n public ItemBuilder(ItemStack itemStack) {\n this.itemStack = itemStac... | import org.bukkit.Bukkit;
import org.bukkit.GameMode;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import ru.cyanworld.cyan1dex.api.ItemBuilder;
import ru.cyanworld.cyanuniverse.WorldManager;
import ru.cyanworld.cyanuniverse.menus.nbt.item.NbtItemMenu;
import java.util.*; | 5,558 | package ru.cyanworld.cyanuniverse.commands;
public class CmdNbt extends Command {
public static List<String> blacklist = Arrays.asList("ru.cyanworld.cyanuniverse.coding.number", "ru.cyanworld.cyanuniverse.coding.effect", "ru.cyanworld.cyanuniverse.coding.location");
public static Set<Player> selectmob = new HashSet<>();
public static Map<Player, Entity> selectedmob = new HashMap<>();
public CmdNbt() {
super
(
"nbt",
"Редактор NBT",
"/nbt",
new ArrayList<>()
);
Bukkit.getCommandMap().register(getName(), this);
}
@Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
switch (WorldManager.getWorldType(player.getWorld())) {
case "coding": {
if (player.getGameMode() != GameMode.ADVENTURE) {
sender.sendMessage("Вы не можете редактировать NBT без прав кодинга");
return true;
}
break;
}
case "building": {
if (player.getGameMode() != GameMode.CREATIVE) {
sender.sendMessage("Вы не можете редактировать NBT без прав строительства");
return true;
}
break;
}
default: {
sender.sendMessage("Редактор работает только в режиме кодинга или строительства");
return true;
}
}
if (args.length < 1) {
sender.sendMessage("/nbt item");
return true;
}
switch (args[0]) {
case "item": {
ItemStack item = player.getInventory().getItemInMainHand();
if (item == null || item.getType() == Material.AIR) {
sender.sendMessage("Возьмите предмет в руки и попробуйте снова");
return true;
} | package ru.cyanworld.cyanuniverse.commands;
public class CmdNbt extends Command {
public static List<String> blacklist = Arrays.asList("ru.cyanworld.cyanuniverse.coding.number", "ru.cyanworld.cyanuniverse.coding.effect", "ru.cyanworld.cyanuniverse.coding.location");
public static Set<Player> selectmob = new HashSet<>();
public static Map<Player, Entity> selectedmob = new HashMap<>();
public CmdNbt() {
super
(
"nbt",
"Редактор NBT",
"/nbt",
new ArrayList<>()
);
Bukkit.getCommandMap().register(getName(), this);
}
@Override
public boolean execute(CommandSender sender, String commandLabel, String[] args) {
if (sender instanceof Player) {
Player player = (Player) sender;
switch (WorldManager.getWorldType(player.getWorld())) {
case "coding": {
if (player.getGameMode() != GameMode.ADVENTURE) {
sender.sendMessage("Вы не можете редактировать NBT без прав кодинга");
return true;
}
break;
}
case "building": {
if (player.getGameMode() != GameMode.CREATIVE) {
sender.sendMessage("Вы не можете редактировать NBT без прав строительства");
return true;
}
break;
}
default: {
sender.sendMessage("Редактор работает только в режиме кодинга или строительства");
return true;
}
}
if (args.length < 1) {
sender.sendMessage("/nbt item");
return true;
}
switch (args[0]) {
case "item": {
ItemStack item = player.getInventory().getItemInMainHand();
if (item == null || item.getType() == Material.AIR) {
sender.sendMessage("Возьмите предмет в руки и попробуйте снова");
return true;
} | ItemBuilder itemBuilder = new ItemBuilder(item); | 0 | 2023-10-08 17:50:55+00:00 | 8k |
vaaako/Vakraft | src/main/java/com/magenta/main/Renderer.java | [
{
"identifier": "Camera",
"path": "src/main/java/com/magenta/engine/Camera.java",
"snippet": "public class Camera {\n\tprivate final Window window;\n\t// private int width, height;\n\n\t// Camera movement vectors\n\tprivate Vector3f position = new Vector3f(0.0f, 0.0f, 0.0f);\n\tprivate Vector3f rotation... | import org.joml.Matrix4f;
import org.joml.Vector3f;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
import com.magenta.engine.Camera;
import com.magenta.engine.Window;
import com.magenta.game.Aim;
import com.magenta.game.World;
import com.magenta.render.ShaderProgram; | 6,557 | package com.magenta.main;
public class Renderer {
private ShaderProgram shaderProgram;
private final Window window;
// Matrices //
// Render Matrices
private Matrix4f mvMatrix, pMatrix;
// Camera
private final Camera camera;
private final float nearPlane, farPlane;
// Matrices
private Vector3f position;
private Vector3f rotation;
// Aim
private final Aim aim;
// This is just for view a single block
// private final TextureManager texManager = new TextureManager(16, 16, 256);
// private final BlockType blockType = new BlockType(BlocksEnum.AHIRO, texManager);
// private final int[] indices = {0, 0, 0};
// private final Mesh mesh = new MeshLoader(blockType.getVertexPositions(), indices, blockType.getTexCoords(), blockType.getShadingValues());
public Renderer(Window window, Camera camera) {
this.window = window;
this.camera = camera;
// Matrices //
// Consts
nearPlane = camera.getNearPlane();
farPlane = camera.getFarPlane();
// Render
mvMatrix = new Matrix4f();
pMatrix = new Matrix4f();
// Camera position/rotation
position = new Vector3f();
rotation = new Vector3f();
// Aim
aim = new Aim(Aim.AimType.CIRCLE);
}
public void init() {
// Load shaders
shaderProgram = new ShaderProgram("vertex.glsl", "fragment.glsl");
}
private void clear() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); // Clear frame buffer of Color and Depth (Depth: 3D)
}
| package com.magenta.main;
public class Renderer {
private ShaderProgram shaderProgram;
private final Window window;
// Matrices //
// Render Matrices
private Matrix4f mvMatrix, pMatrix;
// Camera
private final Camera camera;
private final float nearPlane, farPlane;
// Matrices
private Vector3f position;
private Vector3f rotation;
// Aim
private final Aim aim;
// This is just for view a single block
// private final TextureManager texManager = new TextureManager(16, 16, 256);
// private final BlockType blockType = new BlockType(BlocksEnum.AHIRO, texManager);
// private final int[] indices = {0, 0, 0};
// private final Mesh mesh = new MeshLoader(blockType.getVertexPositions(), indices, blockType.getTexCoords(), blockType.getShadingValues());
public Renderer(Window window, Camera camera) {
this.window = window;
this.camera = camera;
// Matrices //
// Consts
nearPlane = camera.getNearPlane();
farPlane = camera.getFarPlane();
// Render
mvMatrix = new Matrix4f();
pMatrix = new Matrix4f();
// Camera position/rotation
position = new Vector3f();
rotation = new Vector3f();
// Aim
aim = new Aim(Aim.AimType.CIRCLE);
}
public void init() {
// Load shaders
shaderProgram = new ShaderProgram("vertex.glsl", "fragment.glsl");
}
private void clear() {
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT); // Clear frame buffer of Color and Depth (Depth: 3D)
}
| public void render(World world) { | 3 | 2023-10-08 04:08:22+00:00 | 8k |
Aywen1/improvident | src/fr/nicolas/main/panels/NBase.java | [
{
"identifier": "MainFrame",
"path": "src/fr/nicolas/main/frames/MainFrame.java",
"snippet": "public class MainFrame extends JFrame implements MouseListener, MouseMotionListener, MouseWheelListener {\n\n\tprivate NBackground bg;\n\tprivate NLeftBar leftBar;\n\tprivate NTitle titlePanel;\n\tprivate NBase... | import java.awt.CardLayout;
import java.awt.Point;
import javax.swing.JPanel;
import fr.nicolas.main.frames.MainFrame;
import fr.nicolas.main.panels.categories.NCategoryPanel;
import fr.nicolas.main.panels.categories.NHome;
import fr.nicolas.main.panels.categories.NPoints;
import fr.nicolas.main.panels.categories.NSettings;
import fr.nicolas.main.panels.categories.NDefault; | 6,860 | package fr.nicolas.main.panels;
public class NBase extends JPanel {
private NCategoryPanel[] panels;
private int currentPanelNumber = 0;
private CardLayout cardLayout;
public NBase(MainFrame mainFrame) { | package fr.nicolas.main.panels;
public class NBase extends JPanel {
private NCategoryPanel[] panels;
private int currentPanelNumber = 0;
private CardLayout cardLayout;
public NBase(MainFrame mainFrame) { | panels = new NCategoryPanel[] { new NHome(mainFrame), new NDefault("Cours écrits"), | 5 | 2023-10-13 10:30:31+00:00 | 8k |
Kelwinkxps13/Projeto_POO_Swing | UrnaEletronica/src/br/edu/view/Urna.java | [
{
"identifier": "ConexaoDAO",
"path": "UrnaEletronica/src/br/edu/bancodedados/ConexaoDAO.java",
"snippet": "public class ConexaoDAO{\r\n public Connection conexaodao(){\r\n Connection conn = null;\r\n // 192.168.18.165\r\n try {\r\n String url = \"jdbc:mysql://sql10.fr... | import br.edu.bancodedados.ConexaoDAO;
import br.edu.bancodedados.User;
import br.edu.bancodedados.UsuarioDAO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.lang.Integer;
import static java.lang.Integer.parseInt; | 4,350 | jButton14.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
jButton14.setForeground(new java.awt.Color(0, 0, 0));
jButton14.setText("Voltar para o Login");
jButton14.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton14ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton14)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(10, 10, 10)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton14)))
.addContainerGap(15, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed
Login login = new Login();
login.setVisible(true);
dispose();
}//GEN-LAST:event_jButton14ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
texto += "1";
campoText.setText(texto);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
texto += "2";
campoText.setText(texto);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
texto += "3";
campoText.setText(texto);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
texto += "4";
campoText.setText(texto);
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
texto += "5";
campoText.setText(texto);
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
texto += "6";
campoText.setText(texto);
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
texto += "7";
campoText.setText(texto);
}//GEN-LAST:event_jButton8ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
texto += "8";
campoText.setText(texto);
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
texto += "9";
campoText.setText(texto);
}//GEN-LAST:event_jButton9ActionPerformed
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
texto += "0";
campoText.setText(texto);
}//GEN-LAST:event_jButton10ActionPerformed
private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
texto = "";
campoText.setText(texto);
}//GEN-LAST:event_jButton12ActionPerformed
private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
if(texto.equals("12")){
try { | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package br.edu.view;
/**
*
* @author Windows
*/
public class Urna extends javax.swing.JFrame {
Connection conn;
String nome = null;
String senha = null;
String email = null;
String votosA = null;
String votosB = null;
String votosC = null;
String votosBB = null;
String votosNull = null;
String votosEx = null;
/**
* Creates new form Urna
*/
private String texto = "";
public Urna() {
initComponents();
setLocationRelativeTo(null);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel6 = new javax.swing.JPanel();
jLabel8 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
jPanel5 = new javax.swing.JPanel();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();
jButton5 = new javax.swing.JButton();
jButton6 = new javax.swing.JButton();
jButton7 = new javax.swing.JButton();
jButton8 = new javax.swing.JButton();
jButton9 = new javax.swing.JButton();
jButton10 = new javax.swing.JButton();
campoText = new javax.swing.JTextField();
jButton11 = new javax.swing.JButton();
jButton12 = new javax.swing.JButton();
jButton13 = new javax.swing.JButton();
jPanel7 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jLabel14 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jLabel16 = new javax.swing.JLabel();
jButton14 = new javax.swing.JButton();
javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6);
jPanel6.setLayout(jPanel6Layout);
jPanel6Layout.setHorizontalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel6Layout.setVerticalGroup(
jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jLabel8.setText("jLabel8");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Urna Eletrônica");
setResizable(false);
jPanel3.setBackground(new java.awt.Color(255, 238, 209));
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/edu/resourses/JUSTIÇA ELEITORAL.png"))); // NOI18N
jPanel5.setBackground(new java.awt.Color(0, 0, 0));
jButton1.setBackground(new java.awt.Color(51, 51, 51));
jButton1.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton1.setForeground(new java.awt.Color(255, 255, 255));
jButton1.setText("2");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setBackground(new java.awt.Color(51, 51, 51));
jButton2.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton2.setForeground(new java.awt.Color(255, 255, 255));
jButton2.setText("1");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jButton3.setBackground(new java.awt.Color(51, 51, 51));
jButton3.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton3.setForeground(new java.awt.Color(255, 255, 255));
jButton3.setText("8");
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});
jButton4.setBackground(new java.awt.Color(51, 51, 51));
jButton4.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton4.setForeground(new java.awt.Color(255, 255, 255));
jButton4.setText("3");
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});
jButton5.setBackground(new java.awt.Color(51, 51, 51));
jButton5.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton5.setForeground(new java.awt.Color(255, 255, 255));
jButton5.setText("6");
jButton5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton5ActionPerformed(evt);
}
});
jButton6.setBackground(new java.awt.Color(51, 51, 51));
jButton6.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton6.setForeground(new java.awt.Color(255, 255, 255));
jButton6.setText("5");
jButton6.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton6ActionPerformed(evt);
}
});
jButton7.setBackground(new java.awt.Color(51, 51, 51));
jButton7.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton7.setForeground(new java.awt.Color(255, 255, 255));
jButton7.setText("4");
jButton7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton7ActionPerformed(evt);
}
});
jButton8.setBackground(new java.awt.Color(51, 51, 51));
jButton8.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton8.setForeground(new java.awt.Color(255, 255, 255));
jButton8.setText("7");
jButton8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton8ActionPerformed(evt);
}
});
jButton9.setBackground(new java.awt.Color(51, 51, 51));
jButton9.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton9.setForeground(new java.awt.Color(255, 255, 255));
jButton9.setText("9");
jButton9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton9ActionPerformed(evt);
}
});
jButton10.setBackground(new java.awt.Color(51, 51, 51));
jButton10.setFont(new java.awt.Font("Kartika", 1, 24)); // NOI18N
jButton10.setForeground(new java.awt.Color(255, 255, 255));
jButton10.setText("0");
jButton10.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton10ActionPerformed(evt);
}
});
campoText.setEditable(false);
campoText.setBackground(new java.awt.Color(255, 255, 255));
campoText.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
campoText.setForeground(new java.awt.Color(0, 0, 0));
campoText.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
jButton11.setBackground(new java.awt.Color(255, 255, 255));
jButton11.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jButton11.setForeground(new java.awt.Color(0, 0, 0));
jButton11.setText("Branco");
jButton11.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton11ActionPerformed(evt);
}
});
jButton12.setBackground(new java.awt.Color(204, 0, 0));
jButton12.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jButton12.setForeground(new java.awt.Color(255, 255, 255));
jButton12.setText("Corrigir");
jButton12.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton12ActionPerformed(evt);
}
});
jButton13.setBackground(new java.awt.Color(0, 153, 0));
jButton13.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jButton13.setForeground(new java.awt.Color(255, 255, 255));
jButton13.setText("Confirmar");
jButton13.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton13ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
jPanel5.setLayout(jPanel5Layout);
jPanel5Layout.setHorizontalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addGap(77, 77, 77)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel5Layout.createSequentialGroup()
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(campoText)))
.addContainerGap(77, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton13)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel5Layout.setVerticalGroup(
jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel5Layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(campoText, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton7, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton8, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton9, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addComponent(jButton10, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton12, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jButton13, javax.swing.GroupLayout.PREFERRED_SIZE, 54, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(56, 56, 56))
);
jPanel7.setBackground(new java.awt.Color(204, 204, 204));
jLabel1.setBackground(new java.awt.Color(0, 0, 0));
jLabel1.setFont(new java.awt.Font("SansSerif", 1, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 0, 0));
jLabel1.setText("Eleições 2023");
jLabel3.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jLabel3.setForeground(new java.awt.Color(0, 0, 0));
jLabel3.setText("Partido dos Trabalhadores (PT)");
jLabel4.setFont(new java.awt.Font("Gadugi", 1, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(0, 0, 0));
jLabel4.setText("Presidente: Luis Inácio Lula da Silva");
jLabel5.setFont(new java.awt.Font("Gadugi", 1, 14)); // NOI18N
jLabel5.setForeground(new java.awt.Color(0, 0, 0));
jLabel5.setText("Vice-presidente: Geraldo Alckmin");
jLabel7.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jLabel7.setForeground(new java.awt.Color(0, 0, 0));
jLabel7.setText("Número eleitoral: 13");
jLabel9.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jLabel9.setForeground(new java.awt.Color(0, 0, 0));
jLabel9.setText("Partido Liberal (PL)");
jLabel10.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jLabel10.setForeground(new java.awt.Color(0, 0, 0));
jLabel10.setText("Número eleitoral: 22");
jLabel11.setFont(new java.awt.Font("Gadugi", 1, 14)); // NOI18N
jLabel11.setForeground(new java.awt.Color(0, 0, 0));
jLabel11.setText("Vice-presidente: Walter Souza Braga Netto");
jLabel12.setFont(new java.awt.Font("Gadugi", 1, 14)); // NOI18N
jLabel12.setForeground(new java.awt.Color(0, 0, 0));
jLabel12.setText("Presidente: Jair Messias Bolsonaro");
jLabel13.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jLabel13.setForeground(new java.awt.Color(0, 0, 0));
jLabel13.setText("Partido Democrático Trabalhista (PDT)");
jLabel14.setFont(new java.awt.Font("Gadugi", 1, 18)); // NOI18N
jLabel14.setForeground(new java.awt.Color(0, 0, 0));
jLabel14.setText("Número eleitoral: 12");
jLabel15.setFont(new java.awt.Font("Gadugi", 1, 14)); // NOI18N
jLabel15.setForeground(new java.awt.Color(0, 0, 0));
jLabel15.setText("Presidente: Ciro Gomes");
jLabel16.setFont(new java.awt.Font("Gadugi", 1, 14)); // NOI18N
jLabel16.setForeground(new java.awt.Color(0, 0, 0));
jLabel16.setText("Vice-presidente: Ana Paula Matos");
javax.swing.GroupLayout jPanel7Layout = new javax.swing.GroupLayout(jPanel7);
jPanel7.setLayout(jPanel7Layout);
jPanel7Layout.setHorizontalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(148, 148, 148)
.addComponent(jLabel1))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(71, 71, 71)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel11)
.addComponent(jLabel10)
.addComponent(jLabel12)))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(51, 51, 51)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(jLabel3)
.addComponent(jLabel9)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel4)
.addComponent(jLabel7)
.addComponent(jLabel5)))
.addComponent(jLabel13)))
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(71, 71, 71)
.addGroup(jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel15)
.addComponent(jLabel14)
.addComponent(jLabel16))))
.addContainerGap(148, Short.MAX_VALUE))
);
jPanel7Layout.setVerticalGroup(
jPanel7Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel7Layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel1)
.addGap(30, 30, 30)
.addComponent(jLabel3)
.addGap(0, 0, 0)
.addComponent(jLabel6)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel7)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel5)
.addGap(37, 37, 37)
.addComponent(jLabel9)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel10)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel12)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel11)
.addGap(36, 36, 36)
.addComponent(jLabel13)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel14)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel15)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel16)
.addContainerGap(78, Short.MAX_VALUE))
);
jButton14.setBackground(new java.awt.Color(255, 255, 255));
jButton14.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
jButton14.setForeground(new java.awt.Color(0, 0, 0));
jButton14.setText("Voltar para o Login");
jButton14.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton14ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jButton14)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(10, 10, 10)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25))
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jPanel7, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel3Layout.createSequentialGroup()
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jButton14)))
.addContainerGap(15, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jButton14ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton14ActionPerformed
Login login = new Login();
login.setVisible(true);
dispose();
}//GEN-LAST:event_jButton14ActionPerformed
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
texto += "1";
campoText.setText(texto);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
texto += "2";
campoText.setText(texto);
}//GEN-LAST:event_jButton1ActionPerformed
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
texto += "3";
campoText.setText(texto);
}//GEN-LAST:event_jButton4ActionPerformed
private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
texto += "4";
campoText.setText(texto);
}//GEN-LAST:event_jButton7ActionPerformed
private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
texto += "5";
campoText.setText(texto);
}//GEN-LAST:event_jButton6ActionPerformed
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
texto += "6";
campoText.setText(texto);
}//GEN-LAST:event_jButton5ActionPerformed
private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton8ActionPerformed
texto += "7";
campoText.setText(texto);
}//GEN-LAST:event_jButton8ActionPerformed
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
texto += "8";
campoText.setText(texto);
}//GEN-LAST:event_jButton3ActionPerformed
private void jButton9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton9ActionPerformed
texto += "9";
campoText.setText(texto);
}//GEN-LAST:event_jButton9ActionPerformed
private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
texto += "0";
campoText.setText(texto);
}//GEN-LAST:event_jButton10ActionPerformed
private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
texto = "";
campoText.setText(texto);
}//GEN-LAST:event_jButton12ActionPerformed
private void jButton13ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton13ActionPerformed
if(texto.equals("12")){
try { | conn = new ConexaoDAO().conexaodao(); | 0 | 2023-10-10 18:25:35+00:00 | 8k |
ljjy1/discord-mj-java | src/main/java/com/github/dmj/service/DiscordService.java | [
{
"identifier": "DiscordMjJavaException",
"path": "src/main/java/com/github/dmj/error/DiscordMjJavaException.java",
"snippet": "@Getter\npublic class DiscordMjJavaException extends RuntimeException {\n\n private static final long serialVersionUID = 7869786563361406291L;\n\n /**\n * 错误代码\n ... | import cn.hutool.core.util.StrUtil;
import com.github.dmj.error.DiscordMjJavaException;
import com.github.dmj.model.*;
import com.github.dmj.queue.TaskQueue;
import com.github.dmj.service.api.DiscordApi;
import com.github.dmj.util.UniqueUtil;
import java.io.File;
import java.net.URLConnection;
import java.util.Map; | 6,859 | package com.github.dmj.service;
/**
* @author ljjy1
* @classname DiscordService
* @description API接口服务
* @date 2023/10/11 16:31
*/
public class DiscordService {
private final Map<String, DiscordApi> discordApiMap;
public DiscordService(Map<String, DiscordApi> discordApiMap) {
this.discordApiMap = discordApiMap;
}
/**
* 文生图/图生图 返回唯一id 用于获取后续图片信息 对应机器人命令 /imagine
*/
public Integer imagine(ImagineInRequest request){
request.check();
String userKey = request.getUserKey();
DiscordApi discordApi = discordApiMap.get(userKey);
if(discordApi == null){
throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey);
}
Integer triggerId = request.getTriggerId();
//加入队列 | package com.github.dmj.service;
/**
* @author ljjy1
* @classname DiscordService
* @description API接口服务
* @date 2023/10/11 16:31
*/
public class DiscordService {
private final Map<String, DiscordApi> discordApiMap;
public DiscordService(Map<String, DiscordApi> discordApiMap) {
this.discordApiMap = discordApiMap;
}
/**
* 文生图/图生图 返回唯一id 用于获取后续图片信息 对应机器人命令 /imagine
*/
public Integer imagine(ImagineInRequest request){
request.check();
String userKey = request.getUserKey();
DiscordApi discordApi = discordApiMap.get(userKey);
if(discordApi == null){
throw new DiscordMjJavaException("未找到对应用户key{}配置 [The corresponding user key:{} configuration is not found]",userKey,userKey);
}
Integer triggerId = request.getTriggerId();
//加入队列 | TaskQueue.getInstance().putTask(userKey,discordApi::triggerImagine,request); | 1 | 2023-10-11 01:12:39+00:00 | 8k |
weizen-w/Educational-Management-System-BE | src/main/java/de/ait/ems/services/GroupsService.java | [
{
"identifier": "from",
"path": "src/main/java/de/ait/ems/dto/GroupDto.java",
"snippet": "public static GroupDto from(Group group) {\n return GroupDto.builder()\n .id(group.getId())\n .name(group.getName())\n .courseId(group.getCourse().getId())\n .archived(group.getArchived())\n ... | import static de.ait.ems.dto.GroupDto.from;
import static de.ait.ems.dto.UserDto.from;
import de.ait.ems.dto.GroupDto;
import de.ait.ems.dto.NewGroupDto;
import de.ait.ems.dto.UpdateGroupDto;
import de.ait.ems.dto.UserDto;
import de.ait.ems.exceptions.RestException;
import de.ait.ems.mapper.EntityMapper;
import de.ait.ems.models.Course;
import de.ait.ems.models.Group;
import de.ait.ems.models.User;
import de.ait.ems.models.UserGroup;
import de.ait.ems.repositories.CoursesRepository;
import de.ait.ems.repositories.GroupsRepository;
import de.ait.ems.repositories.UserGroupsRepository;
import de.ait.ems.security.details.AuthenticatedUser;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service; | 4,137 | package de.ait.ems.services;
/**
* 14/10/2023 EducationalManagementSystem
*
* @author Wladimir Weizen
*/
@RequiredArgsConstructor
@Service
public class GroupsService {
private final GroupsRepository groupsRepository;
private final CoursesRepository coursesRepository;
private final UserGroupsRepository userGroupsRepository;
private final EntityMapper entityMapper;
| package de.ait.ems.services;
/**
* 14/10/2023 EducationalManagementSystem
*
* @author Wladimir Weizen
*/
@RequiredArgsConstructor
@Service
public class GroupsService {
private final GroupsRepository groupsRepository;
private final CoursesRepository coursesRepository;
private final UserGroupsRepository userGroupsRepository;
private final EntityMapper entityMapper;
| public GroupDto addGroup(NewGroupDto newGroup) { | 3 | 2023-10-07 16:00:02+00:00 | 8k |
ProjectgamesOOP/Adventure_to_the_Fallen_Kingdom | src/UI/LevelCompleted.java | [
{
"identifier": "Gamestate",
"path": "src/gamestates/Gamestate.java",
"snippet": "public enum Gamestate {\n PLAYING, MENU, OPTIONS, QUIT;\n public static Gamestate state = MENU;\n}"
},
{
"identifier": "Playing",
"path": "src/gamestates/Playing.java",
"snippet": "public class Playin... | import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import gamestates.Gamestate;
import gamestates.Playing;
import main.Game;
import utilz.LoadSave;
import static utilz.Constants.UI.URMButtons.*; | 5,013 | package UI;
public class LevelCompleted {
private Playing playing;
private UrmButton menu, next;
private BufferedImage img;
private int bgX, bgY, bgW, bgH;
public LevelCompleted(Playing playing) {
this.playing = playing;
initImg();
initButtons();
}
private void initButtons() {
int menuX = (int) (330 * Game.SCALE);
int nextX = (int) (445 * Game.SCALE);
int y = (int) (195 * Game.SCALE);
next = new UrmButton(nextX, y, URM_SIZE, URM_SIZE, 0);
menu = new UrmButton(menuX, y, URM_SIZE, URM_SIZE, 2);
}
private void initImg() {
img = LoadSave.GetSpriteAtlas(LoadSave.LEVEL_COMPLETED);
bgW = (int) (img.getWidth() * Game.SCALE);
bgH = (int) (img.getHeight() * Game.SCALE);
bgX = Game.GAME_WIDTH / 2 - bgW / 2;
bgY = (int) (75 * Game.SCALE);
}
public void draw(Graphics g) {
g.setColor(new Color(0, 0, 0, 200));
g.fillRect(0, 0, Game.GAME_WIDTH, Game.GAME_HEIGHT);
g.drawImage(img, bgX, bgY, bgW, bgH, null);
next.draw(g);
menu.draw(g);
}
public void update() {
next.update();
menu.update();
}
private boolean isIn(UrmButton b, MouseEvent e) {
return b.getBounds().contains(e.getX(), e.getY());
}
public void mouseMoved(MouseEvent e) {
next.setMouseOver(false);
menu.setMouseOver(false);
if (isIn(menu, e))
menu.setMouseOver(true);
else if (isIn(next, e))
next.setMouseOver(true);
}
public void mouseReleased(MouseEvent e) {
if (isIn(menu, e)) {
if (menu.isMousePressed()) {
playing.resetAll(); | package UI;
public class LevelCompleted {
private Playing playing;
private UrmButton menu, next;
private BufferedImage img;
private int bgX, bgY, bgW, bgH;
public LevelCompleted(Playing playing) {
this.playing = playing;
initImg();
initButtons();
}
private void initButtons() {
int menuX = (int) (330 * Game.SCALE);
int nextX = (int) (445 * Game.SCALE);
int y = (int) (195 * Game.SCALE);
next = new UrmButton(nextX, y, URM_SIZE, URM_SIZE, 0);
menu = new UrmButton(menuX, y, URM_SIZE, URM_SIZE, 2);
}
private void initImg() {
img = LoadSave.GetSpriteAtlas(LoadSave.LEVEL_COMPLETED);
bgW = (int) (img.getWidth() * Game.SCALE);
bgH = (int) (img.getHeight() * Game.SCALE);
bgX = Game.GAME_WIDTH / 2 - bgW / 2;
bgY = (int) (75 * Game.SCALE);
}
public void draw(Graphics g) {
g.setColor(new Color(0, 0, 0, 200));
g.fillRect(0, 0, Game.GAME_WIDTH, Game.GAME_HEIGHT);
g.drawImage(img, bgX, bgY, bgW, bgH, null);
next.draw(g);
menu.draw(g);
}
public void update() {
next.update();
menu.update();
}
private boolean isIn(UrmButton b, MouseEvent e) {
return b.getBounds().contains(e.getX(), e.getY());
}
public void mouseMoved(MouseEvent e) {
next.setMouseOver(false);
menu.setMouseOver(false);
if (isIn(menu, e))
menu.setMouseOver(true);
else if (isIn(next, e))
next.setMouseOver(true);
}
public void mouseReleased(MouseEvent e) {
if (isIn(menu, e)) {
if (menu.isMousePressed()) {
playing.resetAll(); | playing.setGamestate(Gamestate.MENU); | 0 | 2023-10-07 12:07:45+00:00 | 8k |
whykang/Trajectory-extraction | app/src/main/java/com/wang/tracker/MainActivity.java | [
{
"identifier": "LogRecorder",
"path": "app/src/main/java/com/wang/tracker/log/LogRecorder.java",
"snippet": "public class LogRecorder {\n Context context = null;\n public static LogRecorder instance;\n\n static String STORAGE_PATH = \"\";\n\n public LogRecorder(Context context) {\n t... | import android.Manifest;
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.wang.tracker.databinding.ActivityFullscreenBinding;
import com.wang.tracker.log.LogRecorder;
import com.wang.tracker.pojo.StepPosition;
import com.wang.tracker.sensor.StepEventHandler;
import com.wang.tracker.sensor.StepEventListener;
import com.wang.tracker.tool.Permission;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID; | 4,503 | package com.wang.tracker;
/**
*
* @Description V2.0
* @Author WangHongyue
* @CreateTime 2023-10-12 15:32
*/
public class MainActivity extends AppCompatActivity {
private static final int UI_ANIMATION_DELAY = 300;
private static final int PERMISSION_REQUEST_CODE =100;
private float x=0,y=0;
private int x623=0;
private final Handler mHideHandler = new Handler();
private TextView text;
private Button cle,abu,save,set;
private Handler positionHandler,positionHandler1;
private int xnum=0;
private int ynum=0;
private final Runnable mHidePart2Runnable = new Runnable() {
@SuppressLint("InlinedApi")
@Override
public void run() {
// Delayed removal of status and navigation bar
if (Build.VERSION.SDK_INT >= 30) {
// mCanvas.getWindowInsetsController().hide(
// WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
} else {
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mCanvas.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
}
};
private View mControlsView;
private CanvasView mCanvas;
private final Runnable mShowPart2Runnable = new Runnable() {
@Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private boolean mVisible;
private final Runnable mHideRunnable = this::hide;
private void clearView() {
tipDialog();
}
/**
* 提示对话框
*/
public void tipDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("提示:");
builder.setMessage("重置后将恢复初始界面,且轨迹数据将不可保存!");
builder.setIcon(R.mipmap.ic_launcher);
builder.setCancelable(true); //点击对话框以外的区域是否让对话框消失
//设置正面按钮
builder.setPositiveButton("确定重置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mCanvas.clearPoints(xnum,ynum);
if(positions!=null && positions.size()>0){
positions.clear();
}
dialog.dismiss();
}
});
//设置反面按钮
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(MainActivity.this, "你点击了取消", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
AlertDialog dialog = builder.create(); //创建AlertDialog对象
//对话框显示的监听事件
dialog.show(); //显示对话框
}
// private void requestPermission() {
// // checkSelfPermission() 检测权限
// String[] PERMISSIONS_STORAGE = {
// Manifest.permission.READ_EXTERNAL_STORAGE,
// Manifest.permission.WRITE_EXTERNAL_STORAGE};
//
// if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE )!= PackageManager.PERMISSION_GRANTED) {
// //TODO 申请存储权限
// ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,
// PERMISSION_REQUEST_CODE);
// }
//
// else{
// // Utils.writeTxt(getApplicationContext(),"44444444444",true);
// Toast.makeText(getApplicationContext(),"已授予权限",Toast.LENGTH_SHORT).show();
// }
// }
private ActivityFullscreenBinding binding; | package com.wang.tracker;
/**
*
* @Description V2.0
* @Author WangHongyue
* @CreateTime 2023-10-12 15:32
*/
public class MainActivity extends AppCompatActivity {
private static final int UI_ANIMATION_DELAY = 300;
private static final int PERMISSION_REQUEST_CODE =100;
private float x=0,y=0;
private int x623=0;
private final Handler mHideHandler = new Handler();
private TextView text;
private Button cle,abu,save,set;
private Handler positionHandler,positionHandler1;
private int xnum=0;
private int ynum=0;
private final Runnable mHidePart2Runnable = new Runnable() {
@SuppressLint("InlinedApi")
@Override
public void run() {
// Delayed removal of status and navigation bar
if (Build.VERSION.SDK_INT >= 30) {
// mCanvas.getWindowInsetsController().hide(
// WindowInsets.Type.statusBars() | WindowInsets.Type.navigationBars());
} else {
// Note that some of these constants are new as of API 16 (Jelly Bean)
// and API 19 (KitKat). It is safe to use them, as they are inlined
// at compile-time and do nothing on earlier devices.
mCanvas.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
}
};
private View mControlsView;
private CanvasView mCanvas;
private final Runnable mShowPart2Runnable = new Runnable() {
@Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private boolean mVisible;
private final Runnable mHideRunnable = this::hide;
private void clearView() {
tipDialog();
}
/**
* 提示对话框
*/
public void tipDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("提示:");
builder.setMessage("重置后将恢复初始界面,且轨迹数据将不可保存!");
builder.setIcon(R.mipmap.ic_launcher);
builder.setCancelable(true); //点击对话框以外的区域是否让对话框消失
//设置正面按钮
builder.setPositiveButton("确定重置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
mCanvas.clearPoints(xnum,ynum);
if(positions!=null && positions.size()>0){
positions.clear();
}
dialog.dismiss();
}
});
//设置反面按钮
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(MainActivity.this, "你点击了取消", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
AlertDialog dialog = builder.create(); //创建AlertDialog对象
//对话框显示的监听事件
dialog.show(); //显示对话框
}
// private void requestPermission() {
// // checkSelfPermission() 检测权限
// String[] PERMISSIONS_STORAGE = {
// Manifest.permission.READ_EXTERNAL_STORAGE,
// Manifest.permission.WRITE_EXTERNAL_STORAGE};
//
// if (ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE )!= PackageManager.PERMISSION_GRANTED) {
// //TODO 申请存储权限
// ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,
// PERMISSION_REQUEST_CODE);
// }
//
// else{
// // Utils.writeTxt(getApplicationContext(),"44444444444",true);
// Toast.makeText(getApplicationContext(),"已授予权限",Toast.LENGTH_SHORT).show();
// }
// }
private ActivityFullscreenBinding binding; | private StepEventHandler stepEventHandler; | 2 | 2023-10-10 12:49:16+00:00 | 8k |
yc-huang/bsdb | src/main/java/tech/bsdb/read/kv/PartitionedKVReader.java | [
{
"identifier": "AsyncFileReader",
"path": "src/main/java/tech/bsdb/io/AsyncFileReader.java",
"snippet": "public interface AsyncFileReader {\n int QD = 512;\n int DEFAULT_TIMEOUT = 1000; //1 us\n int MAX_TIMEOUT = 10 * 1000 * 1000;//1ms\n\n void start();\n\n /**\n * Caution: the buffe... | import tech.bsdb.io.AsyncFileReader;
import tech.bsdb.io.NativeFileIO;
import tech.bsdb.io.SimpleAsyncFileReader;
import tech.bsdb.io.UringAsyncFileReader;
import tech.bsdb.util.Common;
import com.google.common.io.Files;
import org.apache.commons.configuration2.Configuration;
import xerial.larray.mmap.MMapBuffer;
import xerial.larray.mmap.MMapMode;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler; | 6,730 | package tech.bsdb.read.kv;
public abstract class PartitionedKVReader extends BaseKVReader {
protected MMapBuffer[] mmaps;
protected final int[] fds;
protected ThreadLocal<ByteBuffer> threadLocalPooledBuffer = new ThreadLocal<>();
protected AsyncFileReader asyncReader;
protected final int maxRecordSize;
protected final boolean useDirectIO;
protected int partitions;
public PartitionedKVReader(File kvFile, Configuration config, boolean async, boolean useDirectIO, boolean initReader) throws IOException {
super(config);
this.useDirectIO = useDirectIO;
//maxRecordSize = NativeFileIO.alignToPageSize(config.getInt(Common.CONFIG_KEY_KV_KEY_LEN_MAX) + config.getInt(Common.CONFIG_KEY_KV_VALUE_LEN_MAX) + Common.RECORD_HEADER_SIZE); | package tech.bsdb.read.kv;
public abstract class PartitionedKVReader extends BaseKVReader {
protected MMapBuffer[] mmaps;
protected final int[] fds;
protected ThreadLocal<ByteBuffer> threadLocalPooledBuffer = new ThreadLocal<>();
protected AsyncFileReader asyncReader;
protected final int maxRecordSize;
protected final boolean useDirectIO;
protected int partitions;
public PartitionedKVReader(File kvFile, Configuration config, boolean async, boolean useDirectIO, boolean initReader) throws IOException {
super(config);
this.useDirectIO = useDirectIO;
//maxRecordSize = NativeFileIO.alignToPageSize(config.getInt(Common.CONFIG_KEY_KV_KEY_LEN_MAX) + config.getInt(Common.CONFIG_KEY_KV_VALUE_LEN_MAX) + Common.RECORD_HEADER_SIZE); | maxRecordSize = config.getInt(Common.CONFIG_KEY_KV_KEY_LEN_MAX) + config.getInt(Common.CONFIG_KEY_KV_VALUE_LEN_MAX) + Common.RECORD_HEADER_SIZE; | 4 | 2023-10-07 03:32:27+00:00 | 8k |
reinershir/Shir-Boot | src/main/java/io/github/reinershir/boot/controller/DevelopmentController.java | [
{
"identifier": "Result",
"path": "src/main/java/io/github/reinershir/boot/common/Result.java",
"snippet": "@Schema(description = \"Response DTO\")\n@JsonInclude(value = JsonInclude.Include.ALWAYS)//Even if the returned object is null, it will still be returned when this annotation is added.\npublic cla... | import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.github.reinershir.auth.annotation.OptionType;
import io.github.reinershir.auth.annotation.Permission;
import io.github.reinershir.auth.annotation.PermissionMapping;
import io.github.reinershir.boot.common.Result;
import io.github.reinershir.boot.core.easygenerator.generator.EasyAutoModule;
import io.github.reinershir.boot.core.easygenerator.generator.MicroSMSCodeGenerator;
import io.github.reinershir.boot.core.easygenerator.model.FieldInfo;
import io.github.reinershir.boot.core.easygenerator.model.GenerateInfo;
import io.github.reinershir.boot.core.international.IMessager;
import io.github.reinershir.boot.dto.req.CodeGenerateDTO;
import io.github.reinershir.boot.exception.BusinessException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse; | 6,624 | package io.github.reinershir.boot.controller;
@RequestMapping("development")
@RestController
@Tag(description = "Development management",name = "Development management")
@PermissionMapping(value="DEVELOPMENT")
public class DevelopmentController {
@Autowired
MicroSMSCodeGenerator codeGenerator;
@Permission(name = "Get Table columns",value = OptionType.LIST)
@Operation(summary = "Get Table columns",description = "Get Table columns")
@Parameter(name = "tableName",required = false,description = "Parent menu id")
@GetMapping("/codeGenerate/{tableName}/columns")
public Result<List<FieldInfo>> getColumns(@PathVariable(value="tableName",required = true) String tableName){
try {
return Result.ok(codeGenerator.getTableFields(tableName));
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
return Result.failed(IMessager.getMessageByCode("message.error"));
}
}
@Permission(name = "Code generate",value = OptionType.LIST)
@Operation(summary = "Code generate",description = "Generate front-end and back-end codes")
@PostMapping("/codeGenerate/codes")
public void generate(@RequestBody @Validated CodeGenerateDTO dto,HttpServletResponse response){ | package io.github.reinershir.boot.controller;
@RequestMapping("development")
@RestController
@Tag(description = "Development management",name = "Development management")
@PermissionMapping(value="DEVELOPMENT")
public class DevelopmentController {
@Autowired
MicroSMSCodeGenerator codeGenerator;
@Permission(name = "Get Table columns",value = OptionType.LIST)
@Operation(summary = "Get Table columns",description = "Get Table columns")
@Parameter(name = "tableName",required = false,description = "Parent menu id")
@GetMapping("/codeGenerate/{tableName}/columns")
public Result<List<FieldInfo>> getColumns(@PathVariable(value="tableName",required = true) String tableName){
try {
return Result.ok(codeGenerator.getTableFields(tableName));
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
return Result.failed(IMessager.getMessageByCode("message.error"));
}
}
@Permission(name = "Code generate",value = OptionType.LIST)
@Operation(summary = "Code generate",description = "Generate front-end and back-end codes")
@PostMapping("/codeGenerate/codes")
public void generate(@RequestBody @Validated CodeGenerateDTO dto,HttpServletResponse response){ | GenerateInfo generateInfo = new GenerateInfo(dto.getTableName(),dto.getModelName(),dto.getModelDescription()); | 4 | 2023-10-10 13:06:54+00:00 | 8k |
wise-old-man/wiseoldman-runelite-plugin | src/main/java/net/wiseoldman/panel/SkillingPanel.java | [
{
"identifier": "Format",
"path": "src/main/java/net/wiseoldman/util/Format.java",
"snippet": "public class Format\n{\n public static String formatNumber(long num)\n {\n if ((num < 10000 && num > -10000))\n {\n return QuantityFormatter.formatNumber(num);\n }\n\n ... | import com.google.common.collect.ImmutableList;
import net.wiseoldman.util.Format;
import net.wiseoldman.WomUtilsConfig;
import net.wiseoldman.beans.PlayerInfo;
import net.wiseoldman.beans.Skill;
import net.wiseoldman.beans.Snapshot;
import net.runelite.api.Experience;
import net.runelite.client.ui.ColorScheme;
import net.runelite.client.util.QuantityFormatter;
import net.runelite.client.hiscore.HiscoreSkill;
import net.runelite.client.hiscore.HiscoreSkillType;
import javax.inject.Inject;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static net.runelite.client.hiscore.HiscoreSkill.*; | 4,143 | package net.wiseoldman.panel;
class SkillingPanel extends JPanel
{
/**
* Real skills, ordered in the way they should be displayed in the panel.
*/
private static final List<HiscoreSkill> SKILLS = ImmutableList.of(
ATTACK, DEFENCE, STRENGTH,
HITPOINTS, RANGED, PRAYER,
MAGIC, COOKING, WOODCUTTING,
FLETCHING, FISHING, FIREMAKING,
CRAFTING, SMITHING, MINING,
HERBLORE, AGILITY, THIEVING,
SLAYER, FARMING, RUNECRAFT,
HUNTER, CONSTRUCTION
);
static Color[] ROW_COLORS = {ColorScheme.DARKER_GRAY_COLOR, new Color(34, 34, 34)};
TableRow overallRow;
List<RowPair> tableRows = new ArrayList<>();
WomUtilsConfig config;
@Inject
private SkillingPanel(WomUtilsConfig config)
{
this.config = config;
setLayout(new GridLayout(0, 1));
StatsTableHeader tableHeader = new StatsTableHeader("skilling");
// Handle overall separately because it's special
overallRow = new TableRow(
OVERALL.name(), OVERALL.getName(), HiscoreSkillType.SKILL,
"experience", "level", "rank", "ehp"
);
overallRow.setBackground(ROW_COLORS[1]);
add(tableHeader);
add(overallRow);
for (int i = 0; i < SKILLS.size(); i++)
{
HiscoreSkill skill = SKILLS.get(i);
TableRow row = new TableRow(
skill.name(), skill.getName(), HiscoreSkillType.SKILL,
"experience", "level", "rank", "ehp"
);
row.setBackground(ROW_COLORS[i%2]);
tableRows.add(new RowPair(skill, row));
add(row);
}
}
public void update(PlayerInfo info)
{
if (info == null)
{
return;
}
Snapshot latestSnapshot = info.getLatestSnapshot();
for (RowPair rp : tableRows)
{
HiscoreSkill skill = rp.getSkill();
TableRow row = rp.getRow();
row.update(latestSnapshot.getData().getSkills().getSkill(skill), config.virtualLevels());
}
updateTotalLevel(latestSnapshot);
}
private void updateTotalLevel(Snapshot snapshot)
{
int totalLevel = 0;
Skill overall = snapshot.getData().getSkills().getSkill(OVERALL);
long overallExperience = overall.getExperience();
int overallRank = overall.getRank();
for (HiscoreSkill skill : SKILLS)
{
int experience = (int) snapshot.getData().getSkills().getSkill(skill).getExperience();
int level = experience >= 0 ? Experience.getLevelForXp(experience) : 0;
totalLevel += !config.virtualLevels() && level > Experience.MAX_REAL_LEVEL ? Experience.MAX_REAL_LEVEL : level;
}
JLabel expLabel = overallRow.labels.get("experience");
JLabel levelLabel = overallRow.labels.get("level");
JLabel rankLabel = overallRow.labels.get("rank");
JLabel ehpLabel = overallRow.labels.get("ehp");
| package net.wiseoldman.panel;
class SkillingPanel extends JPanel
{
/**
* Real skills, ordered in the way they should be displayed in the panel.
*/
private static final List<HiscoreSkill> SKILLS = ImmutableList.of(
ATTACK, DEFENCE, STRENGTH,
HITPOINTS, RANGED, PRAYER,
MAGIC, COOKING, WOODCUTTING,
FLETCHING, FISHING, FIREMAKING,
CRAFTING, SMITHING, MINING,
HERBLORE, AGILITY, THIEVING,
SLAYER, FARMING, RUNECRAFT,
HUNTER, CONSTRUCTION
);
static Color[] ROW_COLORS = {ColorScheme.DARKER_GRAY_COLOR, new Color(34, 34, 34)};
TableRow overallRow;
List<RowPair> tableRows = new ArrayList<>();
WomUtilsConfig config;
@Inject
private SkillingPanel(WomUtilsConfig config)
{
this.config = config;
setLayout(new GridLayout(0, 1));
StatsTableHeader tableHeader = new StatsTableHeader("skilling");
// Handle overall separately because it's special
overallRow = new TableRow(
OVERALL.name(), OVERALL.getName(), HiscoreSkillType.SKILL,
"experience", "level", "rank", "ehp"
);
overallRow.setBackground(ROW_COLORS[1]);
add(tableHeader);
add(overallRow);
for (int i = 0; i < SKILLS.size(); i++)
{
HiscoreSkill skill = SKILLS.get(i);
TableRow row = new TableRow(
skill.name(), skill.getName(), HiscoreSkillType.SKILL,
"experience", "level", "rank", "ehp"
);
row.setBackground(ROW_COLORS[i%2]);
tableRows.add(new RowPair(skill, row));
add(row);
}
}
public void update(PlayerInfo info)
{
if (info == null)
{
return;
}
Snapshot latestSnapshot = info.getLatestSnapshot();
for (RowPair rp : tableRows)
{
HiscoreSkill skill = rp.getSkill();
TableRow row = rp.getRow();
row.update(latestSnapshot.getData().getSkills().getSkill(skill), config.virtualLevels());
}
updateTotalLevel(latestSnapshot);
}
private void updateTotalLevel(Snapshot snapshot)
{
int totalLevel = 0;
Skill overall = snapshot.getData().getSkills().getSkill(OVERALL);
long overallExperience = overall.getExperience();
int overallRank = overall.getRank();
for (HiscoreSkill skill : SKILLS)
{
int experience = (int) snapshot.getData().getSkills().getSkill(skill).getExperience();
int level = experience >= 0 ? Experience.getLevelForXp(experience) : 0;
totalLevel += !config.virtualLevels() && level > Experience.MAX_REAL_LEVEL ? Experience.MAX_REAL_LEVEL : level;
}
JLabel expLabel = overallRow.labels.get("experience");
JLabel levelLabel = overallRow.labels.get("level");
JLabel rankLabel = overallRow.labels.get("rank");
JLabel ehpLabel = overallRow.labels.get("ehp");
| expLabel.setText(overallExperience >= 0 ? Format.formatNumber(overallExperience) : "--"); | 0 | 2023-10-09 14:23:06+00:00 | 8k |
PeytonPlayz595/c0.0.23a_01 | src/main/java/com/mojang/minecraft/player/Inventory.java | [
{
"identifier": "User",
"path": "src/main/java/com/mojang/minecraft/User.java",
"snippet": "public final class User {\n\tpublic static List creativeTiles;\n\tpublic String name;\n\tpublic String sessionId;\n\tpublic String mpPass;\n\n\tpublic User(String var1, String var2) {\n\t\tthis.name = var1;\n\t\t... | import com.mojang.minecraft.User;
import com.mojang.minecraft.level.tile.Tile; | 6,727 | package com.mojang.minecraft.player;
public final class Inventory {
public int[] slots = new int[9];
public int selectedSlot = 0;
public Inventory() {
for(int var1 = 0; var1 < 9; ++var1) { | package com.mojang.minecraft.player;
public final class Inventory {
public int[] slots = new int[9];
public int selectedSlot = 0;
public Inventory() {
for(int var1 = 0; var1 < 9; ++var1) { | this.slots[var1] = ((Tile)User.creativeTiles.get(var1)).id; | 1 | 2023-10-10 17:10:45+00:00 | 8k |
vaylor27/config | common/src/main/java/net/vakror/jamesconfig/config/config/performance/DefaultConfigPerformanceAnalyzer.java | [
{
"identifier": "Config",
"path": "common/src/main/java/net/vakror/jamesconfig/config/config/Config.java",
"snippet": "public abstract class Config {\n public abstract void generateDefaultConfig();\n\n @NotNull\n public abstract File getConfigDir();\n\n public abstract String getSubPath();\n... | import com.google.common.base.Stopwatch;
import net.vakror.jamesconfig.config.config.Config;
import net.vakror.jamesconfig.config.config.registry.multi_object.MultiObjectRegistryConfigImpl;
import net.vakror.jamesconfig.config.config.registry.single_object.SingleObjectRegistryConfigImpl;
import net.vakror.jamesconfig.config.config.setting.SettingConfigImpl;
import java.text.DecimalFormat;
import java.util.concurrent.TimeUnit; | 5,564 | package net.vakror.jamesconfig.config.config.performance;
public class DefaultConfigPerformanceAnalyzer implements IConfigPerformanceAnalyzer {
DecimalFormat format = new DecimalFormat("0.##");
public static final DefaultConfigPerformanceAnalyzer INSTANCE = new DefaultConfigPerformanceAnalyzer();
@Override
public String getPerformanceAnalysis(Config config) {
if (config instanceof MultiObjectRegistryConfigImpl multiObjectRegistryConfig) {
return getMultiObjectRegistryConfigAnalysis(multiObjectRegistryConfig); | package net.vakror.jamesconfig.config.config.performance;
public class DefaultConfigPerformanceAnalyzer implements IConfigPerformanceAnalyzer {
DecimalFormat format = new DecimalFormat("0.##");
public static final DefaultConfigPerformanceAnalyzer INSTANCE = new DefaultConfigPerformanceAnalyzer();
@Override
public String getPerformanceAnalysis(Config config) {
if (config instanceof MultiObjectRegistryConfigImpl multiObjectRegistryConfig) {
return getMultiObjectRegistryConfigAnalysis(multiObjectRegistryConfig); | } else if (config instanceof SingleObjectRegistryConfigImpl<?> singleObjectRegistryConfig) { | 2 | 2023-10-07 23:04:49+00:00 | 8k |
uku3lig/ukuwayplus | src/main/java/net/uku3lig/ukuway/UkuwayPlus.java | [
{
"identifier": "UkuwayConfig",
"path": "src/main/java/net/uku3lig/ukuway/config/UkuwayConfig.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\n@AllArgsConstructor\npublic class UkuwayConfig implements IConfig<UkuwayConfig> {\n private boolean hideCosmetics = false;\n private boolean discor... | import lombok.Getter;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.screen.ingame.GenericContainerScreen;
import net.minecraft.entity.EquipmentSlot;
import net.minecraft.entity.LivingEntity;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.uku3lig.ukulib.config.ConfigManager;
import net.uku3lig.ukuway.config.UkuwayConfig;
import net.uku3lig.ukuway.jukebox.Jukebox;
import net.uku3lig.ukuway.ui.FriendListManager;
import net.uku3lig.ukuway.ui.Shop;
import net.uku3lig.ukuway.ui.Wardrobe;
import net.uku3lig.ukuway.util.DiscordManager;
import net.uku3lig.ukuway.util.KeyboardManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Optional;
import java.util.function.Consumer; | 4,004 | package net.uku3lig.ukuway;
@Environment(EnvType.CLIENT)
public class UkuwayPlus implements ClientModInitializer {
@Getter
private static final ConfigManager<UkuwayConfig> manager = ConfigManager.create(UkuwayConfig.class, "ukuway-plus");
@Getter
private static final Logger logger = LoggerFactory.getLogger(UkuwayPlus.class);
@Getter
public static final Jukebox jukebox = new Jukebox();
@Getter | package net.uku3lig.ukuway;
@Environment(EnvType.CLIENT)
public class UkuwayPlus implements ClientModInitializer {
@Getter
private static final ConfigManager<UkuwayConfig> manager = ConfigManager.create(UkuwayConfig.class, "ukuway-plus");
@Getter
private static final Logger logger = LoggerFactory.getLogger(UkuwayPlus.class);
@Getter
public static final Jukebox jukebox = new Jukebox();
@Getter | public static final Shop shop = new Shop(); | 3 | 2023-10-07 00:02:04+00:00 | 8k |
YumiProject/yumi-gradle-licenser | src/main/java/dev/yumi/gradle/licenser/impl/LicenseHeader.java | [
{
"identifier": "YumiLicenserGradlePlugin",
"path": "src/main/java/dev/yumi/gradle/licenser/YumiLicenserGradlePlugin.java",
"snippet": "public class YumiLicenserGradlePlugin implements Plugin<Project> {\n\tpublic static final String LICENSE_TASK_SUFFIX = \"License\";\n\tpublic static final String CHECK_... | import dev.yumi.gradle.licenser.YumiLicenserGradlePlugin;
import dev.yumi.gradle.licenser.api.rule.HeaderFileContext;
import dev.yumi.gradle.licenser.api.rule.HeaderRule;
import org.gradle.api.Project;
import org.gradle.api.logging.Logger;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map; | 4,549 | /*
* Copyright 2023 Yumi Project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package dev.yumi.gradle.licenser.impl;
/**
* Represents the valid license headers for this project.
*
* @author LambdAurora
* @version 1.0.0
* @since 1.0.0
*/
public final class LicenseHeader {
private final List<HeaderRule> rules;
public LicenseHeader(HeaderRule... rules) {
this(new ArrayList<>(List.of(rules)));
}
public LicenseHeader(List<HeaderRule> rules) {
this.rules = rules;
}
/**
* {@return {@code true} if this license header is valid and can be used for validation, otherwise {@code false}}
*/
public boolean isValid() {
return !this.rules.isEmpty();
}
/**
* Adds a header rule.
*
* @param rule the rule to add
*/
public void addRule(HeaderRule rule) {
this.rules.add(rule);
}
/**
* Validates the given file.
*
* @param header the existing header
* @return a list of validation errors if there's any
*/
public @NotNull List<ValidationError> validate(@NotNull List<String> header) {
var errors = new ArrayList<ValidationError>();
for (var rule : this.rules) {
var result = rule.parseHeader(header);
if (result.error() != null) {
errors.add(new ValidationError(rule.getName(), result.error()));
} else {
return List.of();
}
}
return errors;
}
/**
* Formats the given file to contain the correct license header.
*
* @param project the project the file is in
* @param logger the logger
* @param path the path of the file
* @param readComment the read header comment if successful, or {@code null} otherwise
* @return {@code true} if files changed, otherwise {@code false}
*/
public @Nullable List<String> format(Project project, Logger logger, Path path, @Nullable List<String> readComment) {
List<String> newHeader = null;
if (readComment == null) { | /*
* Copyright 2023 Yumi Project
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
package dev.yumi.gradle.licenser.impl;
/**
* Represents the valid license headers for this project.
*
* @author LambdAurora
* @version 1.0.0
* @since 1.0.0
*/
public final class LicenseHeader {
private final List<HeaderRule> rules;
public LicenseHeader(HeaderRule... rules) {
this(new ArrayList<>(List.of(rules)));
}
public LicenseHeader(List<HeaderRule> rules) {
this.rules = rules;
}
/**
* {@return {@code true} if this license header is valid and can be used for validation, otherwise {@code false}}
*/
public boolean isValid() {
return !this.rules.isEmpty();
}
/**
* Adds a header rule.
*
* @param rule the rule to add
*/
public void addRule(HeaderRule rule) {
this.rules.add(rule);
}
/**
* Validates the given file.
*
* @param header the existing header
* @return a list of validation errors if there's any
*/
public @NotNull List<ValidationError> validate(@NotNull List<String> header) {
var errors = new ArrayList<ValidationError>();
for (var rule : this.rules) {
var result = rule.parseHeader(header);
if (result.error() != null) {
errors.add(new ValidationError(rule.getName(), result.error()));
} else {
return List.of();
}
}
return errors;
}
/**
* Formats the given file to contain the correct license header.
*
* @param project the project the file is in
* @param logger the logger
* @param path the path of the file
* @param readComment the read header comment if successful, or {@code null} otherwise
* @return {@code true} if files changed, otherwise {@code false}
*/
public @Nullable List<String> format(Project project, Logger logger, Path path, @Nullable List<String> readComment) {
List<String> newHeader = null;
if (readComment == null) { | if (YumiLicenserGradlePlugin.DEBUG_MODE) { | 0 | 2023-10-08 20:51:43+00:00 | 8k |
5152Alotobots/2024_Crescendo_Preseason | src/main/java/frc/robot/chargedup/commands/auto/basic/Auto_leftredescape_Cmd.java | [
{
"identifier": "Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj",
"path": "src/main/java/frc/robot/library/drivetrains/commands/Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj.java",
"snippet": "public class Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj extends CommandBase {\n /** Creates a new Cmd_SubSys_Dr... | import edu.wpi.first.wpilibj.DriverStation.Alliance;
import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;
import frc.robot.library.drivetrains.commands.Cmd_SubSys_DriveTrain_FollowPathPlanner_Traj;
import frc.robot.library.drivetrains.SubSys_DriveTrain;
import frc.robot.library.gyroscopes.pigeon2.SubSys_PigeonGyro; | 4,392 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.chargedup.commands.auto.basic;
/**
* *Link For PathPlanner
* *https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e64fa08ff8_0_6
*/
public class Auto_leftredescape_Cmd extends SequentialCommandGroup {
private final SubSys_DriveTrain m_DriveTrain; | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package frc.robot.chargedup.commands.auto.basic;
/**
* *Link For PathPlanner
* *https://docs.google.com/presentation/d/1xjYSI4KpbmGBUY-ZMf1nAFrXIoJo1tl-HHNl8LLqa1I/edit#slide=id.g1e64fa08ff8_0_6
*/
public class Auto_leftredescape_Cmd extends SequentialCommandGroup {
private final SubSys_DriveTrain m_DriveTrain; | private final SubSys_PigeonGyro m_pigeonGyro; | 2 | 2023-10-09 00:27:11+00:00 | 8k |
nexus3a/monitor-remote-agent | src/main/java/com/monitor/parser/onec/OneCTJ.java | [
{
"identifier": "Token",
"path": "src/main/java/com/monitor/parser/Token.java",
"snippet": "public class Token implements java.io.Serializable {\r\n\r\n /**\r\n * The version identifier for this Serializable class. Increment only if the <i>serialized</i> form of the class\r\n * changes.\r\n ... | import com.monitor.parser.Token;
import com.monitor.parser.ParseException;
import com.monitor.parser.ParserParameters;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | 4,138 | package com.monitor.parser.onec;
/*
* Copyright 2021 Aleksei Andreev
*
* 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.
*
*/
public class OneCTJ implements OneCTJConstants {
private final static long MICROSECONDS_TO_1970 = 62135596800000L * 1000L;
private final static byte[] ZEROES = "0000000".getBytes();
private final static byte CHR0 = '0';
private final static String SQL_PARAMETERS_PROP_MARKER = "\np_0:";
private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
private final static TimeZone TIME_ZONE = TimeZone.getTimeZone("GMT+0");
private final static String SQL_PARAMETERS_PROP_NAME = "Sql.p_N";
private final static String DATE_TIME_PROP_NAME = "dateTime";
private final static String START_DATE_TIME_PROP_NAME = "startDateTime";
private final static String ONLY_TIME_PROP_NAME = "onlyTime";
private final static String CONTEXT_LAST_LINE_PROP_NAME = "ContextLastLine";
private final static String TIMESTAMP_PROP_NAME = "timestamp";
private final static String LOCKS_PROP_NAME = "Locks";
private final static String LOCK_SPACE_NAME_PROP_NAME = "space";
private final static String LOCK_SPACE_TYPE_PROP_NAME = "type";
private final static String LOCK_SPACE_RECORDS_PROP_NAME = "records";
private final static String LOCK_SPACE_RECORDS_COUNT_PROP_NAME = "recordsCount";
private final static String LOCK_GRANULARITY_PROP_NAME = "granularity";
private static final Pattern UNPRINTABLE_PATTERN = Pattern.compile("[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD\\u10000-\\u10FFFF]");
static {
DATE_FORMAT.setTimeZone(TIME_ZONE);
}
private final OneCTJRecord logRecord0 = new OneCTJRecord();
private final OneCTJRecord logRecord1 = new OneCTJRecord();
private OneCTJRecord logRecord = logRecord1;
private OneCTJRecord readyLogRecord = logRecord0;
private long bytesRead;
private long readyBytesRead;
private final byte[] ms6 = new byte[6];
private String propertyName;
private String propertyValue;
protected long recordsCount = 0L;
private long perfomance = 0L;
private boolean v82format;
private String event;
private String year;
private String month;
private String day;
private String hours;
private String minutes;
private String seconds;
private String microseconds;
private String yyyyMMddhh;
private long microsecondsBase;
private long microsecondsValue;
private String sqlParametersPropValue;
private String lastLineParameterValue;
private ArrayList<HashMap<String, Object>> lockSpaces; // список наборов свойств пространств блокировки
private HashMap<String, Object> lockSpaceProps; // набор свойств текущего пространства блокировок
private ArrayList<HashMap<String, String>> lockRecords; // список записей блокировок (их свойств) для текущего пространства
private int lockRecordsCount; // количество записей блокировок (их свойств) для текущего пространства
private HashMap<String, String> lockRecordProps; // набор свойств текущей записи блокировки
private boolean includeLockRecords; // нужно ли собирать данные полей блокировки
public static void main(String args[]) throws Throwable {
/*
final OneCTJ parser = new OneCTJ();
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\20092816.DBMSSQL.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21112514.DBMSSQL.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21120914.EXCP.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21121011.SDBL.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21121011.TDEADLOCK.log"), "UTF-8");
// System.out.println("perfomance: " + parser.getPerfomance());
// System.out.println("records: " + parser.getRecordsCount());
*/
System.out.println("test = " + DATE_FORMAT.format(new Date((63827362557274001L - MICROSECONDS_TO_1970 - 999983) / 1000L)));
final OneCTJ parser = new OneCTJ();
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\L70\\00000001.log"),
"UTF-8", | package com.monitor.parser.onec;
/*
* Copyright 2021 Aleksei Andreev
*
* 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.
*
*/
public class OneCTJ implements OneCTJConstants {
private final static long MICROSECONDS_TO_1970 = 62135596800000L * 1000L;
private final static byte[] ZEROES = "0000000".getBytes();
private final static byte CHR0 = '0';
private final static String SQL_PARAMETERS_PROP_MARKER = "\np_0:";
private final static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
private final static TimeZone TIME_ZONE = TimeZone.getTimeZone("GMT+0");
private final static String SQL_PARAMETERS_PROP_NAME = "Sql.p_N";
private final static String DATE_TIME_PROP_NAME = "dateTime";
private final static String START_DATE_TIME_PROP_NAME = "startDateTime";
private final static String ONLY_TIME_PROP_NAME = "onlyTime";
private final static String CONTEXT_LAST_LINE_PROP_NAME = "ContextLastLine";
private final static String TIMESTAMP_PROP_NAME = "timestamp";
private final static String LOCKS_PROP_NAME = "Locks";
private final static String LOCK_SPACE_NAME_PROP_NAME = "space";
private final static String LOCK_SPACE_TYPE_PROP_NAME = "type";
private final static String LOCK_SPACE_RECORDS_PROP_NAME = "records";
private final static String LOCK_SPACE_RECORDS_COUNT_PROP_NAME = "recordsCount";
private final static String LOCK_GRANULARITY_PROP_NAME = "granularity";
private static final Pattern UNPRINTABLE_PATTERN = Pattern.compile("[^\\u0009\\u000A\\u000D\\u0020-\\uD7FF\\uE000-\\uFFFD\\u10000-\\u10FFFF]");
static {
DATE_FORMAT.setTimeZone(TIME_ZONE);
}
private final OneCTJRecord logRecord0 = new OneCTJRecord();
private final OneCTJRecord logRecord1 = new OneCTJRecord();
private OneCTJRecord logRecord = logRecord1;
private OneCTJRecord readyLogRecord = logRecord0;
private long bytesRead;
private long readyBytesRead;
private final byte[] ms6 = new byte[6];
private String propertyName;
private String propertyValue;
protected long recordsCount = 0L;
private long perfomance = 0L;
private boolean v82format;
private String event;
private String year;
private String month;
private String day;
private String hours;
private String minutes;
private String seconds;
private String microseconds;
private String yyyyMMddhh;
private long microsecondsBase;
private long microsecondsValue;
private String sqlParametersPropValue;
private String lastLineParameterValue;
private ArrayList<HashMap<String, Object>> lockSpaces; // список наборов свойств пространств блокировки
private HashMap<String, Object> lockSpaceProps; // набор свойств текущего пространства блокировок
private ArrayList<HashMap<String, String>> lockRecords; // список записей блокировок (их свойств) для текущего пространства
private int lockRecordsCount; // количество записей блокировок (их свойств) для текущего пространства
private HashMap<String, String> lockRecordProps; // набор свойств текущей записи блокировки
private boolean includeLockRecords; // нужно ли собирать данные полей блокировки
public static void main(String args[]) throws Throwable {
/*
final OneCTJ parser = new OneCTJ();
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\20092816.DBMSSQL.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21112514.DBMSSQL.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21120914.EXCP.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21121011.SDBL.log"), "UTF-8");
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\21121011.TDEADLOCK.log"), "UTF-8");
// System.out.println("perfomance: " + parser.getPerfomance());
// System.out.println("records: " + parser.getRecordsCount());
*/
System.out.println("test = " + DATE_FORMAT.format(new Date((63827362557274001L - MICROSECONDS_TO_1970 - 999983) / 1000L)));
final OneCTJ parser = new OneCTJ();
parser.parse(new File("d:\\java\\projects\\monitor-remote-agent\\src\\test\\logs\\L70\\00000001.log"),
"UTF-8", | new ParserParameters()); | 2 | 2023-10-11 20:25:12+00:00 | 8k |
mhaupt/basicode | src/main/java/de/haupz/basicode/ast/ExpressionNode.java | [
{
"identifier": "InterpreterState",
"path": "src/main/java/de/haupz/basicode/interpreter/InterpreterState.java",
"snippet": "public class InterpreterState {\n\n /**\n * The root node of the program whose state this instance represents.\n */\n private final ProgramNode program;\n\n /**\n... | import de.haupz.basicode.interpreter.InterpreterState;
import de.haupz.basicode.parser.Token;
import java.util.List; | 5,382 | package de.haupz.basicode.ast;
/**
* The super class of all AST nodes representing BASICODE expressions. It overrides
* {@link BasicNode#run(InterpreterState)} to throw an exception, as this method will not be used in the entire
* hierarchy.
*/
public abstract class ExpressionNode extends BasicNode {
@Override | package de.haupz.basicode.ast;
/**
* The super class of all AST nodes representing BASICODE expressions. It overrides
* {@link BasicNode#run(InterpreterState)} to throw an exception, as this method will not be used in the entire
* hierarchy.
*/
public abstract class ExpressionNode extends BasicNode {
@Override | public final void run(InterpreterState state) { | 0 | 2023-10-14 12:20:59+00:00 | 8k |
Thenuka22/BakerySalesnOrdering_System | BakeryPosSystem/src/bakerypossystem/Model/Menu.java | [
{
"identifier": "Bottom",
"path": "BakeryPosSystem/src/bakerypossystem/Model/Bottom.java",
"snippet": "public class Bottom extends javax.swing.JPanel {\n\n public void setAlpha(float alpha) {\n this.alpha = alpha;\n }\n\n private float alpha;\n\n public Bottom() {\n initCompone... | import bakerypossystem.Model.Bottom;
import bakerypossystem.Model.Header;
import bakerypossystem.Controller.EventMenuSelected;
import bakerypossystem.Controller.MenuController;
import bakerypossystem.Controller.MenuController;
import CustomComponents.ButtonCustom;
import CustomComponents.ButtonCustom;
import bakerypossystem.Controller.EventMenuSelected;
import bakerypossystem.Controller.MenuItem;
import bakerypossystem.Controller.MenuItem;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout; | 4,286 | package bakerypossystem.Model;
public class Menu extends javax.swing.JPanel {
public void setEvent(EventMenuSelected event) {
this.event = event;
}
private MigLayout layout;
private JPanel panelMenu;
private JButton cmdMenu;
private JButton cmdLogOut;
private Header header;
private Bottom bottom;
private EventMenuSelected event;
public Menu() {
initComponents();
setOpaque(false);
init();
}
private void init() {
setLayout(new MigLayout("wrap, fillx, insets 0", "[fill]", "5[]0[]push[60]0"));
panelMenu = new JPanel();
header = new Header();
bottom = new Bottom();
createButtonMenu();
createButtonLogout();
panelMenu.setOpaque(false);
layout = new MigLayout("fillx, wrap", "0[fill]0", "0[]3[]0");
panelMenu.setLayout(layout);
add(cmdMenu, "pos 1al 0al 100% 50");
add(cmdLogOut, "pos 1al 1al 100% 100, height 60!");
add(header);
add(panelMenu);
add(bottom);
}
public void addMenu(MenuController menu) {
MenuItem item = new MenuItem(menu.getIcon(), menu.getMenuName(), panelMenu.getComponentCount());
item.addEvent(new EventMenuSelected() {
@Override
public void selected(int index) {
clearMenu(index);
}
});
item.addEvent(event);
panelMenu.add(item);
}
private void createButtonMenu() {
cmdMenu = new JButton();
cmdMenu.setContentAreaFilled(false);
cmdMenu.setCursor(new Cursor(Cursor.HAND_CURSOR));
cmdMenu.setIcon(new ImageIcon(getClass().getResource("/icon/menu.png")));
cmdMenu.setBorder(new EmptyBorder(5, 12, 5, 12));
}
private void createButtonLogout() { | package bakerypossystem.Model;
public class Menu extends javax.swing.JPanel {
public void setEvent(EventMenuSelected event) {
this.event = event;
}
private MigLayout layout;
private JPanel panelMenu;
private JButton cmdMenu;
private JButton cmdLogOut;
private Header header;
private Bottom bottom;
private EventMenuSelected event;
public Menu() {
initComponents();
setOpaque(false);
init();
}
private void init() {
setLayout(new MigLayout("wrap, fillx, insets 0", "[fill]", "5[]0[]push[60]0"));
panelMenu = new JPanel();
header = new Header();
bottom = new Bottom();
createButtonMenu();
createButtonLogout();
panelMenu.setOpaque(false);
layout = new MigLayout("fillx, wrap", "0[fill]0", "0[]3[]0");
panelMenu.setLayout(layout);
add(cmdMenu, "pos 1al 0al 100% 50");
add(cmdLogOut, "pos 1al 1al 100% 100, height 60!");
add(header);
add(panelMenu);
add(bottom);
}
public void addMenu(MenuController menu) {
MenuItem item = new MenuItem(menu.getIcon(), menu.getMenuName(), panelMenu.getComponentCount());
item.addEvent(new EventMenuSelected() {
@Override
public void selected(int index) {
clearMenu(index);
}
});
item.addEvent(event);
panelMenu.add(item);
}
private void createButtonMenu() {
cmdMenu = new JButton();
cmdMenu.setContentAreaFilled(false);
cmdMenu.setCursor(new Cursor(Cursor.HAND_CURSOR));
cmdMenu.setIcon(new ImageIcon(getClass().getResource("/icon/menu.png")));
cmdMenu.setBorder(new EmptyBorder(5, 12, 5, 12));
}
private void createButtonLogout() { | cmdLogOut = new ButtonCustom(); | 6 | 2023-10-11 16:55:32+00:00 | 8k |
giteecode/bookmanage2-public | nhXJH-admin/src/main/java/com/nhXJH/web/domain/BaseDeptAuthority.java | [
{
"identifier": "SysDept",
"path": "nhXJH-common/src/main/java/com/nhXJH/common/core/domain/entity/SysDept.java",
"snippet": "public class SysDept extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /** 部门ID */\n private Long deptId;\n\n /** 父部门ID */\n private Long... | import com.nhXJH.common.annotation.Excels;
import com.nhXJH.common.core.domain.entity.SysDept;
import com.nhXJH.common.core.domain.entity.SysUser;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import com.nhXJH.common.annotation.Excel;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.nhXJH.common.annotation.Excel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.springframework.data.annotation.Id;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import com.nhXJH.common.core.domain.BaseEntity; | 3,927 | package com.nhXJH.web.domain;
/**
* 用户可访问部门信息对象 base_dept_authority
*
* @author xjh
* @date 2022-02-27
*/
@TableName("base_dept_authority")
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class BaseDeptAuthority extends BaseEntity {
private static final long serialVersionUID = 1L;
/** 主键 */
@TableId(value = "id", type = IdType.ASSIGN_ID)
@ApiModelProperty("id")
private Long id;
/** 部门id */
// @Excel(name = "部门id")
@ApiModelProperty("部门id")
private Long deptId;
@Excels({
@Excel(name = "可访问部门",targetAttr = "deptName",type = Excel.Type.EXPORT)
})
private SysDept dept;
/** 用户id */
// @Excel(name = "用户id")
@ApiModelProperty("用户id")
private Long userId;
@Excels({
@Excel(name = "用户名",targetAttr = "userName",type = Excel.Type.EXPORT)
}) | package com.nhXJH.web.domain;
/**
* 用户可访问部门信息对象 base_dept_authority
*
* @author xjh
* @date 2022-02-27
*/
@TableName("base_dept_authority")
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class BaseDeptAuthority extends BaseEntity {
private static final long serialVersionUID = 1L;
/** 主键 */
@TableId(value = "id", type = IdType.ASSIGN_ID)
@ApiModelProperty("id")
private Long id;
/** 部门id */
// @Excel(name = "部门id")
@ApiModelProperty("部门id")
private Long deptId;
@Excels({
@Excel(name = "可访问部门",targetAttr = "deptName",type = Excel.Type.EXPORT)
})
private SysDept dept;
/** 用户id */
// @Excel(name = "用户id")
@ApiModelProperty("用户id")
private Long userId;
@Excels({
@Excel(name = "用户名",targetAttr = "userName",type = Excel.Type.EXPORT)
}) | private SysUser sysUser; | 1 | 2023-10-13 07:19:20+00:00 | 8k |
M-D-Team/ait-fabric-1.20.1 | src/main/java/mdteam/ait/core/item/ArtronCollectorItem.java | [
{
"identifier": "ConsoleBlockEntity",
"path": "src/main/java/mdteam/ait/core/blockentities/ConsoleBlockEntity.java",
"snippet": "public class ConsoleBlockEntity extends BlockEntity implements BlockEntityTicker<ConsoleBlockEntity> {\n public final AnimationState ANIM_FLIGHT = new AnimationState();\n ... | import mdteam.ait.core.blockentities.ConsoleBlockEntity;
import mdteam.ait.core.blockentities.ExteriorBlockEntity;
import mdteam.ait.core.interfaces.RiftChunk;
import mdteam.ait.core.managers.DeltaTimeManager;
import net.minecraft.block.Block;
import net.minecraft.client.item.TooltipContext;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUsageContext;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.text.Text;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Formatting;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.UUID; | 5,959 | package mdteam.ait.core.item;
public class ArtronCollectorItem extends Item {
public static final String AU_LEVEL = "au_level";
public static final String UUID_KEY = "uuid";
public static final Integer COLLECTOR_MAX_FUEL = 1500;
public ArtronCollectorItem(Settings settings) {
super(settings);
}
@Override
public ItemStack getDefaultStack() {
ItemStack stack = new ItemStack(this);
NbtCompound nbt = stack.getOrCreateNbt();
nbt.putDouble(AU_LEVEL, 0);
return super.getDefaultStack();
}
@Override
public void inventoryTick(ItemStack stack, World world, Entity entity, int slot, boolean selected) {
if(world.isClient()) return;
if (!(entity instanceof ServerPlayerEntity) || !selected) return;
| package mdteam.ait.core.item;
public class ArtronCollectorItem extends Item {
public static final String AU_LEVEL = "au_level";
public static final String UUID_KEY = "uuid";
public static final Integer COLLECTOR_MAX_FUEL = 1500;
public ArtronCollectorItem(Settings settings) {
super(settings);
}
@Override
public ItemStack getDefaultStack() {
ItemStack stack = new ItemStack(this);
NbtCompound nbt = stack.getOrCreateNbt();
nbt.putDouble(AU_LEVEL, 0);
return super.getDefaultStack();
}
@Override
public void inventoryTick(ItemStack stack, World world, Entity entity, int slot, boolean selected) {
if(world.isClient()) return;
if (!(entity instanceof ServerPlayerEntity) || !selected) return;
| RiftChunk riftChunk = (RiftChunk) world.getChunk(entity.getBlockPos()); | 2 | 2023-10-08 00:38:53+00:00 | 8k |
jianjian3219/044_bookmanage2-public | nhXJH-admin/src/main/java/com/nhXJH/web/domain/vo/BookShelfVO.java | [
{
"identifier": "SysDept",
"path": "nhXJH-common/src/main/java/com/nhXJH/common/core/domain/entity/SysDept.java",
"snippet": "public class SysDept extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n /** 部门ID */\n private Long deptId;\n\n /** 父部门ID */\n private Long... | import com.nhXJH.common.core.domain.entity.SysDept;
import com.nhXJH.common.core.domain.entity.SysUser;
import com.nhXJH.system.domain.po.BaseBookClassCn;
import com.nhXJH.web.domain.StockBookshelf;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor; | 4,937 | package com.nhXJH.web.domain.vo;
/**
* Created by IntelliJ IDEA.
* User: xjh
* Date: 2022/2/22
* Time: 10:07
* 图书书架返回结果实体
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookShelfVO extends StockBookshelf {
SysUser createUser;
SysUser updateUser;
SysDept sysDept; | package com.nhXJH.web.domain.vo;
/**
* Created by IntelliJ IDEA.
* User: xjh
* Date: 2022/2/22
* Time: 10:07
* 图书书架返回结果实体
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BookShelfVO extends StockBookshelf {
SysUser createUser;
SysUser updateUser;
SysDept sysDept; | BaseBookClassCn bookClassCn; | 2 | 2023-10-14 04:57:42+00:00 | 8k |
aleksandarsusnjar/paniql | core/src/main/java/net/susnjar/paniql/models/InterfaceModel.java | [
{
"identifier": "Environment",
"path": "core/src/main/java/net/susnjar/paniql/Environment.java",
"snippet": "public class Environment {\n private static final String SCHEMA_SEPARATOR = System.lineSeparator() + System.lineSeparator();\n\n private final TypeDefinitionRegistry typeRegistry;\n\n pr... | import graphql.language.InterfaceTypeDefinition;
import graphql.language.InterfaceTypeExtensionDefinition;
import graphql.language.Type;
import graphql.language.TypeName;
import net.susnjar.paniql.Environment;
import net.susnjar.paniql.pricing.Bounds;
import net.susnjar.paniql.pricing.BoundsCollector; | 4,167 | package net.susnjar.paniql.models;
public class InterfaceModel extends FieldContainerModel<InterfaceTypeDefinition, InterfaceTypeExtensionDefinition> {
public InterfaceModel(Environment environment, InterfaceTypeDefinition definition) {
super(environment, definition);
}
@Override | package net.susnjar.paniql.models;
public class InterfaceModel extends FieldContainerModel<InterfaceTypeDefinition, InterfaceTypeExtensionDefinition> {
public InterfaceModel(Environment environment, InterfaceTypeDefinition definition) {
super(environment, definition);
}
@Override | protected Bounds getDefaultCardinality() { | 1 | 2023-10-10 01:58:56+00:00 | 8k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.